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