]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kfileitemmodel.cpp
Fix sorting-issues when value of a sort-role has been changed
[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 <KLocale>
25 #include <KStringHandler>
26 #include <KDebug>
27
28 #include <QMimeData>
29 #include <QTimer>
30
31 #define KFILEITEMMODEL_DEBUG
32
33 KFileItemModel::KFileItemModel(KDirLister* dirLister, QObject* parent) :
34 KItemModelBase("name", parent),
35 m_dirLister(dirLister),
36 m_naturalSorting(true),
37 m_sortFoldersFirst(true),
38 m_sortRole(NameRole),
39 m_roles(),
40 m_caseSensitivity(Qt::CaseInsensitive),
41 m_sortedItems(),
42 m_items(),
43 m_data(),
44 m_requestRole(),
45 m_minimumUpdateIntervalTimer(0),
46 m_maximumUpdateIntervalTimer(0),
47 m_pendingItemsToInsert(),
48 m_pendingEmitLoadingCompleted(false),
49 m_groups(),
50 m_rootExpansionLevel(-1),
51 m_expandedUrls(),
52 m_restoredExpandedUrls()
53 {
54 // Apply default roles that should be determined
55 resetRoles();
56 m_requestRole[NameRole] = true;
57 m_requestRole[IsDirRole] = true;
58 m_roles.insert("name");
59 m_roles.insert("isDir");
60
61 Q_ASSERT(dirLister);
62
63 connect(dirLister, SIGNAL(canceled()), this, SLOT(slotCanceled()));
64 connect(dirLister, SIGNAL(completed()), this, SLOT(slotCompleted()));
65 connect(dirLister, SIGNAL(newItems(KFileItemList)), this, SLOT(slotNewItems(KFileItemList)));
66 connect(dirLister, SIGNAL(itemsDeleted(KFileItemList)), this, SLOT(slotItemsDeleted(KFileItemList)));
67 connect(dirLister, SIGNAL(refreshItems(QList<QPair<KFileItem,KFileItem> >)), this, SLOT(slotRefreshItems(QList<QPair<KFileItem,KFileItem> >)));
68 connect(dirLister, SIGNAL(clear()), this, SLOT(slotClear()));
69 connect(dirLister, SIGNAL(clear(KUrl)), this, SLOT(slotClear(KUrl)));
70
71 // Although the layout engine of KItemListView is fast it is very inefficient to e.g.
72 // emit 50 itemsInserted()-signals each 100 ms. m_minimumUpdateIntervalTimer assures that updates
73 // are done in 1 second intervals for equal operations.
74 m_minimumUpdateIntervalTimer = new QTimer(this);
75 m_minimumUpdateIntervalTimer->setInterval(1000);
76 m_minimumUpdateIntervalTimer->setSingleShot(true);
77 connect(m_minimumUpdateIntervalTimer, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
78
79 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
80 // before the completed() or canceled() signal has been emitted.
81 m_maximumUpdateIntervalTimer = new QTimer(this);
82 m_maximumUpdateIntervalTimer->setInterval(2000);
83 m_maximumUpdateIntervalTimer->setSingleShot(true);
84 connect(m_maximumUpdateIntervalTimer, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
85
86 Q_ASSERT(m_minimumUpdateIntervalTimer->interval() <= m_maximumUpdateIntervalTimer->interval());
87 }
88
89 KFileItemModel::~KFileItemModel()
90 {
91 }
92
93 int KFileItemModel::count() const
94 {
95 return m_data.count();
96 }
97
98 QHash<QByteArray, QVariant> KFileItemModel::data(int index) const
99 {
100 if (index >= 0 && index < count()) {
101 return m_data.at(index);
102 }
103 return QHash<QByteArray, QVariant>();
104 }
105
106 bool KFileItemModel::setData(int index, const QHash<QByteArray, QVariant>& values)
107 {
108 if (index < 0 || index >= count()) {
109 return false;
110 }
111
112 QHash<QByteArray, QVariant> currentValue = m_data.at(index);
113
114 // Determine which roles have been changed
115 QSet<QByteArray> changedRoles;
116 QHashIterator<QByteArray, QVariant> it(values);
117 while (it.hasNext()) {
118 it.next();
119 const QByteArray role = it.key();
120 const QVariant value = it.value();
121
122 if (currentValue[role] != value) {
123 currentValue[role] = value;
124 changedRoles.insert(role);
125 }
126 }
127
128 if (changedRoles.isEmpty()) {
129 return false;
130 }
131
132 m_data[index] = currentValue;
133
134 if (!changedRoles.contains(sortRole())) {
135 emit itemsChanged(KItemRangeList() << KItemRange(index, 1), changedRoles);
136 return true;
137 }
138
139 // The sort role has been changed which might result in a changed
140 // item index. In this case instead of emitting the itemsChanged()
141 // signal the following is done:
142 // 1. The item gets removed from the current position and the signal
143 // itemsRemoved() will be emitted.
144 // 2. The item gets inserted to the new position and the signal
145 // itemsInserted() will be emitted.
146
147 const KFileItem& changedItem = m_sortedItems.at(index);
148 const bool sortOrderDecreased = (index > 0 && lessThan(changedItem, m_sortedItems.at(index - 1)));
149 const bool sortOrderIncreased = !sortOrderDecreased &&
150 (index < count() - 1 && lessThan(m_sortedItems.at(index + 1), changedItem));
151
152 if (!sortOrderDecreased && !sortOrderIncreased) {
153 // Although the value of the sort-role has been changed it did not result
154 // into a changed position.
155 emit itemsChanged(KItemRangeList() << KItemRange(index, 1), changedRoles);
156 return true;
157 }
158
159 m_groups.clear();
160
161 if (!m_pendingItemsToInsert.isEmpty()) {
162 insertItems(m_pendingItemsToInsert);
163 m_pendingItemsToInsert.clear();
164 }
165
166 // Do a binary search to find the new position where the item
167 // should get inserted. The result will be stored in 'mid'.
168 int min = sortOrderIncreased ? index + 1 : 0;
169 int max = sortOrderDecreased ? index - 1 : count() - 1;
170 int mid = 0;
171 do {
172 mid = (min + max) / 2;
173 if (lessThan(m_sortedItems.at(mid), changedItem)) {
174 min = mid + 1;
175 } else {
176 max = mid - 1;
177 }
178 } while (min <= max);
179
180 if (sortOrderIncreased && mid == max && lessThan(m_sortedItems.at(max), changedItem)) {
181 ++mid;
182 }
183
184 // Remove the item from the old position
185 const KFileItem removedItem = changedItem;
186 const QHash<QByteArray, QVariant> removedData = m_data[index];
187
188 m_items.remove(changedItem.url());
189 m_sortedItems.removeAt(index);
190 m_data.removeAt(index);
191 for (int i = 0; i < m_sortedItems.count(); ++i) {
192 m_items.insert(m_sortedItems.at(i).url(), i);
193 }
194
195 emit itemsRemoved(KItemRangeList() << KItemRange(index, 1));
196
197 // Insert the item to the new position
198 if (sortOrderIncreased) {
199 --mid;
200 }
201
202 m_sortedItems.insert(mid, removedItem);
203 m_data.insert(mid, removedData);
204 for (int i = 0; i < m_sortedItems.count(); ++i) {
205 m_items.insert(m_sortedItems.at(i).url(), i);
206 }
207
208 emit itemsInserted(KItemRangeList() << KItemRange(mid, 1));
209
210 return true;
211 }
212
213 void KFileItemModel::setSortFoldersFirst(bool foldersFirst)
214 {
215 if (foldersFirst != m_sortFoldersFirst) {
216 m_sortFoldersFirst = foldersFirst;
217 resortAllItems();
218 }
219 }
220
221 bool KFileItemModel::sortFoldersFirst() const
222 {
223 return m_sortFoldersFirst;
224 }
225
226 QMimeData* KFileItemModel::createMimeData(const QSet<int>& indexes) const
227 {
228 QMimeData* data = new QMimeData();
229
230 // The following code has been taken from KDirModel::mimeData()
231 // (kdelibs/kio/kio/kdirmodel.cpp)
232 // Copyright (C) 2006 David Faure <faure@kde.org>
233 KUrl::List urls;
234 KUrl::List mostLocalUrls;
235 bool canUseMostLocalUrls = true;
236
237 QSetIterator<int> it(indexes);
238 while (it.hasNext()) {
239 const int index = it.next();
240 const KFileItem item = fileItem(index);
241 if (!item.isNull()) {
242 urls << item.url();
243
244 bool isLocal;
245 mostLocalUrls << item.mostLocalUrl(isLocal);
246 if (!isLocal) {
247 canUseMostLocalUrls = false;
248 }
249 }
250 }
251
252 const bool different = canUseMostLocalUrls && mostLocalUrls != urls;
253 urls = KDirModel::simplifiedUrlList(urls); // TODO: Check if we still need KDirModel for this in KDE 5.0
254 if (different) {
255 mostLocalUrls = KDirModel::simplifiedUrlList(mostLocalUrls);
256 urls.populateMimeData(mostLocalUrls, data);
257 } else {
258 urls.populateMimeData(data);
259 }
260
261 return data;
262 }
263
264 int KFileItemModel::indexForKeyboardSearch(const QString& text, int startFromIndex) const
265 {
266 startFromIndex = qMax(0, startFromIndex);
267 for (int i = startFromIndex; i < count(); ++i) {
268 if (data(i)["name"].toString().startsWith(text, Qt::CaseInsensitive)) {
269 return i;
270 }
271 }
272 for (int i = 0; i < startFromIndex; ++i) {
273 if (data(i)["name"].toString().startsWith(text, Qt::CaseInsensitive)) {
274 return i;
275 }
276 }
277 return -1;
278 }
279
280 bool KFileItemModel::supportsDropping(int index) const
281 {
282 const KFileItem item = fileItem(index);
283 return item.isNull() ? false : item.isDir();
284 }
285
286 QString KFileItemModel::roleDescription(const QByteArray& role) const
287 {
288 QString descr;
289
290 switch (roleIndex(role)) {
291 case NameRole: descr = i18nc("@item:intable", "Name"); break;
292 case SizeRole: descr = i18nc("@item:intable", "Size"); break;
293 case DateRole: descr = i18nc("@item:intable", "Date"); break;
294 case PermissionsRole: descr = i18nc("@item:intable", "Permissions"); break;
295 case OwnerRole: descr = i18nc("@item:intable", "Owner"); break;
296 case GroupRole: descr = i18nc("@item:intable", "Group"); break;
297 case TypeRole: descr = i18nc("@item:intable", "Type"); break;
298 case DestinationRole: descr = i18nc("@item:intable", "Destination"); break;
299 case PathRole: descr = i18nc("@item:intable", "Path"); break;
300 case CommentRole: descr = i18nc("@item:intable", "Comment"); break;
301 case TagsRole: descr = i18nc("@item:intable", "Tags"); break;
302 case RatingRole: descr = i18nc("@item:intable", "Rating"); break;
303 case NoRole: break;
304 case IsDirRole: break;
305 case IsExpandedRole: break;
306 case ExpansionLevelRole: break;
307 default: Q_ASSERT(false); break;
308 }
309
310 return descr;
311 }
312
313 QList<QPair<int, QVariant> > KFileItemModel::groups() const
314 {
315 if (!m_data.isEmpty() && m_groups.isEmpty()) {
316 #ifdef KFILEITEMMODEL_DEBUG
317 QElapsedTimer timer;
318 timer.start();
319 #endif
320 switch (roleIndex(sortRole())) {
321 case NameRole: m_groups = nameRoleGroups(); break;
322 case SizeRole: m_groups = sizeRoleGroups(); break;
323 case DateRole: m_groups = dateRoleGroups(); break;
324 case PermissionsRole: m_groups = permissionRoleGroups(); break;
325 case OwnerRole: m_groups = genericStringRoleGroups("owner"); break;
326 case GroupRole: m_groups = genericStringRoleGroups("group"); break;
327 case TypeRole: m_groups = genericStringRoleGroups("type"); break;
328 case DestinationRole: m_groups = genericStringRoleGroups("destination"); break;
329 case PathRole: m_groups = genericStringRoleGroups("path"); break;
330 case CommentRole: m_groups = genericStringRoleGroups("comment"); break;
331 case TagsRole: m_groups = genericStringRoleGroups("tags"); break;
332 case RatingRole: m_groups = ratingRoleGroups(); break;
333 case NoRole: break;
334 case IsDirRole: break;
335 case IsExpandedRole: break;
336 case ExpansionLevelRole: break;
337 default: Q_ASSERT(false); break;
338 }
339
340 #ifdef KFILEITEMMODEL_DEBUG
341 kDebug() << "[TIME] Calculating groups for" << count() << "items:" << timer.elapsed();
342 #endif
343 }
344
345 return m_groups;
346 }
347
348 KFileItem KFileItemModel::fileItem(int index) const
349 {
350 if (index >= 0 && index < count()) {
351 return m_sortedItems.at(index);
352 }
353
354 return KFileItem();
355 }
356
357 KFileItem KFileItemModel::fileItem(const KUrl& url) const
358 {
359 const int index = m_items.value(url, -1);
360 if (index >= 0) {
361 return m_sortedItems.at(index);
362 }
363 return KFileItem();
364 }
365
366 int KFileItemModel::index(const KFileItem& item) const
367 {
368 if (item.isNull()) {
369 return -1;
370 }
371
372 return m_items.value(item.url(), -1);
373 }
374
375 int KFileItemModel::index(const KUrl& url) const
376 {
377 KUrl urlToFind = url;
378 urlToFind.adjustPath(KUrl::RemoveTrailingSlash);
379 return m_items.value(urlToFind, -1);
380 }
381
382 KFileItem KFileItemModel::rootItem() const
383 {
384 const KDirLister* dirLister = m_dirLister.data();
385 if (dirLister) {
386 return dirLister->rootItem();
387 }
388 return KFileItem();
389 }
390
391 void KFileItemModel::clear()
392 {
393 slotClear();
394 }
395
396 void KFileItemModel::setRoles(const QSet<QByteArray>& roles)
397 {
398 m_roles = roles;
399
400 if (count() > 0) {
401 const bool supportedExpanding = m_requestRole[IsExpandedRole] && m_requestRole[ExpansionLevelRole];
402 const bool willSupportExpanding = roles.contains("isExpanded") && roles.contains("expansionLevel");
403 if (supportedExpanding && !willSupportExpanding) {
404 // No expanding is supported anymore. Take care to delete all items that have an expansion level
405 // that is not 0 (and hence are part of an expanded item).
406 removeExpandedItems();
407 }
408 }
409
410 resetRoles();
411
412 QSetIterator<QByteArray> it(roles);
413 while (it.hasNext()) {
414 const QByteArray& role = it.next();
415 m_requestRole[roleIndex(role)] = true;
416 }
417
418 if (count() > 0) {
419 // Update m_data with the changed requested roles
420 const int maxIndex = count() - 1;
421 for (int i = 0; i <= maxIndex; ++i) {
422 m_data[i] = retrieveData(m_sortedItems.at(i));
423 }
424
425 kWarning() << "TODO: Emitting itemsChanged() with no information what has changed!";
426 emit itemsChanged(KItemRangeList() << KItemRange(0, count()), QSet<QByteArray>());
427 }
428 }
429
430 QSet<QByteArray> KFileItemModel::roles() const
431 {
432 return m_roles;
433 }
434
435 bool KFileItemModel::setExpanded(int index, bool expanded)
436 {
437 if (isExpanded(index) == expanded || index < 0 || index >= count()) {
438 return false;
439 }
440
441 QHash<QByteArray, QVariant> values;
442 values.insert("isExpanded", expanded);
443 if (!setData(index, values)) {
444 return false;
445 }
446
447 const KUrl url = m_sortedItems.at(index).url();
448 if (expanded) {
449 m_expandedUrls.insert(url);
450
451 KDirLister* dirLister = m_dirLister.data();
452 if (dirLister) {
453 dirLister->openUrl(url, KDirLister::Keep);
454 return true;
455 }
456 } else {
457 m_expandedUrls.remove(url);
458
459 KFileItemList itemsToRemove;
460 const int expansionLevel = data(index)["expansionLevel"].toInt();
461 ++index;
462 while (index < count() && data(index)["expansionLevel"].toInt() > expansionLevel) {
463 itemsToRemove.append(m_sortedItems.at(index));
464 ++index;
465 }
466 removeItems(itemsToRemove);
467 return true;
468 }
469
470 return false;
471 }
472
473 bool KFileItemModel::isExpanded(int index) const
474 {
475 if (index >= 0 && index < count()) {
476 return m_data.at(index).value("isExpanded").toBool();
477 }
478 return false;
479 }
480
481 bool KFileItemModel::isExpandable(int index) const
482 {
483 if (index >= 0 && index < count()) {
484 return m_sortedItems.at(index).isDir();
485 }
486 return false;
487 }
488
489 QSet<KUrl> KFileItemModel::expandedUrls() const
490 {
491 return m_expandedUrls;
492 }
493
494 void KFileItemModel::restoreExpandedUrls(const QSet<KUrl>& urls)
495 {
496 m_restoredExpandedUrls = urls;
497 }
498
499 void KFileItemModel::onGroupedSortingChanged(bool current)
500 {
501 Q_UNUSED(current);
502 m_groups.clear();
503 }
504
505 void KFileItemModel::onSortRoleChanged(const QByteArray& current, const QByteArray& previous)
506 {
507 Q_UNUSED(previous);
508 m_sortRole = roleIndex(current);
509
510 #ifdef KFILEITEMMODEL_DEBUG
511 if (!m_requestRole[m_sortRole]) {
512 kWarning() << "The sort-role has been changed to a role that has not been received yet";
513 }
514 #endif
515
516 resortAllItems();
517 }
518
519 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous)
520 {
521 Q_UNUSED(current);
522 Q_UNUSED(previous);
523 resortAllItems();
524 }
525
526 void KFileItemModel::slotCompleted()
527 {
528 if (m_restoredExpandedUrls.isEmpty() && m_minimumUpdateIntervalTimer->isActive()) {
529 // dispatchPendingItems() will be called when the timer
530 // has been expired.
531 m_pendingEmitLoadingCompleted = true;
532 return;
533 }
534
535 m_pendingEmitLoadingCompleted = false;
536 dispatchPendingItemsToInsert();
537
538 if (!m_restoredExpandedUrls.isEmpty()) {
539 // Try to find a URL that can be expanded.
540 // Note that the parent folder must be expanded before any of its subfolders become visible.
541 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
542 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
543 foreach(const KUrl& url, m_restoredExpandedUrls) {
544 const int index = m_items.value(url, -1);
545 if (index >= 0) {
546 // We have found an expandable URL. Expand it and return - when
547 // the dir lister has finished, this slot will be called again.
548 m_restoredExpandedUrls.remove(url);
549 setExpanded(index, true);
550 return;
551 }
552 }
553
554 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
555 // if these URLs have been deleted in the meantime.
556 m_restoredExpandedUrls.clear();
557 }
558
559 emit loadingCompleted();
560 m_minimumUpdateIntervalTimer->start();
561 }
562
563 void KFileItemModel::slotCanceled()
564 {
565 m_minimumUpdateIntervalTimer->stop();
566 m_maximumUpdateIntervalTimer->stop();
567 dispatchPendingItemsToInsert();
568 }
569
570 void KFileItemModel::slotNewItems(const KFileItemList& items)
571 {
572 m_pendingItemsToInsert.append(items);
573
574 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer->isActive()) {
575 // Assure that items get dispatched if no completed() or canceled() signal is
576 // emitted during the maximum update interval.
577 m_maximumUpdateIntervalTimer->start();
578 }
579 }
580
581 void KFileItemModel::slotItemsDeleted(const KFileItemList& items)
582 {
583 if (!m_pendingItemsToInsert.isEmpty()) {
584 insertItems(m_pendingItemsToInsert);
585 m_pendingItemsToInsert.clear();
586 }
587 removeItems(items);
588 }
589
590 void KFileItemModel::slotRefreshItems(const QList<QPair<KFileItem, KFileItem> >& items)
591 {
592 Q_ASSERT(!items.isEmpty());
593 #ifdef KFILEITEMMODEL_DEBUG
594 kDebug() << "Refreshing" << items.count() << "items";
595 #endif
596
597 m_groups.clear();
598
599 // Get the indexes of all items that have been refreshed
600 QList<int> indexes;
601 indexes.reserve(items.count());
602
603 QListIterator<QPair<KFileItem, KFileItem> > it(items);
604 while (it.hasNext()) {
605 const QPair<KFileItem, KFileItem>& itemPair = it.next();
606 const int index = m_items.value(itemPair.second.url(), -1);
607 if (index >= 0) {
608 indexes.append(index);
609 }
610 }
611
612 // If the changed items have been created recently, they might not be in m_items yet.
613 // In that case, the list 'indexes' might be empty.
614 if (indexes.isEmpty()) {
615 return;
616 }
617
618 // Extract the item-ranges out of the changed indexes
619 qSort(indexes);
620
621 KItemRangeList itemRangeList;
622 int rangeIndex = 0;
623 int rangeCount = 1;
624 int previousIndex = indexes.at(0);
625
626 const int maxIndex = indexes.count() - 1;
627 for (int i = 1; i <= maxIndex; ++i) {
628 const int currentIndex = indexes.at(i);
629 if (currentIndex == previousIndex + 1) {
630 ++rangeCount;
631 } else {
632 itemRangeList.append(KItemRange(rangeIndex, rangeCount));
633
634 rangeIndex = currentIndex;
635 rangeCount = 1;
636 }
637 previousIndex = currentIndex;
638 }
639
640 if (rangeCount > 0) {
641 itemRangeList.append(KItemRange(rangeIndex, rangeCount));
642 }
643
644 emit itemsChanged(itemRangeList, QSet<QByteArray>());
645 }
646
647 void KFileItemModel::slotClear()
648 {
649 #ifdef KFILEITEMMODEL_DEBUG
650 kDebug() << "Clearing all items";
651 #endif
652
653 m_groups.clear();
654
655 m_minimumUpdateIntervalTimer->stop();
656 m_maximumUpdateIntervalTimer->stop();
657 m_pendingItemsToInsert.clear();
658
659 m_rootExpansionLevel = -1;
660
661 const int removedCount = m_data.count();
662 if (removedCount > 0) {
663 m_sortedItems.clear();
664 m_items.clear();
665 m_data.clear();
666 emit itemsRemoved(KItemRangeList() << KItemRange(0, removedCount));
667 }
668
669 m_expandedUrls.clear();
670 }
671
672 void KFileItemModel::slotClear(const KUrl& url)
673 {
674 Q_UNUSED(url);
675 }
676
677 void KFileItemModel::dispatchPendingItemsToInsert()
678 {
679 if (!m_pendingItemsToInsert.isEmpty()) {
680 insertItems(m_pendingItemsToInsert);
681 m_pendingItemsToInsert.clear();
682 }
683
684 if (m_pendingEmitLoadingCompleted) {
685 emit loadingCompleted();
686 }
687 }
688
689 void KFileItemModel::insertItems(const KFileItemList& items)
690 {
691 if (items.isEmpty()) {
692 return;
693 }
694
695 #ifdef KFILEITEMMODEL_DEBUG
696 QElapsedTimer timer;
697 timer.start();
698 kDebug() << "===========================================================";
699 kDebug() << "Inserting" << items.count() << "items";
700 #endif
701
702 m_groups.clear();
703
704 KFileItemList sortedItems = items;
705 sort(sortedItems.begin(), sortedItems.end());
706
707 #ifdef KFILEITEMMODEL_DEBUG
708 kDebug() << "[TIME] Sorting:" << timer.elapsed();
709 #endif
710
711 KItemRangeList itemRanges;
712 int targetIndex = 0;
713 int sourceIndex = 0;
714 int insertedAtIndex = -1; // Index for the current item-range
715 int insertedCount = 0; // Count for the current item-range
716 int previouslyInsertedCount = 0; // Sum of previously inserted items for all ranges
717 while (sourceIndex < sortedItems.count()) {
718 // Find target index from m_items to insert the current item
719 // in a sorted order
720 const int previousTargetIndex = targetIndex;
721 while (targetIndex < m_sortedItems.count()) {
722 if (!lessThan(m_sortedItems.at(targetIndex), sortedItems.at(sourceIndex))) {
723 break;
724 }
725 ++targetIndex;
726 }
727
728 if (targetIndex - previousTargetIndex > 0 && insertedAtIndex >= 0) {
729 itemRanges << KItemRange(insertedAtIndex, insertedCount);
730 previouslyInsertedCount += insertedCount;
731 insertedAtIndex = targetIndex - previouslyInsertedCount;
732 insertedCount = 0;
733 }
734
735 // Insert item at the position targetIndex
736 const KFileItem item = sortedItems.at(sourceIndex);
737 m_sortedItems.insert(targetIndex, item);
738 m_data.insert(targetIndex, retrieveData(item));
739 // m_items will be inserted after the loop (see comment below)
740 ++insertedCount;
741
742 if (insertedAtIndex < 0) {
743 insertedAtIndex = targetIndex;
744 Q_ASSERT(previouslyInsertedCount == 0);
745 }
746 ++targetIndex;
747 ++sourceIndex;
748 }
749
750 // The indexes of all m_items must be adjusted, not only the index
751 // of the new items
752 for (int i = 0; i < m_sortedItems.count(); ++i) {
753 m_items.insert(m_sortedItems.at(i).url(), i);
754 }
755
756 itemRanges << KItemRange(insertedAtIndex, insertedCount);
757 emit itemsInserted(itemRanges);
758
759 #ifdef KFILEITEMMODEL_DEBUG
760 kDebug() << "[TIME] Inserting of" << items.count() << "items:" << timer.elapsed();
761 #endif
762 }
763
764 void KFileItemModel::removeItems(const KFileItemList& items)
765 {
766 if (items.isEmpty()) {
767 return;
768 }
769
770 #ifdef KFILEITEMMODEL_DEBUG
771 kDebug() << "Removing " << items.count() << "items";
772 #endif
773
774 m_groups.clear();
775
776 KFileItemList sortedItems = items;
777 sort(sortedItems.begin(), sortedItems.end());
778
779 QList<int> indexesToRemove;
780 indexesToRemove.reserve(items.count());
781
782 // Calculate the item ranges that will get deleted
783 KItemRangeList itemRanges;
784 int removedAtIndex = -1;
785 int removedCount = 0;
786 int targetIndex = 0;
787 foreach (const KFileItem& itemToRemove, sortedItems) {
788 const int previousTargetIndex = targetIndex;
789 while (targetIndex < m_sortedItems.count()) {
790 if (m_sortedItems.at(targetIndex).url() == itemToRemove.url()) {
791 break;
792 }
793 ++targetIndex;
794 }
795 if (targetIndex >= m_sortedItems.count()) {
796 kWarning() << "Item that should be deleted has not been found!";
797 return;
798 }
799
800 if (targetIndex - previousTargetIndex > 0 && removedAtIndex >= 0) {
801 itemRanges << KItemRange(removedAtIndex, removedCount);
802 removedAtIndex = targetIndex;
803 removedCount = 0;
804 }
805
806 indexesToRemove.append(targetIndex);
807 if (removedAtIndex < 0) {
808 removedAtIndex = targetIndex;
809 }
810 ++removedCount;
811 ++targetIndex;
812 }
813
814 // Delete the items
815 for (int i = indexesToRemove.count() - 1; i >= 0; --i) {
816 const int indexToRemove = indexesToRemove.at(i);
817 m_items.remove(m_sortedItems.at(indexToRemove).url());
818 m_sortedItems.removeAt(indexToRemove);
819 m_data.removeAt(indexToRemove);
820 }
821
822 // The indexes of all m_items must be adjusted, not only the index
823 // of the removed items
824 for (int i = 0; i < m_sortedItems.count(); ++i) {
825 m_items.insert(m_sortedItems.at(i).url(), i);
826 }
827
828 if (count() <= 0) {
829 m_rootExpansionLevel = -1;
830 }
831
832 itemRanges << KItemRange(removedAtIndex, removedCount);
833 emit itemsRemoved(itemRanges);
834 }
835
836 void KFileItemModel::resortAllItems()
837 {
838 const int itemCount = count();
839 if (itemCount <= 0) {
840 return;
841 }
842
843 const KFileItemList oldSortedItems = m_sortedItems;
844 const QHash<KUrl, int> oldItems = m_items;
845 const QList<QHash<QByteArray, QVariant> > oldData = m_data;
846
847 m_groups.clear();
848 m_items.clear();
849 m_data.clear();
850
851 sort(m_sortedItems.begin(), m_sortedItems.end());
852 int index = 0;
853 foreach (const KFileItem& item, m_sortedItems) {
854 m_items.insert(item.url(), index);
855
856 const int oldItemIndex = oldItems.value(item.url());
857 m_data.append(oldData.at(oldItemIndex));
858
859 ++index;
860 }
861
862 bool emitItemsMoved = false;
863 QList<int> movedToIndexes;
864 movedToIndexes.reserve(m_sortedItems.count());
865 for (int i = 0; i < itemCount; i++) {
866 const int newIndex = m_items.value(oldSortedItems.at(i).url());
867 movedToIndexes.append(newIndex);
868 if (!emitItemsMoved && newIndex != i) {
869 emitItemsMoved = true;
870 }
871 }
872
873 if (emitItemsMoved) {
874 emit itemsMoved(KItemRange(0, itemCount), movedToIndexes);
875 }
876 }
877
878 void KFileItemModel::removeExpandedItems()
879 {
880 KFileItemList expandedItems;
881
882 const int maxIndex = m_data.count() - 1;
883 for (int i = 0; i <= maxIndex; ++i) {
884 if (m_data.at(i).value("expansionLevel").toInt() > 0) {
885 const KFileItem fileItem = m_sortedItems.at(i);
886 expandedItems.append(fileItem);
887 }
888 }
889
890 // The m_rootExpansionLevel may not get reset before all items with
891 // a bigger expansionLevel have been removed.
892 Q_ASSERT(m_rootExpansionLevel >= 0);
893 removeItems(expandedItems);
894
895 m_rootExpansionLevel = -1;
896 m_expandedUrls.clear();
897 }
898
899 void KFileItemModel::resetRoles()
900 {
901 for (int i = 0; i < RolesCount; ++i) {
902 m_requestRole[i] = false;
903 }
904 }
905
906 KFileItemModel::Role KFileItemModel::roleIndex(const QByteArray& role) const
907 {
908 static QHash<QByteArray, Role> rolesHash;
909 if (rolesHash.isEmpty()) {
910 rolesHash.insert("name", NameRole);
911 rolesHash.insert("size", SizeRole);
912 rolesHash.insert("date", DateRole);
913 rolesHash.insert("permissions", PermissionsRole);
914 rolesHash.insert("owner", OwnerRole);
915 rolesHash.insert("group", GroupRole);
916 rolesHash.insert("type", TypeRole);
917 rolesHash.insert("destination", DestinationRole);
918 rolesHash.insert("path", PathRole);
919 rolesHash.insert("comment", CommentRole);
920 rolesHash.insert("tags", TagsRole);
921 rolesHash.insert("rating", RatingRole);
922 rolesHash.insert("isDir", IsDirRole);
923 rolesHash.insert("isExpanded", IsExpandedRole);
924 rolesHash.insert("expansionLevel", ExpansionLevelRole);
925 }
926 return rolesHash.value(role, NoRole);
927 }
928
929 QHash<QByteArray, QVariant> KFileItemModel::retrieveData(const KFileItem& item) const
930 {
931 // It is important to insert only roles that are fast to retrieve. E.g.
932 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
933 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
934 QHash<QByteArray, QVariant> data;
935 data.insert("iconPixmap", QPixmap());
936
937 const bool isDir = item.isDir();
938 if (m_requestRole[IsDirRole]) {
939 data.insert("isDir", isDir);
940 }
941
942 if (m_requestRole[NameRole]) {
943 data.insert("name", item.name());
944 }
945
946 if (m_requestRole[SizeRole]) {
947 if (isDir) {
948 data.insert("size", QVariant());
949 } else {
950 data.insert("size", item.size());
951 }
952 }
953
954 if (m_requestRole[DateRole]) {
955 // Don't use KFileItem::timeString() as this is too expensive when
956 // having several thousands of items. Instead the formatting of the
957 // date-time will be done on-demand by the view when the date will be shown.
958 const KDateTime dateTime = item.time(KFileItem::ModificationTime);
959 data.insert("date", dateTime.dateTime());
960 }
961
962 if (m_requestRole[PermissionsRole]) {
963 data.insert("permissions", item.permissionsString());
964 }
965
966 if (m_requestRole[OwnerRole]) {
967 data.insert("owner", item.user());
968 }
969
970 if (m_requestRole[GroupRole]) {
971 data.insert("group", item.group());
972 }
973
974 if (m_requestRole[DestinationRole]) {
975 QString destination = item.linkDest();
976 if (destination.isEmpty()) {
977 destination = i18nc("@item:intable", "No destination");
978 }
979 data.insert("destination", destination);
980 }
981
982 if (m_requestRole[PathRole]) {
983 data.insert("path", item.localPath());
984 }
985
986 if (m_requestRole[IsExpandedRole]) {
987 data.insert("isExpanded", false);
988 }
989
990 if (m_requestRole[ExpansionLevelRole]) {
991 if (m_rootExpansionLevel < 0) {
992 KDirLister* dirLister = m_dirLister.data();
993 if (dirLister) {
994 const QString rootDir = dirLister->url().directory(KUrl::AppendTrailingSlash);
995 m_rootExpansionLevel = rootDir.count('/');
996 }
997 }
998 const QString dir = item.url().directory(KUrl::AppendTrailingSlash);
999 const int level = dir.count('/') - m_rootExpansionLevel - 1;
1000 data.insert("expansionLevel", level);
1001 }
1002
1003 if (item.isMimeTypeKnown()) {
1004 data.insert("iconName", item.iconName());
1005
1006 if (m_requestRole[TypeRole]) {
1007 data.insert("type", item.mimeComment());
1008 }
1009 }
1010
1011 return data;
1012 }
1013
1014 bool KFileItemModel::lessThan(const KFileItem& a, const KFileItem& b) const
1015 {
1016 int result = 0;
1017
1018 if (m_rootExpansionLevel >= 0) {
1019 result = expansionLevelsCompare(a, b);
1020 if (result != 0) {
1021 // The items have parents with different expansion levels
1022 return (sortOrder() == Qt::AscendingOrder) ? result < 0 : result > 0;
1023 }
1024 }
1025
1026 if (m_sortFoldersFirst || m_sortRole == SizeRole) {
1027 const bool isDirA = a.isDir();
1028 const bool isDirB = b.isDir();
1029 if (isDirA && !isDirB) {
1030 return true;
1031 } else if (!isDirA && isDirB) {
1032 return false;
1033 }
1034 }
1035
1036 switch (m_sortRole) {
1037 case NameRole: {
1038 result = stringCompare(a.text(), b.text());
1039 if (result == 0) {
1040 // KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1041 result = stringCompare(a.name(m_caseSensitivity == Qt::CaseInsensitive),
1042 b.name(m_caseSensitivity == Qt::CaseInsensitive));
1043 }
1044 break;
1045 }
1046
1047 case DateRole: {
1048 const KDateTime dateTimeA = a.time(KFileItem::ModificationTime);
1049 const KDateTime dateTimeB = b.time(KFileItem::ModificationTime);
1050 if (dateTimeA < dateTimeB) {
1051 result = -1;
1052 } else if (dateTimeA > dateTimeB) {
1053 result = +1;
1054 }
1055 break;
1056 }
1057
1058 case SizeRole: {
1059 const KIO::filesize_t sizeA = a.size();
1060 const KIO::filesize_t sizeB = b.size();
1061 if (sizeA < sizeB) {
1062 result = -1;
1063 } else if (sizeA > sizeB) {
1064 result = +1;
1065 }
1066 break;
1067 }
1068
1069 case TypeRole: {
1070 // Only compare the type if the MIME-type is known for performance reasons.
1071 // If the MIME-type is unknown it will be resolved later by KFileItemModelRolesUpdater
1072 // and a resorting will be triggered.
1073 if (a.isMimeTypeKnown() && b.isMimeTypeKnown()) {
1074 result = QString::compare(a.mimeComment(), b.mimeComment());
1075 }
1076 break;
1077 }
1078
1079 case RatingRole: {
1080 const int indexA = m_items.value(a.url(), -1);
1081 const int indexB = m_items.value(b.url(), -1);
1082 result = m_data.value(indexA).value("rating").toInt() - m_data.value(indexB).value("rating").toInt();
1083 break;
1084 }
1085
1086 default:
1087 break;
1088 }
1089
1090 if (result == 0) {
1091 // It must be assured that the sort order is always unique even if two values have been
1092 // equal. In this case a comparison of the URL is done which is unique in all cases
1093 // within KDirLister.
1094 result = QString::compare(a.url().url(), b.url().url(), Qt::CaseSensitive);
1095 }
1096
1097 return (sortOrder() == Qt::AscendingOrder) ? result < 0 : result > 0;
1098 }
1099
1100 void KFileItemModel::sort(const KFileItemList::iterator& startIterator, const KFileItemList::iterator& endIterator)
1101 {
1102 KFileItemList::iterator start = startIterator;
1103 KFileItemList::iterator end = endIterator;
1104
1105 // The implementation is based on qSortHelper() from qalgorithms.h
1106 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1107 // In opposite to qSort() it allows to use a member-function for the comparison of elements.
1108 while (1) {
1109 int span = int(end - start);
1110 if (span < 2) {
1111 return;
1112 }
1113
1114 --end;
1115 KFileItemList::iterator low = start, high = end - 1;
1116 KFileItemList::iterator pivot = start + span / 2;
1117
1118 if (lessThan(*end, *start)) {
1119 qSwap(*end, *start);
1120 }
1121 if (span == 2) {
1122 return;
1123 }
1124
1125 if (lessThan(*pivot, *start)) {
1126 qSwap(*pivot, *start);
1127 }
1128 if (lessThan(*end, *pivot)) {
1129 qSwap(*end, *pivot);
1130 }
1131 if (span == 3) {
1132 return;
1133 }
1134
1135 qSwap(*pivot, *end);
1136
1137 while (low < high) {
1138 while (low < high && lessThan(*low, *end)) {
1139 ++low;
1140 }
1141
1142 while (high > low && lessThan(*end, *high)) {
1143 --high;
1144 }
1145 if (low < high) {
1146 qSwap(*low, *high);
1147 ++low;
1148 --high;
1149 } else {
1150 break;
1151 }
1152 }
1153
1154 if (lessThan(*low, *end)) {
1155 ++low;
1156 }
1157
1158 qSwap(*end, *low);
1159 sort(start, low);
1160
1161 start = low + 1;
1162 ++end;
1163 }
1164 }
1165
1166 int KFileItemModel::stringCompare(const QString& a, const QString& b) const
1167 {
1168 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1169 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1170 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1171 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1172
1173 if (m_caseSensitivity == Qt::CaseInsensitive) {
1174 const int result = m_naturalSorting ? KStringHandler::naturalCompare(a, b, Qt::CaseInsensitive)
1175 : QString::compare(a, b, Qt::CaseInsensitive);
1176 if (result != 0) {
1177 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1178 // comparison, still a deterministic sort order is required. A case sensitive
1179 // comparison is done as fallback.
1180 return result;
1181 }
1182 }
1183
1184 return m_naturalSorting ? KStringHandler::naturalCompare(a, b, Qt::CaseSensitive)
1185 : QString::compare(a, b, Qt::CaseSensitive);
1186 }
1187
1188 int KFileItemModel::expansionLevelsCompare(const KFileItem& a, const KFileItem& b) const
1189 {
1190 const KUrl urlA = a.url();
1191 const KUrl urlB = b.url();
1192 if (urlA.directory() == urlB.directory()) {
1193 // Both items have the same directory as parent
1194 return 0;
1195 }
1196
1197 // Check whether one item is the parent of the other item
1198 if (urlA.isParentOf(urlB)) {
1199 return -1;
1200 } else if (urlB.isParentOf(urlA)) {
1201 return +1;
1202 }
1203
1204 // Determine the maximum common path of both items and
1205 // remember the index in 'index'
1206 const QString pathA = urlA.path();
1207 const QString pathB = urlB.path();
1208
1209 const int maxIndex = qMin(pathA.length(), pathB.length()) - 1;
1210 int index = 0;
1211 while (index <= maxIndex && pathA.at(index) == pathB.at(index)) {
1212 ++index;
1213 }
1214 if (index > maxIndex) {
1215 index = maxIndex;
1216 }
1217 while ((pathA.at(index) != QLatin1Char('/') || pathB.at(index) != QLatin1Char('/')) && index > 0) {
1218 --index;
1219 }
1220
1221 // Determine the first sub-path after the common path and
1222 // check whether it represents a directory or already a file
1223 bool isDirA = true;
1224 const QString subPathA = subPath(a, pathA, index, &isDirA);
1225 bool isDirB = true;
1226 const QString subPathB = subPath(b, pathB, index, &isDirB);
1227
1228 if (isDirA && !isDirB) {
1229 return -1;
1230 } else if (!isDirA && isDirB) {
1231 return +1;
1232 }
1233
1234 return stringCompare(subPathA, subPathB);
1235 }
1236
1237 QString KFileItemModel::subPath(const KFileItem& item,
1238 const QString& itemPath,
1239 int start,
1240 bool* isDir) const
1241 {
1242 Q_ASSERT(isDir);
1243 const int pathIndex = itemPath.indexOf('/', start + 1);
1244 *isDir = (pathIndex > 0) || item.isDir();
1245 return itemPath.mid(start, pathIndex - start);
1246 }
1247
1248 bool KFileItemModel::useMaximumUpdateInterval() const
1249 {
1250 const KDirLister* dirLister = m_dirLister.data();
1251 return dirLister && !dirLister->url().isLocalFile();
1252 }
1253
1254 QList<QPair<int, QVariant> > KFileItemModel::nameRoleGroups() const
1255 {
1256 Q_ASSERT(!m_data.isEmpty());
1257
1258 const int maxIndex = count() - 1;
1259 QList<QPair<int, QVariant> > groups;
1260
1261 QString groupValue;
1262 QChar firstChar;
1263 bool isLetter = false;
1264 for (int i = 0; i <= maxIndex; ++i) {
1265 if (isChildItem(i)) {
1266 continue;
1267 }
1268
1269 const QString name = m_data.at(i).value("name").toString();
1270
1271 // Use the first character of the name as group indication
1272 QChar newFirstChar = name.at(0).toUpper();
1273 if (newFirstChar == QLatin1Char('~') && name.length() > 1) {
1274 newFirstChar = name.at(1);
1275 }
1276
1277 if (firstChar != newFirstChar) {
1278 QString newGroupValue;
1279 if (newFirstChar >= QLatin1Char('A') && newFirstChar <= QLatin1Char('Z')) {
1280 // Apply group 'A' - 'Z'
1281 newGroupValue = newFirstChar;
1282 isLetter = true;
1283 } else if (newFirstChar >= QLatin1Char('0') && newFirstChar <= QLatin1Char('9')) {
1284 // Apply group '0 - 9' for any name that starts with a digit
1285 newGroupValue = i18nc("@title:group Groups that start with a digit", "0 - 9");
1286 isLetter = false;
1287 } else {
1288 if (isLetter) {
1289 // If the current group is 'A' - 'Z' check whether a locale character
1290 // fits into the existing group.
1291 // TODO: This does not work in the case if e.g. the group 'O' starts with
1292 // an umlaut 'O' -> provide unit-test to document this known issue
1293 const QChar prevChar(firstChar.unicode() - ushort(1));
1294 const QChar nextChar(firstChar.unicode() + ushort(1));
1295 const QString currChar(newFirstChar);
1296 const bool partOfCurrentGroup = currChar.localeAwareCompare(prevChar) > 0 &&
1297 currChar.localeAwareCompare(nextChar) < 0;
1298 if (partOfCurrentGroup) {
1299 continue;
1300 }
1301 }
1302 newGroupValue = i18nc("@title:group", "Others");
1303 isLetter = false;
1304 }
1305
1306 if (newGroupValue != groupValue) {
1307 groupValue = newGroupValue;
1308 groups.append(QPair<int, QVariant>(i, newGroupValue));
1309 }
1310
1311 firstChar = newFirstChar;
1312 }
1313 }
1314 return groups;
1315 }
1316
1317 QList<QPair<int, QVariant> > KFileItemModel::sizeRoleGroups() const
1318 {
1319 Q_ASSERT(!m_data.isEmpty());
1320
1321 const int maxIndex = count() - 1;
1322 QList<QPair<int, QVariant> > groups;
1323
1324 QString groupValue;
1325 for (int i = 0; i <= maxIndex; ++i) {
1326 if (isChildItem(i)) {
1327 continue;
1328 }
1329
1330 const KFileItem& item = m_sortedItems.at(i);
1331 const KIO::filesize_t fileSize = !item.isNull() ? item.size() : ~0U;
1332 QString newGroupValue;
1333 if (!item.isNull() && item.isDir()) {
1334 newGroupValue = i18nc("@title:group Size", "Folders");
1335 } else if (fileSize < 5 * 1024 * 1024) {
1336 newGroupValue = i18nc("@title:group Size", "Small");
1337 } else if (fileSize < 10 * 1024 * 1024) {
1338 newGroupValue = i18nc("@title:group Size", "Medium");
1339 } else {
1340 newGroupValue = i18nc("@title:group Size", "Big");
1341 }
1342
1343 if (newGroupValue != groupValue) {
1344 groupValue = newGroupValue;
1345 groups.append(QPair<int, QVariant>(i, newGroupValue));
1346 }
1347 }
1348
1349 return groups;
1350 }
1351
1352 QList<QPair<int, QVariant> > KFileItemModel::dateRoleGroups() const
1353 {
1354 Q_ASSERT(!m_data.isEmpty());
1355
1356 const int maxIndex = count() - 1;
1357 QList<QPair<int, QVariant> > groups;
1358
1359 const QDate currentDate = KDateTime::currentLocalDateTime().date();
1360
1361 int yearForCurrentWeek = 0;
1362 int currentWeek = currentDate.weekNumber(&yearForCurrentWeek);
1363 if (yearForCurrentWeek == currentDate.year() + 1) {
1364 currentWeek = 53;
1365 }
1366
1367 QDate previousModifiedDate;
1368 QString groupValue;
1369 for (int i = 0; i <= maxIndex; ++i) {
1370 if (isChildItem(i)) {
1371 continue;
1372 }
1373
1374 const KDateTime modifiedTime = m_sortedItems.at(i).time(KFileItem::ModificationTime);
1375 const QDate modifiedDate = modifiedTime.date();
1376 if (modifiedDate == previousModifiedDate) {
1377 // The current item is in the same group as the previous item
1378 continue;
1379 }
1380 previousModifiedDate = modifiedDate;
1381
1382 const int daysDistance = modifiedDate.daysTo(currentDate);
1383
1384 int yearForModifiedWeek = 0;
1385 int modifiedWeek = modifiedDate.weekNumber(&yearForModifiedWeek);
1386 if (yearForModifiedWeek == modifiedDate.year() + 1) {
1387 modifiedWeek = 53;
1388 }
1389
1390 QString newGroupValue;
1391 if (currentDate.year() == modifiedDate.year() && currentDate.month() == modifiedDate.month()) {
1392 if (modifiedWeek > currentWeek) {
1393 // Usecase: modified date = 2010-01-01, current date = 2010-01-22
1394 // modified week = 53, current week = 3
1395 modifiedWeek = 0;
1396 }
1397 switch (currentWeek - modifiedWeek) {
1398 case 0:
1399 switch (daysDistance) {
1400 case 0: newGroupValue = i18nc("@title:group Date", "Today"); break;
1401 case 1: newGroupValue = i18nc("@title:group Date", "Yesterday"); break;
1402 default: newGroupValue = modifiedTime.toString(i18nc("@title:group The week day name: %A", "%A"));
1403 }
1404 break;
1405 case 1:
1406 newGroupValue = i18nc("@title:group Date", "Last Week");
1407 break;
1408 case 2:
1409 newGroupValue = i18nc("@title:group Date", "Two Weeks Ago");
1410 break;
1411 case 3:
1412 newGroupValue = i18nc("@title:group Date", "Three Weeks Ago");
1413 break;
1414 case 4:
1415 case 5:
1416 newGroupValue = i18nc("@title:group Date", "Earlier this Month");
1417 break;
1418 default:
1419 Q_ASSERT(false);
1420 }
1421 } else {
1422 const QDate lastMonthDate = currentDate.addMonths(-1);
1423 if (lastMonthDate.year() == modifiedDate.year() && lastMonthDate.month() == modifiedDate.month()) {
1424 if (daysDistance == 1) {
1425 newGroupValue = modifiedTime.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Yesterday (%B, %Y)"));
1426 } else if (daysDistance <= 7) {
1427 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)"));
1428 } else if (daysDistance <= 7 * 2) {
1429 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)"));
1430 } else if (daysDistance <= 7 * 3) {
1431 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)"));
1432 } else if (daysDistance <= 7 * 4) {
1433 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)"));
1434 } else {
1435 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"));
1436 }
1437 } else {
1438 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"));
1439 }
1440 }
1441
1442 if (newGroupValue != groupValue) {
1443 groupValue = newGroupValue;
1444 groups.append(QPair<int, QVariant>(i, newGroupValue));
1445 }
1446 }
1447
1448 return groups;
1449 }
1450
1451 QList<QPair<int, QVariant> > KFileItemModel::permissionRoleGroups() const
1452 {
1453 Q_ASSERT(!m_data.isEmpty());
1454
1455 const int maxIndex = count() - 1;
1456 QList<QPair<int, QVariant> > groups;
1457
1458 QString permissionsString;
1459 QString groupValue;
1460 for (int i = 0; i <= maxIndex; ++i) {
1461 if (isChildItem(i)) {
1462 continue;
1463 }
1464
1465 const QString newPermissionsString = m_data.at(i).value("permissions").toString();
1466 if (newPermissionsString == permissionsString) {
1467 continue;
1468 }
1469 permissionsString = newPermissionsString;
1470
1471 const QFileInfo info(m_sortedItems.at(i).url().pathOrUrl());
1472
1473 // Set user string
1474 QString user;
1475 if (info.permission(QFile::ReadUser)) {
1476 user = i18nc("@item:intext Access permission, concatenated", "Read, ");
1477 }
1478 if (info.permission(QFile::WriteUser)) {
1479 user += i18nc("@item:intext Access permission, concatenated", "Write, ");
1480 }
1481 if (info.permission(QFile::ExeUser)) {
1482 user += i18nc("@item:intext Access permission, concatenated", "Execute, ");
1483 }
1484 user = user.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user.mid(0, user.count() - 2);
1485
1486 // Set group string
1487 QString group;
1488 if (info.permission(QFile::ReadGroup)) {
1489 group = i18nc("@item:intext Access permission, concatenated", "Read, ");
1490 }
1491 if (info.permission(QFile::WriteGroup)) {
1492 group += i18nc("@item:intext Access permission, concatenated", "Write, ");
1493 }
1494 if (info.permission(QFile::ExeGroup)) {
1495 group += i18nc("@item:intext Access permission, concatenated", "Execute, ");
1496 }
1497 group = group.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group.mid(0, group.count() - 2);
1498
1499 // Set others string
1500 QString others;
1501 if (info.permission(QFile::ReadOther)) {
1502 others = i18nc("@item:intext Access permission, concatenated", "Read, ");
1503 }
1504 if (info.permission(QFile::WriteOther)) {
1505 others += i18nc("@item:intext Access permission, concatenated", "Write, ");
1506 }
1507 if (info.permission(QFile::ExeOther)) {
1508 others += i18nc("@item:intext Access permission, concatenated", "Execute, ");
1509 }
1510 others = others.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others.mid(0, others.count() - 2);
1511
1512 const QString newGroupValue = i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user, group, others);
1513 if (newGroupValue != groupValue) {
1514 groupValue = newGroupValue;
1515 groups.append(QPair<int, QVariant>(i, newGroupValue));
1516 }
1517 }
1518
1519 return groups;
1520 }
1521
1522 QList<QPair<int, QVariant> > KFileItemModel::ratingRoleGroups() const
1523 {
1524 Q_ASSERT(!m_data.isEmpty());
1525
1526 const int maxIndex = count() - 1;
1527 QList<QPair<int, QVariant> > groups;
1528
1529 int groupValue;
1530 for (int i = 0; i <= maxIndex; ++i) {
1531 if (isChildItem(i)) {
1532 continue;
1533 }
1534 const int newGroupValue = m_data.at(i).value("rating").toInt();
1535 if (newGroupValue != groupValue) {
1536 groupValue = newGroupValue;
1537 groups.append(QPair<int, QVariant>(i, newGroupValue));
1538 }
1539 }
1540
1541 return groups;
1542 }
1543
1544 QList<QPair<int, QVariant> > KFileItemModel::genericStringRoleGroups(const QByteArray& role) const
1545 {
1546 Q_ASSERT(!m_data.isEmpty());
1547
1548 const int maxIndex = count() - 1;
1549 QList<QPair<int, QVariant> > groups;
1550
1551 QString groupValue;
1552 for (int i = 0; i <= maxIndex; ++i) {
1553 if (isChildItem(i)) {
1554 continue;
1555 }
1556 const QString newGroupValue = m_data.at(i).value(role).toString();
1557 if (newGroupValue != groupValue) {
1558 groupValue = newGroupValue;
1559 groups.append(QPair<int, QVariant>(i, newGroupValue));
1560 }
1561 }
1562
1563 return groups;
1564 }
1565
1566 #include "kfileitemmodel.moc"