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