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