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