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