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