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