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