]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kfileitemmodel.cpp
Ensure that the "Sort by Type" setting is respected
[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 #include <algorithm>
37 #include <vector>
38
39 // #define KFILEITEMMODEL_DEBUG
40
41 KFileItemModel::KFileItemModel(QObject* parent) :
42 KItemModelBase("text", parent),
43 m_dirLister(0),
44 m_naturalSorting(KGlobalSettings::naturalSorting()),
45 m_sortDirsFirst(true),
46 m_sortRole(NameRole),
47 m_sortingProgressPercent(-1),
48 m_roles(),
49 m_caseSensitivity(Qt::CaseInsensitive),
50 m_itemData(),
51 m_items(),
52 m_filter(),
53 m_filteredItems(),
54 m_requestRole(),
55 m_maximumUpdateIntervalTimer(0),
56 m_resortAllItemsTimer(0),
57 m_pendingItemsToInsert(),
58 m_groups(),
59 m_expandedParentsCountRoot(UninitializedExpandedParentsCountRoot),
60 m_expandedDirs(),
61 m_urlsToExpand()
62 {
63 m_dirLister = new KFileItemModelDirLister(this);
64 m_dirLister->setAutoUpdate(true);
65 m_dirLister->setDelayedMimeTypes(true);
66
67 const QWidget* parentWidget = qobject_cast<QWidget*>(parent);
68 if (parentWidget) {
69 m_dirLister->setMainWindow(parentWidget->window());
70 }
71
72 connect(m_dirLister, SIGNAL(started(KUrl)), this, SIGNAL(directoryLoadingStarted()));
73 connect(m_dirLister, SIGNAL(canceled()), this, SLOT(slotCanceled()));
74 connect(m_dirLister, SIGNAL(completed(KUrl)), this, SLOT(slotCompleted()));
75 connect(m_dirLister, SIGNAL(newItems(KFileItemList)), this, SLOT(slotNewItems(KFileItemList)));
76 connect(m_dirLister, SIGNAL(itemsDeleted(KFileItemList)), this, SLOT(slotItemsDeleted(KFileItemList)));
77 connect(m_dirLister, SIGNAL(refreshItems(QList<QPair<KFileItem,KFileItem> >)), this, SLOT(slotRefreshItems(QList<QPair<KFileItem,KFileItem> >)));
78 connect(m_dirLister, SIGNAL(clear()), this, SLOT(slotClear()));
79 connect(m_dirLister, SIGNAL(clear(KUrl)), this, SLOT(slotClear(KUrl)));
80 connect(m_dirLister, SIGNAL(infoMessage(QString)), this, SIGNAL(infoMessage(QString)));
81 connect(m_dirLister, SIGNAL(errorMessage(QString)), this, SIGNAL(errorMessage(QString)));
82 connect(m_dirLister, SIGNAL(redirection(KUrl,KUrl)), this, SIGNAL(directoryRedirection(KUrl,KUrl)));
83 connect(m_dirLister, SIGNAL(urlIsFileError(KUrl)), this, SIGNAL(urlIsFileError(KUrl)));
84
85 // Apply default roles that should be determined
86 resetRoles();
87 m_requestRole[NameRole] = true;
88 m_requestRole[IsDirRole] = true;
89 m_requestRole[IsLinkRole] = true;
90 m_roles.insert("text");
91 m_roles.insert("isDir");
92 m_roles.insert("isLink");
93
94 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
95 // before the completed() or canceled() signal has been emitted.
96 m_maximumUpdateIntervalTimer = new QTimer(this);
97 m_maximumUpdateIntervalTimer->setInterval(2000);
98 m_maximumUpdateIntervalTimer->setSingleShot(true);
99 connect(m_maximumUpdateIntervalTimer, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
100
101 // When changing the value of an item which represents the sort-role a resorting must be
102 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
103 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
104 // resorting is postponed until the timer has been exceeded.
105 m_resortAllItemsTimer = new QTimer(this);
106 m_resortAllItemsTimer->setInterval(500);
107 m_resortAllItemsTimer->setSingleShot(true);
108 connect(m_resortAllItemsTimer, SIGNAL(timeout()), this, SLOT(resortAllItems()));
109
110 connect(KGlobalSettings::self(), SIGNAL(naturalSortingChanged()), this, SLOT(slotNaturalSortingChanged()));
111 }
112
113 KFileItemModel::~KFileItemModel()
114 {
115 qDeleteAll(m_itemData);
116 m_itemData.clear();
117 }
118
119 void KFileItemModel::loadDirectory(const KUrl& url)
120 {
121 m_dirLister->openUrl(url);
122 }
123
124 void KFileItemModel::refreshDirectory(const KUrl& url)
125 {
126 // Refresh all expanded directories first (Bug 295300)
127 foreach (const KUrl& expandedUrl, m_expandedDirs) {
128 m_dirLister->openUrl(expandedUrl, KDirLister::Reload);
129 }
130
131 m_dirLister->openUrl(url, KDirLister::Reload);
132 }
133
134 KUrl KFileItemModel::directory() const
135 {
136 return m_dirLister->url();
137 }
138
139 void KFileItemModel::cancelDirectoryLoading()
140 {
141 m_dirLister->stop();
142 }
143
144 int KFileItemModel::count() const
145 {
146 return m_itemData.count();
147 }
148
149 QHash<QByteArray, QVariant> KFileItemModel::data(int index) const
150 {
151 if (index >= 0 && index < count()) {
152 return m_itemData.at(index)->values;
153 }
154 return QHash<QByteArray, QVariant>();
155 }
156
157 bool KFileItemModel::setData(int index, const QHash<QByteArray, QVariant>& values)
158 {
159 if (index < 0 || index >= count()) {
160 return false;
161 }
162
163 QHash<QByteArray, QVariant> currentValues = m_itemData.at(index)->values;
164
165 // Determine which roles have been changed
166 QSet<QByteArray> changedRoles;
167 QHashIterator<QByteArray, QVariant> it(values);
168 while (it.hasNext()) {
169 it.next();
170 const QByteArray role = it.key();
171 const QVariant value = it.value();
172
173 if (currentValues[role] != value) {
174 currentValues[role] = value;
175 changedRoles.insert(role);
176 }
177 }
178
179 if (changedRoles.isEmpty()) {
180 return false;
181 }
182
183 m_itemData[index]->values = currentValues;
184 if (changedRoles.contains("text")) {
185 KUrl url = m_itemData[index]->item.url();
186 url.setFileName(currentValues["text"].toString());
187 m_itemData[index]->item.setUrl(url);
188 }
189
190 emit itemsChanged(KItemRangeList() << KItemRange(index, 1), changedRoles);
191
192 if (changedRoles.contains(sortRole())) {
193 m_resortAllItemsTimer->start();
194 }
195
196 return true;
197 }
198
199 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst)
200 {
201 if (dirsFirst != m_sortDirsFirst) {
202 m_sortDirsFirst = dirsFirst;
203 resortAllItems();
204 }
205 }
206
207 bool KFileItemModel::sortDirectoriesFirst() const
208 {
209 return m_sortDirsFirst;
210 }
211
212 void KFileItemModel::setShowHiddenFiles(bool show)
213 {
214 m_dirLister->setShowingDotFiles(show);
215 m_dirLister->emitChanges();
216 if (show) {
217 slotCompleted();
218 }
219 }
220
221 bool KFileItemModel::showHiddenFiles() const
222 {
223 return m_dirLister->showingDotFiles();
224 }
225
226 void KFileItemModel::setShowDirectoriesOnly(bool enabled)
227 {
228 m_dirLister->setDirOnlyMode(enabled);
229 }
230
231 bool KFileItemModel::showDirectoriesOnly() const
232 {
233 return m_dirLister->dirOnlyMode();
234 }
235
236 QMimeData* KFileItemModel::createMimeData(const QSet<int>& indexes) const
237 {
238 QMimeData* data = new QMimeData();
239
240 // The following code has been taken from KDirModel::mimeData()
241 // (kdelibs/kio/kio/kdirmodel.cpp)
242 // Copyright (C) 2006 David Faure <faure@kde.org>
243 KUrl::List urls;
244 KUrl::List mostLocalUrls;
245 bool canUseMostLocalUrls = true;
246
247 QSetIterator<int> it(indexes);
248 while (it.hasNext()) {
249 const int index = it.next();
250 const KFileItem item = fileItem(index);
251 if (!item.isNull()) {
252 urls << item.url();
253
254 bool isLocal;
255 mostLocalUrls << item.mostLocalUrl(isLocal);
256 if (!isLocal) {
257 canUseMostLocalUrls = false;
258 }
259 }
260 }
261
262 const bool different = canUseMostLocalUrls && mostLocalUrls != urls;
263 urls = KDirModel::simplifiedUrlList(urls); // TODO: Check if we still need KDirModel for this in KDE 5.0
264 if (different) {
265 mostLocalUrls = KDirModel::simplifiedUrlList(mostLocalUrls);
266 urls.populateMimeData(mostLocalUrls, data);
267 } else {
268 urls.populateMimeData(data);
269 }
270
271 return data;
272 }
273
274 int KFileItemModel::indexForKeyboardSearch(const QString& text, int startFromIndex) const
275 {
276 startFromIndex = qMax(0, startFromIndex);
277 for (int i = startFromIndex; i < count(); ++i) {
278 if (data(i)["text"].toString().startsWith(text, Qt::CaseInsensitive)) {
279 return i;
280 }
281 }
282 for (int i = 0; i < startFromIndex; ++i) {
283 if (data(i)["text"].toString().startsWith(text, Qt::CaseInsensitive)) {
284 return i;
285 }
286 }
287 return -1;
288 }
289
290 bool KFileItemModel::supportsDropping(int index) const
291 {
292 const KFileItem item = fileItem(index);
293 return !item.isNull() && (item.isDir() || item.isDesktopFile());
294 }
295
296 QString KFileItemModel::roleDescription(const QByteArray& role) const
297 {
298 static QHash<QByteArray, QString> description;
299 if (description.isEmpty()) {
300 int count = 0;
301 const RoleInfoMap* map = rolesInfoMap(count);
302 for (int i = 0; i < count; ++i) {
303 description.insert(map[i].role, i18nc(map[i].roleTranslationContext, map[i].roleTranslation));
304 }
305 }
306
307 return description.value(role);
308 }
309
310 QList<QPair<int, QVariant> > KFileItemModel::groups() const
311 {
312 if (!m_itemData.isEmpty() && m_groups.isEmpty()) {
313 #ifdef KFILEITEMMODEL_DEBUG
314 QElapsedTimer timer;
315 timer.start();
316 #endif
317 switch (typeForRole(sortRole())) {
318 case NameRole: m_groups = nameRoleGroups(); break;
319 case SizeRole: m_groups = sizeRoleGroups(); break;
320 case DateRole: m_groups = dateRoleGroups(); break;
321 case PermissionsRole: m_groups = permissionRoleGroups(); break;
322 case RatingRole: m_groups = ratingRoleGroups(); break;
323 default: m_groups = genericStringRoleGroups(sortRole()); break;
324 }
325
326 #ifdef KFILEITEMMODEL_DEBUG
327 kDebug() << "[TIME] Calculating groups for" << count() << "items:" << timer.elapsed();
328 #endif
329 }
330
331 return m_groups;
332 }
333
334 KFileItem KFileItemModel::fileItem(int index) const
335 {
336 if (index >= 0 && index < count()) {
337 return m_itemData.at(index)->item;
338 }
339
340 return KFileItem();
341 }
342
343 KFileItem KFileItemModel::fileItem(const KUrl& url) const
344 {
345 const int index = m_items.value(url, -1);
346 if (index >= 0) {
347 return m_itemData.at(index)->item;
348 }
349 return KFileItem();
350 }
351
352 int KFileItemModel::index(const KFileItem& item) const
353 {
354 if (item.isNull()) {
355 return -1;
356 }
357
358 return m_items.value(item.url(), -1);
359 }
360
361 int KFileItemModel::index(const KUrl& url) const
362 {
363 KUrl urlToFind = url;
364 urlToFind.adjustPath(KUrl::RemoveTrailingSlash);
365 return m_items.value(urlToFind, -1);
366 }
367
368 KFileItem KFileItemModel::rootItem() const
369 {
370 return m_dirLister->rootItem();
371 }
372
373 void KFileItemModel::clear()
374 {
375 slotClear();
376 }
377
378 void KFileItemModel::setRoles(const QSet<QByteArray>& roles)
379 {
380 if (m_roles == roles) {
381 return;
382 }
383 m_roles = roles;
384
385 if (count() > 0) {
386 const bool supportedExpanding = m_requestRole[ExpandedParentsCountRole];
387 const bool willSupportExpanding = roles.contains("expandedParentsCount");
388 if (supportedExpanding && !willSupportExpanding) {
389 // No expanding is supported anymore. Take care to delete all items that have an expansion level
390 // that is not 0 (and hence are part of an expanded item).
391 removeExpandedItems();
392 }
393 }
394
395 m_groups.clear();
396 resetRoles();
397
398 QSetIterator<QByteArray> it(roles);
399 while (it.hasNext()) {
400 const QByteArray& role = it.next();
401 m_requestRole[typeForRole(role)] = true;
402 }
403
404 if (count() > 0) {
405 // Update m_data with the changed requested roles
406 const int maxIndex = count() - 1;
407 for (int i = 0; i <= maxIndex; ++i) {
408 m_itemData[i]->values = retrieveData(m_itemData.at(i)->item);
409 }
410
411 kWarning() << "TODO: Emitting itemsChanged() with no information what has changed!";
412 emit itemsChanged(KItemRangeList() << KItemRange(0, count()), QSet<QByteArray>());
413 }
414 }
415
416 QSet<QByteArray> KFileItemModel::roles() const
417 {
418 return m_roles;
419 }
420
421 bool KFileItemModel::setExpanded(int index, bool expanded)
422 {
423 if (!isExpandable(index) || isExpanded(index) == expanded) {
424 return false;
425 }
426
427 QHash<QByteArray, QVariant> values;
428 values.insert("isExpanded", expanded);
429 if (!setData(index, values)) {
430 return false;
431 }
432
433 const KUrl url = m_itemData.at(index)->item.url();
434 if (expanded) {
435 m_expandedDirs.insert(url);
436 m_dirLister->openUrl(url, KDirLister::Keep);
437 } else {
438 m_expandedDirs.remove(url);
439 m_dirLister->stop(url);
440
441
442 KFileItemList itemsToRemove;
443 const int expandedParentsCount = data(index)["expandedParentsCount"].toInt();
444 ++index;
445 while (index < count() && data(index)["expandedParentsCount"].toInt() > expandedParentsCount) {
446 itemsToRemove.append(m_itemData.at(index)->item);
447 ++index;
448 }
449
450 QSet<KUrl> urlsToRemove;
451 urlsToRemove.reserve(itemsToRemove.count() + 1);
452 urlsToRemove.insert(url);
453 foreach (const KFileItem& item, itemsToRemove) {
454 KUrl url = item.url();
455 url.adjustPath(KUrl::RemoveTrailingSlash);
456 urlsToRemove.insert(url);
457 }
458
459 QSet<KFileItem>::iterator it = m_filteredItems.begin();
460 while (it != m_filteredItems.end()) {
461 const KUrl url = it->url();
462 KUrl parentUrl = url.upUrl();
463 parentUrl.adjustPath(KUrl::RemoveTrailingSlash);
464
465 if (urlsToRemove.contains(parentUrl)) {
466 it = m_filteredItems.erase(it);
467 } else {
468 ++it;
469 }
470 }
471
472 removeItems(itemsToRemove);
473 }
474
475 return true;
476 }
477
478 bool KFileItemModel::isExpanded(int index) const
479 {
480 if (index >= 0 && index < count()) {
481 return m_itemData.at(index)->values.value("isExpanded").toBool();
482 }
483 return false;
484 }
485
486 bool KFileItemModel::isExpandable(int index) const
487 {
488 if (index >= 0 && index < count()) {
489 return m_itemData.at(index)->values.value("isExpandable").toBool();
490 }
491 return false;
492 }
493
494 int KFileItemModel::expandedParentsCount(int index) const
495 {
496 if (index >= 0 && index < count()) {
497 const int parentsCount = m_itemData.at(index)->values.value("expandedParentsCount").toInt();
498 if (parentsCount > 0) {
499 return parentsCount;
500 }
501 }
502 return 0;
503 }
504
505 QSet<KUrl> KFileItemModel::expandedDirectories() const
506 {
507 return m_expandedDirs;
508 }
509
510 void KFileItemModel::restoreExpandedDirectories(const QSet<KUrl>& urls)
511 {
512 m_urlsToExpand = urls;
513 }
514
515 void KFileItemModel::expandParentDirectories(const KUrl& url)
516 {
517 const int pos = m_dirLister->url().path().length();
518
519 // Assure that each sub-path of the URL that should be
520 // expanded is added to m_urlsToExpand. KDirLister
521 // does not care whether the parent-URL has already been
522 // expanded.
523 KUrl urlToExpand = m_dirLister->url();
524 const QStringList subDirs = url.path().mid(pos).split(QDir::separator());
525 for (int i = 0; i < subDirs.count() - 1; ++i) {
526 urlToExpand.addPath(subDirs.at(i));
527 m_urlsToExpand.insert(urlToExpand);
528 }
529
530 // KDirLister::open() must called at least once to trigger an initial
531 // loading. The pending URLs that must be restored are handled
532 // in slotCompleted().
533 QSetIterator<KUrl> it2(m_urlsToExpand);
534 while (it2.hasNext()) {
535 const int idx = index(it2.next());
536 if (idx >= 0 && !isExpanded(idx)) {
537 setExpanded(idx, true);
538 break;
539 }
540 }
541 }
542
543 void KFileItemModel::setNameFilter(const QString& nameFilter)
544 {
545 if (m_filter.pattern() != nameFilter) {
546 dispatchPendingItemsToInsert();
547 m_filter.setPattern(nameFilter);
548 applyFilters();
549 }
550 }
551
552 QString KFileItemModel::nameFilter() const
553 {
554 return m_filter.pattern();
555 }
556
557 void KFileItemModel::setMimeTypeFilters(const QStringList& filters)
558 {
559 if (m_filter.mimeTypes() != filters) {
560 dispatchPendingItemsToInsert();
561 m_filter.setMimeTypes(filters);
562 applyFilters();
563 }
564 }
565
566 QStringList KFileItemModel::mimeTypeFilters() const
567 {
568 return m_filter.mimeTypes();
569 }
570
571
572 void KFileItemModel::applyFilters()
573 {
574 // Check which shown items from m_itemData must get
575 // hidden and hence moved to m_filteredItems.
576 KFileItemList newFilteredItems;
577
578 foreach (ItemData* itemData, m_itemData) {
579 // Only filter non-expanded items as child items may never
580 // exist without a parent item
581 if (!itemData->values.value("isExpanded").toBool()) {
582 if (!m_filter.matches(itemData->item)) {
583 newFilteredItems.append(itemData->item);
584 m_filteredItems.insert(itemData->item);
585 }
586 }
587 }
588
589 removeItems(newFilteredItems);
590
591 // Check which hidden items from m_filteredItems should
592 // get visible again and hence removed from m_filteredItems.
593 KFileItemList newVisibleItems;
594
595 QMutableSetIterator<KFileItem> it(m_filteredItems);
596 while (it.hasNext()) {
597 const KFileItem item = it.next();
598 if (m_filter.matches(item)) {
599 newVisibleItems.append(item);
600 it.remove();
601 }
602 }
603
604 insertItems(newVisibleItems);
605 }
606
607 QList<KFileItemModel::RoleInfo> KFileItemModel::rolesInformation()
608 {
609 static QList<RoleInfo> rolesInfo;
610 if (rolesInfo.isEmpty()) {
611 int count = 0;
612 const RoleInfoMap* map = rolesInfoMap(count);
613 for (int i = 0; i < count; ++i) {
614 if (map[i].roleType != NoRole) {
615 RoleInfo info;
616 info.role = map[i].role;
617 info.translation = i18nc(map[i].roleTranslationContext, map[i].roleTranslation);
618 if (map[i].groupTranslation) {
619 info.group = i18nc(map[i].groupTranslationContext, map[i].groupTranslation);
620 } else {
621 // For top level roles, groupTranslation is 0. We must make sure that
622 // info.group is an empty string then because the code that generates
623 // menus tries to put the actions into sub menus otherwise.
624 info.group = QString();
625 }
626 info.requiresNepomuk = map[i].requiresNepomuk;
627 info.requiresIndexer = map[i].requiresIndexer;
628 rolesInfo.append(info);
629 }
630 }
631 }
632
633 return rolesInfo;
634 }
635
636 void KFileItemModel::onGroupedSortingChanged(bool current)
637 {
638 Q_UNUSED(current);
639 m_groups.clear();
640 }
641
642 void KFileItemModel::onSortRoleChanged(const QByteArray& current, const QByteArray& previous)
643 {
644 Q_UNUSED(previous);
645 m_sortRole = typeForRole(current);
646
647 if (!m_requestRole[m_sortRole]) {
648 QSet<QByteArray> newRoles = m_roles;
649 newRoles << current;
650 setRoles(newRoles);
651 }
652
653 resortAllItems();
654 }
655
656 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous)
657 {
658 Q_UNUSED(current);
659 Q_UNUSED(previous);
660 resortAllItems();
661 }
662
663 void KFileItemModel::resortAllItems()
664 {
665 m_resortAllItemsTimer->stop();
666
667 const int itemCount = count();
668 if (itemCount <= 0) {
669 return;
670 }
671
672 #ifdef KFILEITEMMODEL_DEBUG
673 QElapsedTimer timer;
674 timer.start();
675 kDebug() << "===========================================================";
676 kDebug() << "Resorting" << itemCount << "items";
677 #endif
678
679 // Remember the order of the current URLs so
680 // that it can be determined which indexes have
681 // been moved because of the resorting.
682 QList<KUrl> oldUrls;
683 oldUrls.reserve(itemCount);
684 foreach (const ItemData* itemData, m_itemData) {
685 oldUrls.append(itemData->item.url());
686 }
687
688 m_groups.clear();
689 m_items.clear();
690
691 // Resort the items
692 KFileItemModelSortAlgorithm::sort(this, m_itemData.begin(), m_itemData.end());
693 for (int i = 0; i < itemCount; ++i) {
694 m_items.insert(m_itemData.at(i)->item.url(), i);
695 }
696
697 // Determine the indexes that have been moved
698 QList<int> movedToIndexes;
699 movedToIndexes.reserve(itemCount);
700 for (int i = 0; i < itemCount; i++) {
701 const int newIndex = m_items.value(oldUrls.at(i).url());
702 movedToIndexes.append(newIndex);
703 }
704
705 // Don't check whether items have really been moved and always emit a
706 // itemsMoved() signal after resorting: In case of grouped items
707 // the groups might change even if the items themselves don't change their
708 // position. Let the receiver of the signal decide whether a check for moved
709 // items makes sense.
710 emit itemsMoved(KItemRange(0, itemCount), movedToIndexes);
711
712 #ifdef KFILEITEMMODEL_DEBUG
713 kDebug() << "[TIME] Resorting of" << itemCount << "items:" << timer.elapsed();
714 #endif
715 }
716
717 void KFileItemModel::slotCompleted()
718 {
719 dispatchPendingItemsToInsert();
720
721 if (!m_urlsToExpand.isEmpty()) {
722 // Try to find a URL that can be expanded.
723 // Note that the parent folder must be expanded before any of its subfolders become visible.
724 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
725 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
726 foreach (const KUrl& url, m_urlsToExpand) {
727 const int index = m_items.value(url, -1);
728 if (index >= 0) {
729 m_urlsToExpand.remove(url);
730 if (setExpanded(index, true)) {
731 // The dir lister has been triggered. This slot will be called
732 // again after the directory has been expanded.
733 return;
734 }
735 }
736 }
737
738 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
739 // if these URLs have been deleted in the meantime.
740 m_urlsToExpand.clear();
741 }
742
743 emit directoryLoadingCompleted();
744 }
745
746 void KFileItemModel::slotCanceled()
747 {
748 m_maximumUpdateIntervalTimer->stop();
749 dispatchPendingItemsToInsert();
750
751 emit directoryLoadingCanceled();
752 }
753
754 void KFileItemModel::slotNewItems(const KFileItemList& items)
755 {
756 Q_ASSERT(!items.isEmpty());
757
758 if (m_requestRole[ExpandedParentsCountRole] && m_expandedParentsCountRoot >= 0) {
759 // To be able to compare whether the new items may be inserted as children
760 // of a parent item the pending items must be added to the model first.
761 dispatchPendingItemsToInsert();
762
763 KFileItem item = items.first();
764
765 // If the expanding of items is enabled, the call
766 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
767 // might result in emitting the same items twice due to the Keep-parameter.
768 // This case happens if an item gets expanded, collapsed and expanded again
769 // before the items could be loaded for the first expansion.
770 const int index = m_items.value(item.url(), -1);
771 if (index >= 0) {
772 // The items are already part of the model.
773 return;
774 }
775
776 // KDirLister keeps the children of items that got expanded once even if
777 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
778 // checked whether the parent for new items is still expanded.
779 KUrl parentUrl = item.url().upUrl();
780 parentUrl.adjustPath(KUrl::RemoveTrailingSlash);
781 const int parentIndex = m_items.value(parentUrl, -1);
782 if (parentIndex >= 0 && !m_itemData[parentIndex]->values.value("isExpanded").toBool()) {
783 // The parent is not expanded.
784 return;
785 }
786 }
787
788 if (!m_filter.hasSetFilters()) {
789 m_pendingItemsToInsert.append(items);
790 } else {
791 // The name or type filter is active. Hide filtered items
792 // before inserting them into the model and remember
793 // the filtered items in m_filteredItems.
794 KFileItemList filteredItems;
795 foreach (const KFileItem& item, items) {
796 if (m_filter.matches(item)) {
797 filteredItems.append(item);
798 } else {
799 m_filteredItems.insert(item);
800 }
801 }
802
803 m_pendingItemsToInsert.append(filteredItems);
804 }
805
806 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer->isActive()) {
807 // Assure that items get dispatched if no completed() or canceled() signal is
808 // emitted during the maximum update interval.
809 m_maximumUpdateIntervalTimer->start();
810 }
811 }
812
813 void KFileItemModel::slotItemsDeleted(const KFileItemList& items)
814 {
815 dispatchPendingItemsToInsert();
816
817 KFileItemList itemsToRemove = items;
818 if (m_requestRole[ExpandedParentsCountRole] && m_expandedParentsCountRoot >= 0) {
819 // Assure that removing a parent item also results in removing all children
820 foreach (const KFileItem& item, items) {
821 itemsToRemove.append(childItems(item));
822 }
823 }
824
825 if (!m_filteredItems.isEmpty()) {
826 foreach (const KFileItem& item, itemsToRemove) {
827 m_filteredItems.remove(item);
828 }
829
830 if (m_requestRole[ExpandedParentsCountRole] && m_expandedParentsCountRoot >= 0) {
831 // Remove all filtered children of deleted items. First, we put the
832 // deleted URLs into a set to provide fast lookup while iterating
833 // over m_filteredItems and prevent quadratic complexity if there
834 // are N removed items and N filtered items.
835 QSet<KUrl> urlsToRemove;
836 urlsToRemove.reserve(itemsToRemove.count());
837 foreach (const KFileItem& item, itemsToRemove) {
838 KUrl url = item.url();
839 url.adjustPath(KUrl::RemoveTrailingSlash);
840 urlsToRemove.insert(url);
841 }
842
843 QSet<KFileItem>::iterator it = m_filteredItems.begin();
844 while (it != m_filteredItems.end()) {
845 const KUrl url = it->url();
846 KUrl parentUrl = url.upUrl();
847 parentUrl.adjustPath(KUrl::RemoveTrailingSlash);
848
849 if (urlsToRemove.contains(parentUrl)) {
850 it = m_filteredItems.erase(it);
851 } else {
852 ++it;
853 }
854 }
855 }
856 }
857
858 removeItems(itemsToRemove);
859 }
860
861 void KFileItemModel::slotRefreshItems(const QList<QPair<KFileItem, KFileItem> >& items)
862 {
863 Q_ASSERT(!items.isEmpty());
864 #ifdef KFILEITEMMODEL_DEBUG
865 kDebug() << "Refreshing" << items.count() << "items";
866 #endif
867
868 m_groups.clear();
869
870 // Get the indexes of all items that have been refreshed
871 QList<int> indexes;
872 indexes.reserve(items.count());
873
874 QListIterator<QPair<KFileItem, KFileItem> > it(items);
875 while (it.hasNext()) {
876 const QPair<KFileItem, KFileItem>& itemPair = it.next();
877 const KFileItem& oldItem = itemPair.first;
878 const KFileItem& newItem = itemPair.second;
879 const int index = m_items.value(oldItem.url(), -1);
880 if (index >= 0) {
881 m_itemData[index]->item = newItem;
882
883 // Keep old values as long as possible if they could not retrieved synchronously yet.
884 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
885 QHashIterator<QByteArray, QVariant> it(retrieveData(newItem));
886 while (it.hasNext()) {
887 it.next();
888 m_itemData[index]->values.insert(it.key(), it.value());
889 }
890
891 m_items.remove(oldItem.url());
892 m_items.insert(newItem.url(), index);
893 indexes.append(index);
894 }
895 }
896
897 // If the changed items have been created recently, they might not be in m_items yet.
898 // In that case, the list 'indexes' might be empty.
899 if (indexes.isEmpty()) {
900 return;
901 }
902
903 // Extract the item-ranges out of the changed indexes
904 qSort(indexes);
905
906 KItemRangeList itemRangeList;
907 int previousIndex = indexes.at(0);
908 int rangeIndex = previousIndex;
909 int rangeCount = 1;
910
911 const int maxIndex = indexes.count() - 1;
912 for (int i = 1; i <= maxIndex; ++i) {
913 const int currentIndex = indexes.at(i);
914 if (currentIndex == previousIndex + 1) {
915 ++rangeCount;
916 } else {
917 itemRangeList.append(KItemRange(rangeIndex, rangeCount));
918
919 rangeIndex = currentIndex;
920 rangeCount = 1;
921 }
922 previousIndex = currentIndex;
923 }
924
925 if (rangeCount > 0) {
926 itemRangeList.append(KItemRange(rangeIndex, rangeCount));
927 }
928
929 emit itemsChanged(itemRangeList, m_roles);
930
931 resortAllItems();
932 }
933
934 void KFileItemModel::slotClear()
935 {
936 #ifdef KFILEITEMMODEL_DEBUG
937 kDebug() << "Clearing all items";
938 #endif
939
940 m_filteredItems.clear();
941 m_groups.clear();
942
943 m_maximumUpdateIntervalTimer->stop();
944 m_resortAllItemsTimer->stop();
945 m_pendingItemsToInsert.clear();
946
947 m_expandedParentsCountRoot = UninitializedExpandedParentsCountRoot;
948
949 const int removedCount = m_itemData.count();
950 if (removedCount > 0) {
951 qDeleteAll(m_itemData);
952 m_itemData.clear();
953 m_items.clear();
954 emit itemsRemoved(KItemRangeList() << KItemRange(0, removedCount));
955 }
956
957 m_expandedDirs.clear();
958 }
959
960 void KFileItemModel::slotClear(const KUrl& url)
961 {
962 Q_UNUSED(url);
963 }
964
965 void KFileItemModel::slotNaturalSortingChanged()
966 {
967 m_naturalSorting = KGlobalSettings::naturalSorting();
968 resortAllItems();
969 }
970
971 void KFileItemModel::dispatchPendingItemsToInsert()
972 {
973 if (!m_pendingItemsToInsert.isEmpty()) {
974 insertItems(m_pendingItemsToInsert);
975 m_pendingItemsToInsert.clear();
976 }
977 }
978
979 void KFileItemModel::insertItems(const KFileItemList& items)
980 {
981 if (items.isEmpty()) {
982 return;
983 }
984
985 if (m_sortRole == TypeRole) {
986 // Try to resolve the MIME-types synchronously to prevent a reordering of
987 // the items when sorting by type (per default MIME-types are resolved
988 // asynchronously by KFileItemModelRolesUpdater).
989 determineMimeTypes(items, 200);
990 }
991
992 #ifdef KFILEITEMMODEL_DEBUG
993 QElapsedTimer timer;
994 timer.start();
995 kDebug() << "===========================================================";
996 kDebug() << "Inserting" << items.count() << "items";
997 #endif
998
999 m_groups.clear();
1000
1001 QList<ItemData*> sortedItems = createItemDataList(items);
1002 KFileItemModelSortAlgorithm::sort(this, sortedItems.begin(), sortedItems.end());
1003
1004 #ifdef KFILEITEMMODEL_DEBUG
1005 kDebug() << "[TIME] Sorting:" << timer.elapsed();
1006 #endif
1007
1008 KItemRangeList itemRanges;
1009 int targetIndex = 0;
1010 int sourceIndex = 0;
1011 int insertedAtIndex = -1; // Index for the current item-range
1012 int insertedCount = 0; // Count for the current item-range
1013 int previouslyInsertedCount = 0; // Sum of previously inserted items for all ranges
1014 while (sourceIndex < sortedItems.count()) {
1015 // Find target index from m_items to insert the current item
1016 // in a sorted order
1017 const int previousTargetIndex = targetIndex;
1018 while (targetIndex < m_itemData.count()) {
1019 if (!lessThan(m_itemData.at(targetIndex), sortedItems.at(sourceIndex))) {
1020 break;
1021 }
1022 ++targetIndex;
1023 }
1024
1025 if (targetIndex - previousTargetIndex > 0 && insertedAtIndex >= 0) {
1026 itemRanges << KItemRange(insertedAtIndex, insertedCount);
1027 previouslyInsertedCount += insertedCount;
1028 insertedAtIndex = targetIndex - previouslyInsertedCount;
1029 insertedCount = 0;
1030 }
1031
1032 // Insert item at the position targetIndex by transferring
1033 // the ownership of the item-data from sortedItems to m_itemData.
1034 // m_items will be inserted after the loop (see comment below)
1035 m_itemData.insert(targetIndex, sortedItems.at(sourceIndex));
1036 ++insertedCount;
1037
1038 if (insertedAtIndex < 0) {
1039 insertedAtIndex = targetIndex;
1040 Q_ASSERT(previouslyInsertedCount == 0);
1041 }
1042 ++targetIndex;
1043 ++sourceIndex;
1044 }
1045
1046 // The indexes of all m_items must be adjusted, not only the index
1047 // of the new items
1048 const int itemDataCount = m_itemData.count();
1049 for (int i = 0; i < itemDataCount; ++i) {
1050 m_items.insert(m_itemData.at(i)->item.url(), i);
1051 }
1052
1053 itemRanges << KItemRange(insertedAtIndex, insertedCount);
1054 emit itemsInserted(itemRanges);
1055
1056 #ifdef KFILEITEMMODEL_DEBUG
1057 kDebug() << "[TIME] Inserting of" << items.count() << "items:" << timer.elapsed();
1058 #endif
1059 }
1060
1061 void KFileItemModel::removeItems(const KFileItemList& items)
1062 {
1063 if (items.isEmpty()) {
1064 return;
1065 }
1066
1067 #ifdef KFILEITEMMODEL_DEBUG
1068 kDebug() << "Removing " << items.count() << "items";
1069 #endif
1070
1071 m_groups.clear();
1072
1073 QList<ItemData*> sortedItems;
1074 sortedItems.reserve(items.count());
1075 foreach (const KFileItem& item, items) {
1076 const int index = m_items.value(item.url(), -1);
1077 if (index >= 0) {
1078 sortedItems.append(m_itemData.at(index));
1079 }
1080 }
1081 KFileItemModelSortAlgorithm::sort(this, sortedItems.begin(), sortedItems.end());
1082
1083 QList<int> indexesToRemove;
1084 indexesToRemove.reserve(items.count());
1085
1086 // Calculate the item ranges that will get deleted
1087 KItemRangeList itemRanges;
1088 int removedAtIndex = -1;
1089 int removedCount = 0;
1090 int targetIndex = 0;
1091 foreach (const ItemData* itemData, sortedItems) {
1092 const KFileItem& itemToRemove = itemData->item;
1093
1094 const int previousTargetIndex = targetIndex;
1095 while (targetIndex < m_itemData.count()) {
1096 if (m_itemData.at(targetIndex)->item.url() == itemToRemove.url()) {
1097 break;
1098 }
1099 ++targetIndex;
1100 }
1101 if (targetIndex >= m_itemData.count()) {
1102 kWarning() << "Item that should be deleted has not been found!";
1103 return;
1104 }
1105
1106 if (targetIndex - previousTargetIndex > 0 && removedAtIndex >= 0) {
1107 itemRanges << KItemRange(removedAtIndex, removedCount);
1108 removedAtIndex = targetIndex;
1109 removedCount = 0;
1110 }
1111
1112 indexesToRemove.append(targetIndex);
1113 if (removedAtIndex < 0) {
1114 removedAtIndex = targetIndex;
1115 }
1116 ++removedCount;
1117 ++targetIndex;
1118 }
1119
1120 // Delete the items
1121 for (int i = indexesToRemove.count() - 1; i >= 0; --i) {
1122 const int indexToRemove = indexesToRemove.at(i);
1123 ItemData* data = m_itemData.at(indexToRemove);
1124
1125 m_items.remove(data->item.url());
1126
1127 delete data;
1128 m_itemData.removeAt(indexToRemove);
1129 }
1130
1131 // The indexes of all m_items must be adjusted, not only the index
1132 // of the removed items
1133 const int itemDataCount = m_itemData.count();
1134 for (int i = 0; i < itemDataCount; ++i) {
1135 m_items.insert(m_itemData.at(i)->item.url(), i);
1136 }
1137
1138 if (count() <= 0) {
1139 m_expandedParentsCountRoot = UninitializedExpandedParentsCountRoot;
1140 }
1141
1142 itemRanges << KItemRange(removedAtIndex, removedCount);
1143 emit itemsRemoved(itemRanges);
1144 }
1145
1146 QList<KFileItemModel::ItemData*> KFileItemModel::createItemDataList(const KFileItemList& items) const
1147 {
1148 QList<ItemData*> itemDataList;
1149 itemDataList.reserve(items.count());
1150
1151 foreach (const KFileItem& item, items) {
1152 ItemData* itemData = new ItemData();
1153 itemData->item = item;
1154 itemData->values = retrieveData(item);
1155 itemData->parent = 0;
1156
1157 const bool determineParent = m_requestRole[ExpandedParentsCountRole]
1158 && itemData->values["expandedParentsCount"].toInt() > 0;
1159 if (determineParent) {
1160 KUrl parentUrl = item.url().upUrl();
1161 parentUrl.adjustPath(KUrl::RemoveTrailingSlash);
1162 const int parentIndex = m_items.value(parentUrl, -1);
1163 if (parentIndex >= 0) {
1164 itemData->parent = m_itemData.at(parentIndex);
1165 } else {
1166 kWarning() << "Parent item not found for" << item.url();
1167 }
1168 }
1169
1170 itemDataList.append(itemData);
1171 }
1172
1173 return itemDataList;
1174 }
1175
1176 void KFileItemModel::removeExpandedItems()
1177 {
1178 KFileItemList expandedItems;
1179
1180 const int maxIndex = m_itemData.count() - 1;
1181 for (int i = 0; i <= maxIndex; ++i) {
1182 const ItemData* itemData = m_itemData.at(i);
1183 if (itemData->values.value("expandedParentsCount").toInt() > 0) {
1184 expandedItems.append(itemData->item);
1185 }
1186 }
1187
1188 // The m_expandedParentsCountRoot may not get reset before all items with
1189 // a bigger count have been removed.
1190 removeItems(expandedItems);
1191
1192 m_expandedParentsCountRoot = UninitializedExpandedParentsCountRoot;
1193 m_expandedDirs.clear();
1194 }
1195
1196 void KFileItemModel::resetRoles()
1197 {
1198 for (int i = 0; i < RolesCount; ++i) {
1199 m_requestRole[i] = false;
1200 }
1201 }
1202
1203 KFileItemModel::RoleType KFileItemModel::typeForRole(const QByteArray& role) const
1204 {
1205 static QHash<QByteArray, RoleType> roles;
1206 if (roles.isEmpty()) {
1207 // Insert user visible roles that can be accessed with
1208 // KFileItemModel::roleInformation()
1209 int count = 0;
1210 const RoleInfoMap* map = rolesInfoMap(count);
1211 for (int i = 0; i < count; ++i) {
1212 roles.insert(map[i].role, map[i].roleType);
1213 }
1214
1215 // Insert internal roles (take care to synchronize the implementation
1216 // with KFileItemModel::roleForType() in case if a change is done).
1217 roles.insert("isDir", IsDirRole);
1218 roles.insert("isLink", IsLinkRole);
1219 roles.insert("isExpanded", IsExpandedRole);
1220 roles.insert("isExpandable", IsExpandableRole);
1221 roles.insert("expandedParentsCount", ExpandedParentsCountRole);
1222
1223 Q_ASSERT(roles.count() == RolesCount);
1224 }
1225
1226 return roles.value(role, NoRole);
1227 }
1228
1229 QByteArray KFileItemModel::roleForType(RoleType roleType) const
1230 {
1231 static QHash<RoleType, QByteArray> roles;
1232 if (roles.isEmpty()) {
1233 // Insert user visible roles that can be accessed with
1234 // KFileItemModel::roleInformation()
1235 int count = 0;
1236 const RoleInfoMap* map = rolesInfoMap(count);
1237 for (int i = 0; i < count; ++i) {
1238 roles.insert(map[i].roleType, map[i].role);
1239 }
1240
1241 // Insert internal roles (take care to synchronize the implementation
1242 // with KFileItemModel::typeForRole() in case if a change is done).
1243 roles.insert(IsDirRole, "isDir");
1244 roles.insert(IsLinkRole, "isLink");
1245 roles.insert(IsExpandedRole, "isExpanded");
1246 roles.insert(IsExpandableRole, "isExpandable");
1247 roles.insert(ExpandedParentsCountRole, "expandedParentsCount");
1248
1249 Q_ASSERT(roles.count() == RolesCount);
1250 };
1251
1252 return roles.value(roleType);
1253 }
1254
1255 QHash<QByteArray, QVariant> KFileItemModel::retrieveData(const KFileItem& item) const
1256 {
1257 // It is important to insert only roles that are fast to retrieve. E.g.
1258 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1259 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1260 QHash<QByteArray, QVariant> data;
1261 data.insert("url", item.url());
1262
1263 const bool isDir = item.isDir();
1264 if (m_requestRole[IsDirRole]) {
1265 data.insert("isDir", isDir);
1266 }
1267
1268 if (m_requestRole[IsLinkRole]) {
1269 const bool isLink = item.isLink();
1270 data.insert("isLink", isLink);
1271 }
1272
1273 if (m_requestRole[NameRole]) {
1274 data.insert("text", item.text());
1275 }
1276
1277 if (m_requestRole[SizeRole]) {
1278 if (isDir) {
1279 data.insert("size", QVariant());
1280 } else {
1281 data.insert("size", item.size());
1282 }
1283 }
1284
1285 if (m_requestRole[DateRole]) {
1286 // Don't use KFileItem::timeString() as this is too expensive when
1287 // having several thousands of items. Instead the formatting of the
1288 // date-time will be done on-demand by the view when the date will be shown.
1289 const KDateTime dateTime = item.time(KFileItem::ModificationTime);
1290 data.insert("date", dateTime.dateTime());
1291 }
1292
1293 if (m_requestRole[PermissionsRole]) {
1294 data.insert("permissions", item.permissionsString());
1295 }
1296
1297 if (m_requestRole[OwnerRole]) {
1298 data.insert("owner", item.user());
1299 }
1300
1301 if (m_requestRole[GroupRole]) {
1302 data.insert("group", item.group());
1303 }
1304
1305 if (m_requestRole[DestinationRole]) {
1306 QString destination = item.linkDest();
1307 if (destination.isEmpty()) {
1308 destination = QLatin1String("-");
1309 }
1310 data.insert("destination", destination);
1311 }
1312
1313 if (m_requestRole[PathRole]) {
1314 QString path;
1315 if (item.url().protocol() == QLatin1String("trash")) {
1316 path = item.entry().stringValue(KIO::UDSEntry::UDS_EXTRA);
1317 } else {
1318 // For performance reasons cache the home-path in a static QString
1319 // (see QDir::homePath() for more details)
1320 static QString homePath;
1321 if (homePath.isEmpty()) {
1322 homePath = QDir::homePath();
1323 }
1324
1325 path = item.localPath();
1326 if (path.startsWith(homePath)) {
1327 path.replace(0, homePath.length(), QLatin1Char('~'));
1328 }
1329 }
1330
1331 const int index = path.lastIndexOf(item.text());
1332 path = path.mid(0, index - 1);
1333 data.insert("path", path);
1334 }
1335
1336 if (m_requestRole[IsExpandableRole]) {
1337 data.insert("isExpandable", item.isDir() && item.url() == item.targetUrl());
1338 }
1339
1340 if (m_requestRole[ExpandedParentsCountRole]) {
1341 if (m_expandedParentsCountRoot == UninitializedExpandedParentsCountRoot) {
1342 const KUrl rootUrl = m_dirLister->url();
1343 const QString protocol = rootUrl.protocol();
1344 const bool forceExpandedParentsCountRoot = (protocol == QLatin1String("trash") ||
1345 protocol == QLatin1String("nepomuk") ||
1346 protocol == QLatin1String("remote") ||
1347 protocol.contains(QLatin1String("search")));
1348 if (forceExpandedParentsCountRoot) {
1349 m_expandedParentsCountRoot = ForceExpandedParentsCountRoot;
1350 } else {
1351 const QString rootDir = rootUrl.path(KUrl::AddTrailingSlash);
1352 m_expandedParentsCountRoot = rootDir.count('/');
1353 }
1354 }
1355
1356 if (m_expandedParentsCountRoot == ForceExpandedParentsCountRoot) {
1357 data.insert("expandedParentsCount", -1);
1358 } else {
1359 const QString dir = item.url().directory(KUrl::AppendTrailingSlash);
1360 const int level = dir.count('/') - m_expandedParentsCountRoot;
1361 data.insert("expandedParentsCount", level);
1362 }
1363 }
1364
1365 if (item.isMimeTypeKnown()) {
1366 data.insert("iconName", item.iconName());
1367
1368 if (m_requestRole[TypeRole]) {
1369 data.insert("type", item.mimeComment());
1370 }
1371 }
1372
1373 return data;
1374 }
1375
1376 bool KFileItemModel::lessThan(const ItemData* a, const ItemData* b) const
1377 {
1378 int result = 0;
1379
1380 if (m_expandedParentsCountRoot >= 0) {
1381 result = expandedParentsCountCompare(a, b);
1382 if (result != 0) {
1383 // The items have parents with different expansion levels
1384 return (sortOrder() == Qt::AscendingOrder) ? result < 0 : result > 0;
1385 }
1386 }
1387
1388 if (m_sortDirsFirst || m_sortRole == SizeRole) {
1389 const bool isDirA = a->item.isDir();
1390 const bool isDirB = b->item.isDir();
1391 if (isDirA && !isDirB) {
1392 return true;
1393 } else if (!isDirA && isDirB) {
1394 return false;
1395 }
1396 }
1397
1398 result = sortRoleCompare(a, b);
1399
1400 return (sortOrder() == Qt::AscendingOrder) ? result < 0 : result > 0;
1401 }
1402
1403 int KFileItemModel::sortRoleCompare(const ItemData* a, const ItemData* b) const
1404 {
1405 const KFileItem& itemA = a->item;
1406 const KFileItem& itemB = b->item;
1407
1408 int result = 0;
1409
1410 switch (m_sortRole) {
1411 case NameRole:
1412 // The name role is handled as default fallback after the switch
1413 break;
1414
1415 case SizeRole: {
1416 if (itemA.isDir()) {
1417 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1418 Q_ASSERT(itemB.isDir());
1419
1420 const QVariant valueA = a->values.value("size");
1421 const QVariant valueB = b->values.value("size");
1422 if (valueA.isNull() && valueB.isNull()) {
1423 result = 0;
1424 } else if (valueA.isNull()) {
1425 result = -1;
1426 } else if (valueB.isNull()) {
1427 result = +1;
1428 } else {
1429 result = valueA.toInt() - valueB.toInt();
1430 }
1431 } else {
1432 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1433 Q_ASSERT(!itemB.isDir());
1434 const KIO::filesize_t sizeA = itemA.size();
1435 const KIO::filesize_t sizeB = itemB.size();
1436 if (sizeA > sizeB) {
1437 result = +1;
1438 } else if (sizeA < sizeB) {
1439 result = -1;
1440 } else {
1441 result = 0;
1442 }
1443 }
1444 break;
1445 }
1446
1447 case DateRole: {
1448 const KDateTime dateTimeA = itemA.time(KFileItem::ModificationTime);
1449 const KDateTime dateTimeB = itemB.time(KFileItem::ModificationTime);
1450 if (dateTimeA < dateTimeB) {
1451 result = -1;
1452 } else if (dateTimeA > dateTimeB) {
1453 result = +1;
1454 }
1455 break;
1456 }
1457
1458 case RatingRole: {
1459 result = a->values.value("rating").toInt() - b->values.value("rating").toInt();
1460 break;
1461 }
1462
1463 case ImageSizeRole: {
1464 // Alway use a natural comparing to interpret the numbers of a string like
1465 // "1600 x 1200" for having a correct sorting.
1466 result = KStringHandler::naturalCompare(a->values.value("imageSize").toString(),
1467 b->values.value("imageSize").toString(),
1468 Qt::CaseSensitive);
1469 break;
1470 }
1471
1472 default: {
1473 const QByteArray role = roleForType(m_sortRole);
1474 result = QString::compare(a->values.value(role).toString(),
1475 b->values.value(role).toString());
1476 break;
1477 }
1478
1479 }
1480
1481 if (result != 0) {
1482 // The current sort role was sufficient to define an order
1483 return result;
1484 }
1485
1486 // Fallback #1: Compare the text of the items
1487 result = stringCompare(itemA.text(), itemB.text());
1488 if (result != 0) {
1489 return result;
1490 }
1491
1492 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1493 result = stringCompare(itemA.name(m_caseSensitivity == Qt::CaseInsensitive),
1494 itemB.name(m_caseSensitivity == Qt::CaseInsensitive));
1495 if (result != 0) {
1496 return result;
1497 }
1498
1499 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1500 // equal. In this case a comparison of the URL is done which is unique in all cases
1501 // within KDirLister.
1502 return QString::compare(itemA.url().url(), itemB.url().url(), Qt::CaseSensitive);
1503 }
1504
1505 int KFileItemModel::stringCompare(const QString& a, const QString& b) const
1506 {
1507 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1508 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1509 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1510 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1511
1512 if (m_caseSensitivity == Qt::CaseInsensitive) {
1513 const int result = m_naturalSorting ? KStringHandler::naturalCompare(a, b, Qt::CaseInsensitive)
1514 : QString::compare(a, b, Qt::CaseInsensitive);
1515 if (result != 0) {
1516 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1517 // comparison, still a deterministic sort order is required. A case sensitive
1518 // comparison is done as fallback.
1519 return result;
1520 }
1521 }
1522
1523 return m_naturalSorting ? KStringHandler::naturalCompare(a, b, Qt::CaseSensitive)
1524 : QString::compare(a, b, Qt::CaseSensitive);
1525 }
1526
1527 int KFileItemModel::expandedParentsCountCompare(const ItemData* a, const ItemData* b) const
1528 {
1529 const KUrl urlA = a->item.url();
1530 const KUrl urlB = b->item.url();
1531 if (urlA.directory() == urlB.directory()) {
1532 // Both items have the same directory as parent
1533 return 0;
1534 }
1535
1536 // Check whether one item is the parent of the other item
1537 if (urlA.isParentOf(urlB)) {
1538 return (sortOrder() == Qt::AscendingOrder) ? -1 : +1;
1539 } else if (urlB.isParentOf(urlA)) {
1540 return (sortOrder() == Qt::AscendingOrder) ? +1 : -1;
1541 }
1542
1543 // Determine the maximum common path of both items and
1544 // remember the index in 'index'
1545 const QString pathA = urlA.path();
1546 const QString pathB = urlB.path();
1547
1548 const int maxIndex = qMin(pathA.length(), pathB.length()) - 1;
1549 int index = 0;
1550 while (index <= maxIndex && pathA.at(index) == pathB.at(index)) {
1551 ++index;
1552 }
1553 if (index > maxIndex) {
1554 index = maxIndex;
1555 }
1556 while (index > 0 && (pathA.at(index) != QLatin1Char('/') || pathB.at(index) != QLatin1Char('/'))) {
1557 --index;
1558 }
1559
1560 // Determine the first sub-path after the common path and
1561 // check whether it represents a directory or already a file
1562 bool isDirA = true;
1563 const QString subPathA = subPath(a->item, pathA, index, &isDirA);
1564 bool isDirB = true;
1565 const QString subPathB = subPath(b->item, pathB, index, &isDirB);
1566
1567 if (m_sortDirsFirst || m_sortRole == SizeRole) {
1568 if (isDirA && !isDirB) {
1569 return (sortOrder() == Qt::AscendingOrder) ? -1 : +1;
1570 } else if (!isDirA && isDirB) {
1571 return (sortOrder() == Qt::AscendingOrder) ? +1 : -1;
1572 }
1573 }
1574
1575 // Compare the items of the parents that represent the first
1576 // different path after the common path.
1577 const QString parentPathA = pathA.left(index) + subPathA;
1578 const QString parentPathB = pathB.left(index) + subPathB;
1579
1580 const ItemData* parentA = a;
1581 while (parentA && parentA->item.url().path() != parentPathA) {
1582 parentA = parentA->parent;
1583 }
1584
1585 const ItemData* parentB = b;
1586 while (parentB && parentB->item.url().path() != parentPathB) {
1587 parentB = parentB->parent;
1588 }
1589
1590 if (parentA && parentB) {
1591 return sortRoleCompare(parentA, parentB);
1592 }
1593
1594 kWarning() << "Child items without parent detected:" << a->item.url() << b->item.url();
1595 return QString::compare(urlA.url(), urlB.url(), Qt::CaseSensitive);
1596 }
1597
1598 QString KFileItemModel::subPath(const KFileItem& item,
1599 const QString& itemPath,
1600 int start,
1601 bool* isDir) const
1602 {
1603 Q_ASSERT(isDir);
1604 const int pathIndex = itemPath.indexOf('/', start + 1);
1605 *isDir = (pathIndex > 0) || item.isDir();
1606 return itemPath.mid(start, pathIndex - start);
1607 }
1608
1609 bool KFileItemModel::useMaximumUpdateInterval() const
1610 {
1611 return !m_dirLister->url().isLocalFile();
1612 }
1613
1614 static bool localeAwareLessThan(const QChar& c1, const QChar& c2)
1615 {
1616 return QString::localeAwareCompare(c1, c2) < 0;
1617 }
1618
1619 QList<QPair<int, QVariant> > KFileItemModel::nameRoleGroups() const
1620 {
1621 Q_ASSERT(!m_itemData.isEmpty());
1622
1623 const int maxIndex = count() - 1;
1624 QList<QPair<int, QVariant> > groups;
1625
1626 QString groupValue;
1627 QChar firstChar;
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.isLetter()) {
1644 // Try to find a matching group in the range 'A' to 'Z'.
1645 static std::vector<QChar> lettersAtoZ;
1646 if (lettersAtoZ.empty()) {
1647 for (char c = 'A'; c <= 'Z'; ++c) {
1648 lettersAtoZ.push_back(QLatin1Char(c));
1649 }
1650 }
1651
1652 std::vector<QChar>::iterator it = std::lower_bound(lettersAtoZ.begin(), lettersAtoZ.end(), newFirstChar, localeAwareLessThan);
1653 if (it != lettersAtoZ.end()) {
1654 if (localeAwareLessThan(newFirstChar, *it) && it != lettersAtoZ.begin()) {
1655 // newFirstChar belongs to the group preceding *it.
1656 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
1657 --it;
1658 }
1659 newGroupValue = *it;
1660 } else {
1661 newGroupValue = newFirstChar;
1662 }
1663 } else if (newFirstChar >= QLatin1Char('0') && newFirstChar <= QLatin1Char('9')) {
1664 // Apply group '0 - 9' for any name that starts with a digit
1665 newGroupValue = i18nc("@title:group Groups that start with a digit", "0 - 9");
1666 } else {
1667 newGroupValue = i18nc("@title:group", "Others");
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 #include "kfileitemmodel.moc"