]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kfileitemmodel.cpp
afc6decee81309d32d0fec60ef8fb21cd094a067
[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_restoredExpandedUrls()
53 {
54 // Apply default roles that should be determined
55 resetRoles();
56 m_requestRole[NameRole] = true;
57 m_requestRole[IsDirRole] = true;
58 m_roles.insert("name");
59 m_roles.insert("isDir");
60
61 Q_ASSERT(dirLister);
62
63 connect(dirLister, SIGNAL(canceled()), this, SLOT(slotCanceled()));
64 connect(dirLister, SIGNAL(completed()), this, SLOT(slotCompleted()));
65 connect(dirLister, SIGNAL(newItems(KFileItemList)), this, SLOT(slotNewItems(KFileItemList)));
66 connect(dirLister, SIGNAL(itemsDeleted(KFileItemList)), this, SLOT(slotItemsDeleted(KFileItemList)));
67 connect(dirLister, SIGNAL(refreshItems(QList<QPair<KFileItem,KFileItem> >)), this, SLOT(slotRefreshItems(QList<QPair<KFileItem,KFileItem> >)));
68 connect(dirLister, SIGNAL(clear()), this, SLOT(slotClear()));
69 connect(dirLister, SIGNAL(clear(KUrl)), this, SLOT(slotClear(KUrl)));
70
71 // Although the layout engine of KItemListView is fast it is very inefficient to e.g.
72 // emit 50 itemsInserted()-signals each 100 ms. m_minimumUpdateIntervalTimer assures that updates
73 // are done in 1 second intervals for equal operations.
74 m_minimumUpdateIntervalTimer = new QTimer(this);
75 m_minimumUpdateIntervalTimer->setInterval(1000);
76 m_minimumUpdateIntervalTimer->setSingleShot(true);
77 connect(m_minimumUpdateIntervalTimer, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
78
79 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
80 // before the completed() or canceled() signal has been emitted.
81 m_maximumUpdateIntervalTimer = new QTimer(this);
82 m_maximumUpdateIntervalTimer->setInterval(2000);
83 m_maximumUpdateIntervalTimer->setSingleShot(true);
84 connect(m_maximumUpdateIntervalTimer, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
85
86 // 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(1000);
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::restoreExpandedUrls(const QSet<KUrl>& urls)
435 {
436 m_restoredExpandedUrls = urls;
437 }
438
439 void KFileItemModel::onGroupedSortingChanged(bool current)
440 {
441 Q_UNUSED(current);
442 m_groups.clear();
443 }
444
445 void KFileItemModel::onSortRoleChanged(const QByteArray& current, const QByteArray& previous)
446 {
447 Q_UNUSED(previous);
448 m_sortRole = roleIndex(current);
449
450 #ifdef KFILEITEMMODEL_DEBUG
451 if (!m_requestRole[m_sortRole]) {
452 kWarning() << "The sort-role has been changed to a role that has not been received yet";
453 }
454 #endif
455
456 resortAllItems();
457 }
458
459 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous)
460 {
461 Q_UNUSED(current);
462 Q_UNUSED(previous);
463 resortAllItems();
464 }
465
466 void KFileItemModel::resortAllItems()
467 {
468 m_resortAllItemsTimer->stop();
469
470 const int itemCount = count();
471 if (itemCount <= 0) {
472 return;
473 }
474
475 #ifdef KFILEITEMMODEL_DEBUG
476 QElapsedTimer timer;
477 timer.start();
478 kDebug() << "===========================================================";
479 kDebug() << "Resorting" << itemCount << "items";
480 #endif
481
482 // Remember the order of the current URLs so
483 // that it can be determined which indexes have
484 // been moved because of the resorting.
485 QList<KUrl> oldUrls;
486 oldUrls.reserve(itemCount);
487 foreach (const ItemData* itemData, m_itemData) {
488 oldUrls.append(itemData->item.url());
489 }
490
491 m_groups.clear();
492 m_items.clear();
493
494 // Resort the items
495 sort(m_itemData.begin(), m_itemData.end());
496 for (int i = 0; i < itemCount; ++i) {
497 m_items.insert(m_itemData.at(i)->item.url(), i);
498 }
499
500 // Determine the indexes that have been moved
501 bool emitItemsMoved = false;
502 QList<int> movedToIndexes;
503 movedToIndexes.reserve(itemCount);
504 for (int i = 0; i < itemCount; i++) {
505 const int newIndex = m_items.value(oldUrls.at(i).url());
506 movedToIndexes.append(newIndex);
507 if (!emitItemsMoved && newIndex != i) {
508 emitItemsMoved = true;
509 }
510 }
511
512 if (emitItemsMoved) {
513 emit itemsMoved(KItemRange(0, itemCount), movedToIndexes);
514 }
515
516 #ifdef KFILEITEMMODEL_DEBUG
517 kDebug() << "[TIME] Resorting of" << itemCount << "items:" << timer.elapsed();
518 #endif
519 }
520
521 void KFileItemModel::slotCompleted()
522 {
523 if (m_restoredExpandedUrls.isEmpty() && m_minimumUpdateIntervalTimer->isActive()) {
524 // dispatchPendingItems() will be called when the timer
525 // has been expired.
526 m_pendingEmitLoadingCompleted = true;
527 return;
528 }
529
530 m_pendingEmitLoadingCompleted = false;
531 dispatchPendingItemsToInsert();
532
533 if (!m_restoredExpandedUrls.isEmpty()) {
534 // Try to find a URL that can be expanded.
535 // Note that the parent folder must be expanded before any of its subfolders become visible.
536 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
537 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
538 foreach(const KUrl& url, m_restoredExpandedUrls) {
539 const int index = m_items.value(url, -1);
540 if (index >= 0) {
541 // We have found an expandable URL. Expand it and return - when
542 // the dir lister has finished, this slot will be called again.
543 m_restoredExpandedUrls.remove(url);
544 setExpanded(index, true);
545 return;
546 }
547 }
548
549 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
550 // if these URLs have been deleted in the meantime.
551 m_restoredExpandedUrls.clear();
552 }
553
554 emit loadingCompleted();
555 m_minimumUpdateIntervalTimer->start();
556 }
557
558 void KFileItemModel::slotCanceled()
559 {
560 m_minimumUpdateIntervalTimer->stop();
561 m_maximumUpdateIntervalTimer->stop();
562 dispatchPendingItemsToInsert();
563 }
564
565 void KFileItemModel::slotNewItems(const KFileItemList& items)
566 {
567 m_pendingItemsToInsert.append(items);
568
569 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer->isActive()) {
570 // Assure that items get dispatched if no completed() or canceled() signal is
571 // emitted during the maximum update interval.
572 m_maximumUpdateIntervalTimer->start();
573 }
574 }
575
576 void KFileItemModel::slotItemsDeleted(const KFileItemList& items)
577 {
578 if (!m_pendingItemsToInsert.isEmpty()) {
579 insertItems(m_pendingItemsToInsert);
580 m_pendingItemsToInsert.clear();
581 }
582 removeItems(items);
583 }
584
585 void KFileItemModel::slotRefreshItems(const QList<QPair<KFileItem, KFileItem> >& items)
586 {
587 Q_ASSERT(!items.isEmpty());
588 #ifdef KFILEITEMMODEL_DEBUG
589 kDebug() << "Refreshing" << items.count() << "items";
590 #endif
591
592 m_groups.clear();
593
594 // Get the indexes of all items that have been refreshed
595 QList<int> indexes;
596 indexes.reserve(items.count());
597
598 QListIterator<QPair<KFileItem, KFileItem> > it(items);
599 while (it.hasNext()) {
600 const QPair<KFileItem, KFileItem>& itemPair = it.next();
601 const int index = m_items.value(itemPair.second.url(), -1);
602 if (index >= 0) {
603 indexes.append(index);
604 }
605 }
606
607 // If the changed items have been created recently, they might not be in m_items yet.
608 // In that case, the list 'indexes' might be empty.
609 if (indexes.isEmpty()) {
610 return;
611 }
612
613 // Extract the item-ranges out of the changed indexes
614 qSort(indexes);
615
616 KItemRangeList itemRangeList;
617 int rangeIndex = 0;
618 int rangeCount = 1;
619 int previousIndex = indexes.at(0);
620
621 const int maxIndex = indexes.count() - 1;
622 for (int i = 1; i <= maxIndex; ++i) {
623 const int currentIndex = indexes.at(i);
624 if (currentIndex == previousIndex + 1) {
625 ++rangeCount;
626 } else {
627 itemRangeList.append(KItemRange(rangeIndex, rangeCount));
628
629 rangeIndex = currentIndex;
630 rangeCount = 1;
631 }
632 previousIndex = currentIndex;
633 }
634
635 if (rangeCount > 0) {
636 itemRangeList.append(KItemRange(rangeIndex, rangeCount));
637 }
638
639 emit itemsChanged(itemRangeList, QSet<QByteArray>());
640 }
641
642 void KFileItemModel::slotClear()
643 {
644 #ifdef KFILEITEMMODEL_DEBUG
645 kDebug() << "Clearing all items";
646 #endif
647
648 m_groups.clear();
649
650 m_minimumUpdateIntervalTimer->stop();
651 m_maximumUpdateIntervalTimer->stop();
652 m_resortAllItemsTimer->stop();
653 m_pendingItemsToInsert.clear();
654
655 m_rootExpansionLevel = -1;
656
657 const int removedCount = m_itemData.count();
658 if (removedCount > 0) {
659 qDeleteAll(m_itemData);
660 m_itemData.clear();
661 m_items.clear();
662 emit itemsRemoved(KItemRangeList() << KItemRange(0, removedCount));
663 }
664
665 m_expandedUrls.clear();
666 }
667
668 void KFileItemModel::slotClear(const KUrl& url)
669 {
670 Q_UNUSED(url);
671 }
672
673 void KFileItemModel::dispatchPendingItemsToInsert()
674 {
675 if (!m_pendingItemsToInsert.isEmpty()) {
676 insertItems(m_pendingItemsToInsert);
677 m_pendingItemsToInsert.clear();
678 }
679
680 if (m_pendingEmitLoadingCompleted) {
681 emit loadingCompleted();
682 }
683 }
684
685 void KFileItemModel::insertItems(const KFileItemList& items)
686 {
687 if (items.isEmpty()) {
688 return;
689 }
690
691 #ifdef KFILEITEMMODEL_DEBUG
692 QElapsedTimer timer;
693 timer.start();
694 kDebug() << "===========================================================";
695 kDebug() << "Inserting" << items.count() << "items";
696 #endif
697
698 m_groups.clear();
699
700 QList<ItemData*> sortedItems = createItemDataList(items);
701 sort(sortedItems.begin(), sortedItems.end());
702
703 #ifdef KFILEITEMMODEL_DEBUG
704 kDebug() << "[TIME] Sorting:" << timer.elapsed();
705 #endif
706
707 KItemRangeList itemRanges;
708 int targetIndex = 0;
709 int sourceIndex = 0;
710 int insertedAtIndex = -1; // Index for the current item-range
711 int insertedCount = 0; // Count for the current item-range
712 int previouslyInsertedCount = 0; // Sum of previously inserted items for all ranges
713 while (sourceIndex < sortedItems.count()) {
714 // Find target index from m_items to insert the current item
715 // in a sorted order
716 const int previousTargetIndex = targetIndex;
717 while (targetIndex < m_itemData.count()) {
718 if (!lessThan(m_itemData.at(targetIndex), sortedItems.at(sourceIndex))) {
719 break;
720 }
721 ++targetIndex;
722 }
723
724 if (targetIndex - previousTargetIndex > 0 && insertedAtIndex >= 0) {
725 itemRanges << KItemRange(insertedAtIndex, insertedCount);
726 previouslyInsertedCount += insertedCount;
727 insertedAtIndex = targetIndex - previouslyInsertedCount;
728 insertedCount = 0;
729 }
730
731 // Insert item at the position targetIndex by transfering
732 // the ownership of the item-data from sortedItems to m_itemData.
733 // m_items will be inserted after the loop (see comment below)
734 m_itemData.insert(targetIndex, sortedItems.at(sourceIndex));
735 ++insertedCount;
736
737 if (insertedAtIndex < 0) {
738 insertedAtIndex = targetIndex;
739 Q_ASSERT(previouslyInsertedCount == 0);
740 }
741 ++targetIndex;
742 ++sourceIndex;
743 }
744
745 // The indexes of all m_items must be adjusted, not only the index
746 // of the new items
747 const int itemDataCount = m_itemData.count();
748 for (int i = 0; i < itemDataCount; ++i) {
749 m_items.insert(m_itemData.at(i)->item.url(), i);
750 }
751
752 itemRanges << KItemRange(insertedAtIndex, insertedCount);
753 emit itemsInserted(itemRanges);
754
755 #ifdef KFILEITEMMODEL_DEBUG
756 kDebug() << "[TIME] Inserting of" << items.count() << "items:" << timer.elapsed();
757 #endif
758 }
759
760 void KFileItemModel::removeItems(const KFileItemList& items)
761 {
762 if (items.isEmpty()) {
763 return;
764 }
765
766 #ifdef KFILEITEMMODEL_DEBUG
767 kDebug() << "Removing " << items.count() << "items";
768 #endif
769
770 m_groups.clear();
771
772 QList<ItemData*> sortedItems = createItemDataList(items);
773 sort(sortedItems.begin(), sortedItems.end());
774
775 QList<int> indexesToRemove;
776 indexesToRemove.reserve(items.count());
777
778 // Calculate the item ranges that will get deleted
779 KItemRangeList itemRanges;
780 int removedAtIndex = -1;
781 int removedCount = 0;
782 int targetIndex = 0;
783 foreach (const ItemData* itemData, sortedItems) {
784 const KFileItem& itemToRemove = itemData->item;
785
786 const int previousTargetIndex = targetIndex;
787 while (targetIndex < m_itemData.count()) {
788 if (m_itemData.at(targetIndex)->item.url() == itemToRemove.url()) {
789 break;
790 }
791 ++targetIndex;
792 }
793 if (targetIndex >= m_itemData.count()) {
794 kWarning() << "Item that should be deleted has not been found!";
795 return;
796 }
797
798 if (targetIndex - previousTargetIndex > 0 && removedAtIndex >= 0) {
799 itemRanges << KItemRange(removedAtIndex, removedCount);
800 removedAtIndex = targetIndex;
801 removedCount = 0;
802 }
803
804 indexesToRemove.append(targetIndex);
805 if (removedAtIndex < 0) {
806 removedAtIndex = targetIndex;
807 }
808 ++removedCount;
809 ++targetIndex;
810 }
811 qDeleteAll(sortedItems);
812 sortedItems.clear();
813
814 // Delete the items
815 for (int i = indexesToRemove.count() - 1; i >= 0; --i) {
816 const int indexToRemove = indexesToRemove.at(i);
817 delete m_itemData.at(indexToRemove);
818 m_itemData.removeAt(indexToRemove);
819 }
820
821 // The indexes of all m_items must be adjusted, not only the index
822 // of the removed items
823 const int itemDataCount = m_itemData.count();
824 for (int i = 0; i < itemDataCount; ++i) {
825 m_items.insert(m_itemData.at(i)->item.url(), i);
826 }
827
828 if (count() <= 0) {
829 m_rootExpansionLevel = -1;
830 }
831
832 itemRanges << KItemRange(removedAtIndex, removedCount);
833 emit itemsRemoved(itemRanges);
834 }
835
836 QList<KFileItemModel::ItemData*> KFileItemModel::createItemDataList(const KFileItemList& items) const
837 {
838 QList<ItemData*> itemDataList;
839 itemDataList.reserve(items.count());
840
841 foreach (const KFileItem& item, items) {
842 ItemData* itemData = new ItemData();
843 itemData->item = item;
844 itemData->values = retrieveData(item);
845 itemDataList.append(itemData);
846 }
847
848 return itemDataList;
849 }
850
851 void KFileItemModel::removeExpandedItems()
852 {
853 KFileItemList expandedItems;
854
855 const int maxIndex = m_itemData.count() - 1;
856 for (int i = 0; i <= maxIndex; ++i) {
857 const ItemData* itemData = m_itemData.at(i);
858 if (itemData->values.value("expansionLevel").toInt() > 0) {
859 expandedItems.append(itemData->item);
860 }
861 }
862
863 // The m_rootExpansionLevel may not get reset before all items with
864 // a bigger expansionLevel have been removed.
865 Q_ASSERT(m_rootExpansionLevel >= 0);
866 removeItems(expandedItems);
867
868 m_rootExpansionLevel = -1;
869 m_expandedUrls.clear();
870 }
871
872 void KFileItemModel::resetRoles()
873 {
874 for (int i = 0; i < RolesCount; ++i) {
875 m_requestRole[i] = false;
876 }
877 }
878
879 KFileItemModel::Role KFileItemModel::roleIndex(const QByteArray& role) const
880 {
881 static QHash<QByteArray, Role> rolesHash;
882 if (rolesHash.isEmpty()) {
883 rolesHash.insert("name", NameRole);
884 rolesHash.insert("size", SizeRole);
885 rolesHash.insert("date", DateRole);
886 rolesHash.insert("permissions", PermissionsRole);
887 rolesHash.insert("owner", OwnerRole);
888 rolesHash.insert("group", GroupRole);
889 rolesHash.insert("type", TypeRole);
890 rolesHash.insert("destination", DestinationRole);
891 rolesHash.insert("path", PathRole);
892 rolesHash.insert("comment", CommentRole);
893 rolesHash.insert("tags", TagsRole);
894 rolesHash.insert("rating", RatingRole);
895 rolesHash.insert("isDir", IsDirRole);
896 rolesHash.insert("isExpanded", IsExpandedRole);
897 rolesHash.insert("expansionLevel", ExpansionLevelRole);
898 }
899 return rolesHash.value(role, NoRole);
900 }
901
902 QHash<QByteArray, QVariant> KFileItemModel::retrieveData(const KFileItem& item) const
903 {
904 // It is important to insert only roles that are fast to retrieve. E.g.
905 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
906 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
907 QHash<QByteArray, QVariant> data;
908 data.insert("iconPixmap", QPixmap());
909
910 const bool isDir = item.isDir();
911 if (m_requestRole[IsDirRole]) {
912 data.insert("isDir", isDir);
913 }
914
915 if (m_requestRole[NameRole]) {
916 data.insert("name", item.name());
917 }
918
919 if (m_requestRole[SizeRole]) {
920 if (isDir) {
921 data.insert("size", QVariant());
922 } else {
923 data.insert("size", item.size());
924 }
925 }
926
927 if (m_requestRole[DateRole]) {
928 // Don't use KFileItem::timeString() as this is too expensive when
929 // having several thousands of items. Instead the formatting of the
930 // date-time will be done on-demand by the view when the date will be shown.
931 const KDateTime dateTime = item.time(KFileItem::ModificationTime);
932 data.insert("date", dateTime.dateTime());
933 }
934
935 if (m_requestRole[PermissionsRole]) {
936 data.insert("permissions", item.permissionsString());
937 }
938
939 if (m_requestRole[OwnerRole]) {
940 data.insert("owner", item.user());
941 }
942
943 if (m_requestRole[GroupRole]) {
944 data.insert("group", item.group());
945 }
946
947 if (m_requestRole[DestinationRole]) {
948 QString destination = item.linkDest();
949 if (destination.isEmpty()) {
950 destination = i18nc("@item:intable", "No destination");
951 }
952 data.insert("destination", destination);
953 }
954
955 if (m_requestRole[PathRole]) {
956 data.insert("path", item.localPath());
957 }
958
959 if (m_requestRole[IsExpandedRole]) {
960 data.insert("isExpanded", false);
961 }
962
963 if (m_requestRole[ExpansionLevelRole]) {
964 if (m_rootExpansionLevel < 0) {
965 KDirLister* dirLister = m_dirLister.data();
966 if (dirLister) {
967 const QString rootDir = dirLister->url().directory(KUrl::AppendTrailingSlash);
968 m_rootExpansionLevel = rootDir.count('/');
969 }
970 }
971 const QString dir = item.url().directory(KUrl::AppendTrailingSlash);
972 const int level = dir.count('/') - m_rootExpansionLevel - 1;
973 data.insert("expansionLevel", level);
974 }
975
976 if (item.isMimeTypeKnown()) {
977 data.insert("iconName", item.iconName());
978
979 if (m_requestRole[TypeRole]) {
980 data.insert("type", item.mimeComment());
981 }
982 }
983
984 return data;
985 }
986
987 bool KFileItemModel::lessThan(const ItemData* a, const ItemData* b) const
988 {
989 const KFileItem& itemA = a->item;
990 const KFileItem& itemB = b->item;
991
992 int result = 0;
993
994 if (m_rootExpansionLevel >= 0) {
995 result = expansionLevelsCompare(itemA, itemB);
996 if (result != 0) {
997 // The items have parents with different expansion levels
998 return (sortOrder() == Qt::AscendingOrder) ? result < 0 : result > 0;
999 }
1000 }
1001
1002 if (m_sortFoldersFirst || m_sortRole == SizeRole) {
1003 const bool isDirA = itemA.isDir();
1004 const bool isDirB = itemB.isDir();
1005 if (isDirA && !isDirB) {
1006 return true;
1007 } else if (!isDirA && isDirB) {
1008 return false;
1009 }
1010 }
1011
1012 switch (m_sortRole) {
1013 case NameRole: {
1014 result = stringCompare(itemA.text(), itemB.text());
1015 if (result == 0) {
1016 // KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1017 result = stringCompare(itemA.name(m_caseSensitivity == Qt::CaseInsensitive),
1018 itemB.name(m_caseSensitivity == Qt::CaseInsensitive));
1019 }
1020 break;
1021 }
1022
1023 case DateRole: {
1024 const KDateTime dateTimeA = itemA.time(KFileItem::ModificationTime);
1025 const KDateTime dateTimeB = itemB.time(KFileItem::ModificationTime);
1026 if (dateTimeA < dateTimeB) {
1027 result = -1;
1028 } else if (dateTimeA > dateTimeB) {
1029 result = +1;
1030 }
1031 break;
1032 }
1033
1034 case SizeRole: {
1035 if (itemA.isDir()) {
1036 Q_ASSERT(itemB.isDir()); // see "if (m_sortFoldersFirst || m_sortRole == SizeRole)" above
1037
1038 const QVariant valueA = a->values.value("size");
1039 const QVariant valueB = b->values.value("size");
1040
1041 if (valueA.isNull()) {
1042 result = -1;
1043 } else if (valueB.isNull()) {
1044 result = +1;
1045 } else {
1046 result = valueA.value<KIO::filesize_t>() - valueB.value<KIO::filesize_t>();
1047 }
1048 } else {
1049 Q_ASSERT(!itemB.isDir()); // see "if (m_sortFoldersFirst || m_sortRole == SizeRole)" above
1050 result = itemA.size() - itemB.size();
1051 }
1052 break;
1053 }
1054
1055 case TypeRole: {
1056 result = QString::compare(a->values.value("type").toString(),
1057 b->values.value("type").toString());
1058 break;
1059 }
1060
1061 case CommentRole: {
1062 result = QString::compare(a->values.value("comment").toString(),
1063 b->values.value("comment").toString());
1064 break;
1065 }
1066
1067 case TagsRole: {
1068 result = QString::compare(a->values.value("tags").toString(),
1069 b->values.value("tags").toString());
1070 break;
1071 }
1072
1073 case RatingRole: {
1074 result = a->values.value("rating").toInt() - b->values.value("rating").toInt();
1075 break;
1076 }
1077
1078 default:
1079 break;
1080 }
1081
1082 if (result == 0) {
1083 // It must be assured that the sort order is always unique even if two values have been
1084 // equal. In this case a comparison of the URL is done which is unique in all cases
1085 // within KDirLister.
1086 result = QString::compare(itemA.url().url(), itemB.url().url(), Qt::CaseSensitive);
1087 }
1088
1089 return (sortOrder() == Qt::AscendingOrder) ? result < 0 : result > 0;
1090 }
1091
1092 void KFileItemModel::sort(QList<ItemData*>::iterator begin,
1093 QList<ItemData*>::iterator end)
1094 {
1095 // The implementation is based on qStableSortHelper() from qalgorithms.h
1096 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1097 // In opposite to qStableSort() it allows to use a member-function for the comparison of elements.
1098
1099 const int span = end - begin;
1100 if (span < 2) {
1101 return;
1102 }
1103
1104 const QList<ItemData*>::iterator middle = begin + span / 2;
1105 sort(begin, middle);
1106 sort(middle, end);
1107 merge(begin, middle, end);
1108 }
1109
1110 void KFileItemModel::merge(QList<ItemData*>::iterator begin,
1111 QList<ItemData*>::iterator pivot,
1112 QList<ItemData*>::iterator end)
1113 {
1114 // The implementation is based on qMerge() from qalgorithms.h
1115 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1116
1117 const int len1 = pivot - begin;
1118 const int len2 = end - pivot;
1119
1120 if (len1 == 0 || len2 == 0) {
1121 return;
1122 }
1123
1124 if (len1 + len2 == 2) {
1125 if (lessThan(*(begin + 1), *(begin))) {
1126 qSwap(*begin, *(begin + 1));
1127 }
1128 return;
1129 }
1130
1131 QList<ItemData*>::iterator firstCut;
1132 QList<ItemData*>::iterator secondCut;
1133 int len2Half;
1134 if (len1 > len2) {
1135 const int len1Half = len1 / 2;
1136 firstCut = begin + len1Half;
1137 secondCut = lowerBound(pivot, end, *firstCut);
1138 len2Half = secondCut - pivot;
1139 } else {
1140 len2Half = len2 / 2;
1141 secondCut = pivot + len2Half;
1142 firstCut = upperBound(begin, pivot, *secondCut);
1143 }
1144
1145 reverse(firstCut, pivot);
1146 reverse(pivot, secondCut);
1147 reverse(firstCut, secondCut);
1148
1149 const QList<ItemData*>::iterator newPivot = firstCut + len2Half;
1150 merge(begin, firstCut, newPivot);
1151 merge(newPivot, secondCut, end);
1152 }
1153
1154 QList<KFileItemModel::ItemData*>::iterator KFileItemModel::lowerBound(QList<ItemData*>::iterator begin,
1155 QList<ItemData*>::iterator end,
1156 const ItemData* value)
1157 {
1158 // The implementation is based on qLowerBound() from qalgorithms.h
1159 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1160
1161 QList<ItemData*>::iterator middle;
1162 int n = int(end - begin);
1163 int half;
1164
1165 while (n > 0) {
1166 half = n >> 1;
1167 middle = begin + half;
1168 if (lessThan(*middle, value)) {
1169 begin = middle + 1;
1170 n -= half + 1;
1171 } else {
1172 n = half;
1173 }
1174 }
1175 return begin;
1176 }
1177
1178 QList<KFileItemModel::ItemData*>::iterator KFileItemModel::upperBound(QList<ItemData*>::iterator begin,
1179 QList<ItemData*>::iterator end,
1180 const ItemData* value)
1181 {
1182 // The implementation is based on qUpperBound() from qalgorithms.h
1183 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1184
1185 QList<ItemData*>::iterator middle;
1186 int n = end - begin;
1187 int half;
1188
1189 while (n > 0) {
1190 half = n >> 1;
1191 middle = begin + half;
1192 if (lessThan(value, *middle)) {
1193 n = half;
1194 } else {
1195 begin = middle + 1;
1196 n -= half + 1;
1197 }
1198 }
1199 return begin;
1200 }
1201
1202 void KFileItemModel::reverse(QList<ItemData*>::iterator begin,
1203 QList<ItemData*>::iterator end)
1204 {
1205 // The implementation is based on qReverse() from qalgorithms.h
1206 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1207
1208 --end;
1209 while (begin < end) {
1210 qSwap(*begin++, *end--);
1211 }
1212 }
1213
1214 int KFileItemModel::stringCompare(const QString& a, const QString& b) const
1215 {
1216 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1217 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1218 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1219 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1220
1221 if (m_caseSensitivity == Qt::CaseInsensitive) {
1222 const int result = m_naturalSorting ? KStringHandler::naturalCompare(a, b, Qt::CaseInsensitive)
1223 : QString::compare(a, b, Qt::CaseInsensitive);
1224 if (result != 0) {
1225 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1226 // comparison, still a deterministic sort order is required. A case sensitive
1227 // comparison is done as fallback.
1228 return result;
1229 }
1230 }
1231
1232 return m_naturalSorting ? KStringHandler::naturalCompare(a, b, Qt::CaseSensitive)
1233 : QString::compare(a, b, Qt::CaseSensitive);
1234 }
1235
1236 int KFileItemModel::expansionLevelsCompare(const KFileItem& a, const KFileItem& b) const
1237 {
1238 const KUrl urlA = a.url();
1239 const KUrl urlB = b.url();
1240 if (urlA.directory() == urlB.directory()) {
1241 // Both items have the same directory as parent
1242 return 0;
1243 }
1244
1245 // Check whether one item is the parent of the other item
1246 if (urlA.isParentOf(urlB)) {
1247 return -1;
1248 } else if (urlB.isParentOf(urlA)) {
1249 return +1;
1250 }
1251
1252 // Determine the maximum common path of both items and
1253 // remember the index in 'index'
1254 const QString pathA = urlA.path();
1255 const QString pathB = urlB.path();
1256
1257 const int maxIndex = qMin(pathA.length(), pathB.length()) - 1;
1258 int index = 0;
1259 while (index <= maxIndex && pathA.at(index) == pathB.at(index)) {
1260 ++index;
1261 }
1262 if (index > maxIndex) {
1263 index = maxIndex;
1264 }
1265 while ((pathA.at(index) != QLatin1Char('/') || pathB.at(index) != QLatin1Char('/')) && index > 0) {
1266 --index;
1267 }
1268
1269 // Determine the first sub-path after the common path and
1270 // check whether it represents a directory or already a file
1271 bool isDirA = true;
1272 const QString subPathA = subPath(a, pathA, index, &isDirA);
1273 bool isDirB = true;
1274 const QString subPathB = subPath(b, pathB, index, &isDirB);
1275
1276 if (isDirA && !isDirB) {
1277 return -1;
1278 } else if (!isDirA && isDirB) {
1279 return +1;
1280 }
1281
1282 return stringCompare(subPathA, subPathB);
1283 }
1284
1285 QString KFileItemModel::subPath(const KFileItem& item,
1286 const QString& itemPath,
1287 int start,
1288 bool* isDir) const
1289 {
1290 Q_ASSERT(isDir);
1291 const int pathIndex = itemPath.indexOf('/', start + 1);
1292 *isDir = (pathIndex > 0) || item.isDir();
1293 return itemPath.mid(start, pathIndex - start);
1294 }
1295
1296 bool KFileItemModel::useMaximumUpdateInterval() const
1297 {
1298 const KDirLister* dirLister = m_dirLister.data();
1299 return dirLister && !dirLister->url().isLocalFile();
1300 }
1301
1302 QList<QPair<int, QVariant> > KFileItemModel::nameRoleGroups() const
1303 {
1304 Q_ASSERT(!m_itemData.isEmpty());
1305
1306 const int maxIndex = count() - 1;
1307 QList<QPair<int, QVariant> > groups;
1308
1309 QString groupValue;
1310 QChar firstChar;
1311 bool isLetter = false;
1312 for (int i = 0; i <= maxIndex; ++i) {
1313 if (isChildItem(i)) {
1314 continue;
1315 }
1316
1317 const QString name = m_itemData.at(i)->values.value("name").toString();
1318
1319 // Use the first character of the name as group indication
1320 QChar newFirstChar = name.at(0).toUpper();
1321 if (newFirstChar == QLatin1Char('~') && name.length() > 1) {
1322 newFirstChar = name.at(1);
1323 }
1324
1325 if (firstChar != newFirstChar) {
1326 QString newGroupValue;
1327 if (newFirstChar >= QLatin1Char('A') && newFirstChar <= QLatin1Char('Z')) {
1328 // Apply group 'A' - 'Z'
1329 newGroupValue = newFirstChar;
1330 isLetter = true;
1331 } else if (newFirstChar >= QLatin1Char('0') && newFirstChar <= QLatin1Char('9')) {
1332 // Apply group '0 - 9' for any name that starts with a digit
1333 newGroupValue = i18nc("@title:group Groups that start with a digit", "0 - 9");
1334 isLetter = false;
1335 } else {
1336 if (isLetter) {
1337 // If the current group is 'A' - 'Z' check whether a locale character
1338 // fits into the existing group.
1339 // TODO: This does not work in the case if e.g. the group 'O' starts with
1340 // an umlaut 'O' -> provide unit-test to document this known issue
1341 const QChar prevChar(firstChar.unicode() - ushort(1));
1342 const QChar nextChar(firstChar.unicode() + ushort(1));
1343 const QString currChar(newFirstChar);
1344 const bool partOfCurrentGroup = currChar.localeAwareCompare(prevChar) > 0 &&
1345 currChar.localeAwareCompare(nextChar) < 0;
1346 if (partOfCurrentGroup) {
1347 continue;
1348 }
1349 }
1350 newGroupValue = i18nc("@title:group", "Others");
1351 isLetter = false;
1352 }
1353
1354 if (newGroupValue != groupValue) {
1355 groupValue = newGroupValue;
1356 groups.append(QPair<int, QVariant>(i, newGroupValue));
1357 }
1358
1359 firstChar = newFirstChar;
1360 }
1361 }
1362 return groups;
1363 }
1364
1365 QList<QPair<int, QVariant> > KFileItemModel::sizeRoleGroups() const
1366 {
1367 Q_ASSERT(!m_itemData.isEmpty());
1368
1369 const int maxIndex = count() - 1;
1370 QList<QPair<int, QVariant> > groups;
1371
1372 QString groupValue;
1373 for (int i = 0; i <= maxIndex; ++i) {
1374 if (isChildItem(i)) {
1375 continue;
1376 }
1377
1378 const KFileItem& item = m_itemData.at(i)->item;
1379 const KIO::filesize_t fileSize = !item.isNull() ? item.size() : ~0U;
1380 QString newGroupValue;
1381 if (!item.isNull() && item.isDir()) {
1382 newGroupValue = i18nc("@title:group Size", "Folders");
1383 } else if (fileSize < 5 * 1024 * 1024) {
1384 newGroupValue = i18nc("@title:group Size", "Small");
1385 } else if (fileSize < 10 * 1024 * 1024) {
1386 newGroupValue = i18nc("@title:group Size", "Medium");
1387 } else {
1388 newGroupValue = i18nc("@title:group Size", "Big");
1389 }
1390
1391 if (newGroupValue != groupValue) {
1392 groupValue = newGroupValue;
1393 groups.append(QPair<int, QVariant>(i, newGroupValue));
1394 }
1395 }
1396
1397 return groups;
1398 }
1399
1400 QList<QPair<int, QVariant> > KFileItemModel::dateRoleGroups() const
1401 {
1402 Q_ASSERT(!m_itemData.isEmpty());
1403
1404 const int maxIndex = count() - 1;
1405 QList<QPair<int, QVariant> > groups;
1406
1407 const QDate currentDate = KDateTime::currentLocalDateTime().date();
1408
1409 int yearForCurrentWeek = 0;
1410 int currentWeek = currentDate.weekNumber(&yearForCurrentWeek);
1411 if (yearForCurrentWeek == currentDate.year() + 1) {
1412 currentWeek = 53;
1413 }
1414
1415 QDate previousModifiedDate;
1416 QString groupValue;
1417 for (int i = 0; i <= maxIndex; ++i) {
1418 if (isChildItem(i)) {
1419 continue;
1420 }
1421
1422 const KDateTime modifiedTime = m_itemData.at(i)->item.time(KFileItem::ModificationTime);
1423 const QDate modifiedDate = modifiedTime.date();
1424 if (modifiedDate == previousModifiedDate) {
1425 // The current item is in the same group as the previous item
1426 continue;
1427 }
1428 previousModifiedDate = modifiedDate;
1429
1430 const int daysDistance = modifiedDate.daysTo(currentDate);
1431
1432 int yearForModifiedWeek = 0;
1433 int modifiedWeek = modifiedDate.weekNumber(&yearForModifiedWeek);
1434 if (yearForModifiedWeek == modifiedDate.year() + 1) {
1435 modifiedWeek = 53;
1436 }
1437
1438 QString newGroupValue;
1439 if (currentDate.year() == modifiedDate.year() && currentDate.month() == modifiedDate.month()) {
1440 if (modifiedWeek > currentWeek) {
1441 // Usecase: modified date = 2010-01-01, current date = 2010-01-22
1442 // modified week = 53, current week = 3
1443 modifiedWeek = 0;
1444 }
1445 switch (currentWeek - modifiedWeek) {
1446 case 0:
1447 switch (daysDistance) {
1448 case 0: newGroupValue = i18nc("@title:group Date", "Today"); break;
1449 case 1: newGroupValue = i18nc("@title:group Date", "Yesterday"); break;
1450 default: newGroupValue = modifiedTime.toString(i18nc("@title:group The week day name: %A", "%A"));
1451 }
1452 break;
1453 case 1:
1454 newGroupValue = i18nc("@title:group Date", "Last Week");
1455 break;
1456 case 2:
1457 newGroupValue = i18nc("@title:group Date", "Two Weeks Ago");
1458 break;
1459 case 3:
1460 newGroupValue = i18nc("@title:group Date", "Three Weeks Ago");
1461 break;
1462 case 4:
1463 case 5:
1464 newGroupValue = i18nc("@title:group Date", "Earlier this Month");
1465 break;
1466 default:
1467 Q_ASSERT(false);
1468 }
1469 } else {
1470 const QDate lastMonthDate = currentDate.addMonths(-1);
1471 if (lastMonthDate.year() == modifiedDate.year() && lastMonthDate.month() == modifiedDate.month()) {
1472 if (daysDistance == 1) {
1473 newGroupValue = modifiedTime.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Yesterday (%B, %Y)"));
1474 } else if (daysDistance <= 7) {
1475 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)"));
1476 } else if (daysDistance <= 7 * 2) {
1477 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)"));
1478 } else if (daysDistance <= 7 * 3) {
1479 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)"));
1480 } else if (daysDistance <= 7 * 4) {
1481 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)"));
1482 } else {
1483 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"));
1484 }
1485 } else {
1486 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"));
1487 }
1488 }
1489
1490 if (newGroupValue != groupValue) {
1491 groupValue = newGroupValue;
1492 groups.append(QPair<int, QVariant>(i, newGroupValue));
1493 }
1494 }
1495
1496 return groups;
1497 }
1498
1499 QList<QPair<int, QVariant> > KFileItemModel::permissionRoleGroups() const
1500 {
1501 Q_ASSERT(!m_itemData.isEmpty());
1502
1503 const int maxIndex = count() - 1;
1504 QList<QPair<int, QVariant> > groups;
1505
1506 QString permissionsString;
1507 QString groupValue;
1508 for (int i = 0; i <= maxIndex; ++i) {
1509 if (isChildItem(i)) {
1510 continue;
1511 }
1512
1513 const ItemData* itemData = m_itemData.at(i);
1514 const QString newPermissionsString = itemData->values.value("permissions").toString();
1515 if (newPermissionsString == permissionsString) {
1516 continue;
1517 }
1518 permissionsString = newPermissionsString;
1519
1520 const QFileInfo info(itemData->item.url().pathOrUrl());
1521
1522 // Set user string
1523 QString user;
1524 if (info.permission(QFile::ReadUser)) {
1525 user = i18nc("@item:intext Access permission, concatenated", "Read, ");
1526 }
1527 if (info.permission(QFile::WriteUser)) {
1528 user += i18nc("@item:intext Access permission, concatenated", "Write, ");
1529 }
1530 if (info.permission(QFile::ExeUser)) {
1531 user += i18nc("@item:intext Access permission, concatenated", "Execute, ");
1532 }
1533 user = user.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user.mid(0, user.count() - 2);
1534
1535 // Set group string
1536 QString group;
1537 if (info.permission(QFile::ReadGroup)) {
1538 group = i18nc("@item:intext Access permission, concatenated", "Read, ");
1539 }
1540 if (info.permission(QFile::WriteGroup)) {
1541 group += i18nc("@item:intext Access permission, concatenated", "Write, ");
1542 }
1543 if (info.permission(QFile::ExeGroup)) {
1544 group += i18nc("@item:intext Access permission, concatenated", "Execute, ");
1545 }
1546 group = group.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group.mid(0, group.count() - 2);
1547
1548 // Set others string
1549 QString others;
1550 if (info.permission(QFile::ReadOther)) {
1551 others = i18nc("@item:intext Access permission, concatenated", "Read, ");
1552 }
1553 if (info.permission(QFile::WriteOther)) {
1554 others += i18nc("@item:intext Access permission, concatenated", "Write, ");
1555 }
1556 if (info.permission(QFile::ExeOther)) {
1557 others += i18nc("@item:intext Access permission, concatenated", "Execute, ");
1558 }
1559 others = others.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others.mid(0, others.count() - 2);
1560
1561 const QString newGroupValue = i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user, group, others);
1562 if (newGroupValue != groupValue) {
1563 groupValue = newGroupValue;
1564 groups.append(QPair<int, QVariant>(i, newGroupValue));
1565 }
1566 }
1567
1568 return groups;
1569 }
1570
1571 QList<QPair<int, QVariant> > KFileItemModel::ratingRoleGroups() const
1572 {
1573 Q_ASSERT(!m_itemData.isEmpty());
1574
1575 const int maxIndex = count() - 1;
1576 QList<QPair<int, QVariant> > groups;
1577
1578 int groupValue;
1579 for (int i = 0; i <= maxIndex; ++i) {
1580 if (isChildItem(i)) {
1581 continue;
1582 }
1583 const int newGroupValue = m_itemData.at(i)->values.value("rating").toInt();
1584 if (newGroupValue != groupValue) {
1585 groupValue = newGroupValue;
1586 groups.append(QPair<int, QVariant>(i, newGroupValue));
1587 }
1588 }
1589
1590 return groups;
1591 }
1592
1593 QList<QPair<int, QVariant> > KFileItemModel::genericStringRoleGroups(const QByteArray& role) const
1594 {
1595 Q_ASSERT(!m_itemData.isEmpty());
1596
1597 const int maxIndex = count() - 1;
1598 QList<QPair<int, QVariant> > groups;
1599
1600 QString groupValue;
1601 for (int i = 0; i <= maxIndex; ++i) {
1602 if (isChildItem(i)) {
1603 continue;
1604 }
1605 const QString newGroupValue = m_itemData.at(i)->values.value(role).toString();
1606 if (newGroupValue != groupValue) {
1607 groupValue = newGroupValue;
1608 groups.append(QPair<int, QVariant>(i, newGroupValue));
1609 }
1610 }
1611
1612 return groups;
1613 }
1614
1615 #include "kfileitemmodel.moc"