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