1 /***************************************************************************
2 * Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
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. *
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. *
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 ***************************************************************************/
20 #include "kfileitemmodel.h"
25 #include <KStringHandler>
31 #define KFILEITEMMODEL_DEBUG
33 KFileItemModel::KFileItemModel(KDirLister
* dirLister
, QObject
* parent
) :
34 KItemModelBase("name", parent
),
35 m_dirLister(dirLister
),
36 m_naturalSorting(true),
37 m_sortFoldersFirst(true),
39 m_caseSensitivity(Qt::CaseInsensitive
),
44 m_minimumUpdateIntervalTimer(0),
45 m_maximumUpdateIntervalTimer(0),
46 m_pendingItemsToInsert(),
47 m_pendingEmitLoadingCompleted(false),
48 m_rootExpansionLevel(-1),
50 m_restoredExpandedUrls()
53 m_requestRole
[NameRole
] = true;
54 m_requestRole
[IsDirRole
] = true;
58 connect(dirLister
, SIGNAL(canceled()), this, SLOT(slotCanceled()));
59 connect(dirLister
, SIGNAL(completed()), this, SLOT(slotCompleted()));
60 connect(dirLister
, SIGNAL(newItems(KFileItemList
)), this, SLOT(slotNewItems(KFileItemList
)));
61 connect(dirLister
, SIGNAL(itemsDeleted(KFileItemList
)), this, SLOT(slotItemsDeleted(KFileItemList
)));
62 connect(dirLister
, SIGNAL(refreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)), this, SLOT(slotRefreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)));
63 connect(dirLister
, SIGNAL(clear()), this, SLOT(slotClear()));
64 connect(dirLister
, SIGNAL(clear(KUrl
)), this, SLOT(slotClear(KUrl
)));
66 // Although the layout engine of KItemListView is fast it is very inefficient to e.g.
67 // emit 50 itemsInserted()-signals each 100 ms. m_minimumUpdateIntervalTimer assures that updates
68 // are done in 1 second intervals for equal operations.
69 m_minimumUpdateIntervalTimer
= new QTimer(this);
70 m_minimumUpdateIntervalTimer
->setInterval(1000);
71 m_minimumUpdateIntervalTimer
->setSingleShot(true);
72 connect(m_minimumUpdateIntervalTimer
, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
74 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
75 // before the completed() or canceled() signal has been emitted.
76 m_maximumUpdateIntervalTimer
= new QTimer(this);
77 m_maximumUpdateIntervalTimer
->setInterval(2000);
78 m_maximumUpdateIntervalTimer
->setSingleShot(true);
79 connect(m_maximumUpdateIntervalTimer
, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
81 Q_ASSERT(m_minimumUpdateIntervalTimer
->interval() <= m_maximumUpdateIntervalTimer
->interval());
84 KFileItemModel::~KFileItemModel()
88 int KFileItemModel::count() const
90 return m_data
.count();
93 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
95 if (index
>= 0 && index
< count()) {
96 return m_data
.at(index
);
98 return QHash
<QByteArray
, QVariant
>();
101 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
103 if (index
>= 0 && index
< count()) {
104 QHash
<QByteArray
, QVariant
> currentValue
= m_data
.at(index
);
106 QSet
<QByteArray
> changedRoles
;
107 QHashIterator
<QByteArray
, QVariant
> it(values
);
108 while (it
.hasNext()) {
110 const QByteArray role
= it
.key();
111 const QVariant value
= it
.value();
113 if (currentValue
[role
] != value
) {
114 currentValue
[role
] = value
;
115 changedRoles
.insert(role
);
119 if (!changedRoles
.isEmpty()) {
120 m_data
[index
] = currentValue
;
121 emit
itemsChanged(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
129 void KFileItemModel::setSortFoldersFirst(bool foldersFirst
)
131 if (foldersFirst
!= m_sortFoldersFirst
) {
132 m_sortFoldersFirst
= foldersFirst
;
137 bool KFileItemModel::sortFoldersFirst() const
139 return m_sortFoldersFirst
;
142 QMimeData
* KFileItemModel::createMimeData(const QSet
<int>& indexes
) const
144 QMimeData
* data
= new QMimeData();
146 // The following code has been taken from KDirModel::mimeData()
147 // (kdelibs/kio/kio/kdirmodel.cpp)
148 // Copyright (C) 2006 David Faure <faure@kde.org>
150 KUrl::List mostLocalUrls
;
151 bool canUseMostLocalUrls
= true;
153 QSetIterator
<int> it(indexes
);
154 while (it
.hasNext()) {
155 const int index
= it
.next();
156 const KFileItem item
= fileItem(index
);
157 if (!item
.isNull()) {
161 mostLocalUrls
<< item
.mostLocalUrl(isLocal
);
163 canUseMostLocalUrls
= false;
168 const bool different
= canUseMostLocalUrls
&& mostLocalUrls
!= urls
;
169 urls
= KDirModel::simplifiedUrlList(urls
); // TODO: Check if we still need KDirModel for this in KDE 5.0
171 mostLocalUrls
= KDirModel::simplifiedUrlList(mostLocalUrls
);
172 urls
.populateMimeData(mostLocalUrls
, data
);
174 urls
.populateMimeData(data
);
180 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
182 startFromIndex
= qMax(0, startFromIndex
);
183 for (int i
= startFromIndex
; i
< count(); ++i
) {
184 if (data(i
)["name"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
188 for (int i
= 0; i
< startFromIndex
; ++i
) {
189 if (data(i
)["name"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
196 bool KFileItemModel::supportsDropping(int index
) const
198 const KFileItem item
= fileItem(index
);
199 return item
.isNull() ? false : item
.isDir();
202 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
206 switch (roleIndex(role
)) {
207 case NameRole
: descr
= i18nc("@item:intable", "Name"); break;
208 case SizeRole
: descr
= i18nc("@item:intable", "Size"); break;
209 case DateRole
: descr
= i18nc("@item:intable", "Date"); break;
210 case PermissionsRole
: descr
= i18nc("@item:intable", "Permissions"); break;
211 case OwnerRole
: descr
= i18nc("@item:intable", "Owner"); break;
212 case GroupRole
: descr
= i18nc("@item:intable", "Group"); break;
213 case TypeRole
: descr
= i18nc("@item:intable", "Type"); break;
214 case DestinationRole
: descr
= i18nc("@item:intable", "Destination"); break;
215 case PathRole
: descr
= i18nc("@item:intable", "Path"); break;
217 case IsDirRole
: break;
218 case IsExpandedRole
: break;
219 case ExpansionLevelRole
: break;
220 default: Q_ASSERT(false); break;
226 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
228 // TODO: dirty hack for initial testing of grouping functionality
229 QPair
<int, QVariant
> group1(0, "Group 1");
230 QPair
<int, QVariant
> group2(2, "Group 2");
231 QPair
<int, QVariant
> group3(10, "Group 3");
232 QPair
<int, QVariant
> group4(11, "Group 4");
233 QPair
<int, QVariant
> group5(40, "Group 5");
235 QList
<QPair
<int, QVariant
> > groups
;
236 groups
.append(group1
);
237 groups
.append(group2
);
238 groups
.append(group3
);
239 groups
.append(group4
);
240 groups
.append(group5
);
244 KFileItem
KFileItemModel::fileItem(int index
) const
246 if (index
>= 0 && index
< count()) {
247 return m_sortedItems
.at(index
);
253 KFileItem
KFileItemModel::fileItem(const KUrl
& url
) const
255 const int index
= m_items
.value(url
, -1);
257 return m_sortedItems
.at(index
);
262 int KFileItemModel::index(const KFileItem
& item
) const
268 return m_items
.value(item
.url(), -1);
271 int KFileItemModel::index(const KUrl
& url
) const
273 KUrl urlToFind
= url
;
274 urlToFind
.adjustPath(KUrl::RemoveTrailingSlash
);
275 return m_items
.value(urlToFind
, -1);
278 KFileItem
KFileItemModel::rootItem() const
280 const KDirLister
* dirLister
= m_dirLister
.data();
282 return dirLister
->rootItem();
287 void KFileItemModel::clear()
292 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
295 const bool supportedExpanding
= m_requestRole
[IsExpandedRole
] && m_requestRole
[ExpansionLevelRole
];
296 const bool willSupportExpanding
= roles
.contains("isExpanded") && roles
.contains("expansionLevel");
297 if (supportedExpanding
&& !willSupportExpanding
) {
298 // No expanding is supported anymore. Take care to delete all items that have an expansion level
299 // that is not 0 (and hence are part of an expanded item).
300 removeExpandedItems();
305 QSetIterator
<QByteArray
> it(roles
);
306 while (it
.hasNext()) {
307 const QByteArray
& role
= it
.next();
308 m_requestRole
[roleIndex(role
)] = true;
312 // Update m_data with the changed requested roles
313 const int maxIndex
= count() - 1;
314 for (int i
= 0; i
<= maxIndex
; ++i
) {
315 m_data
[i
] = retrieveData(m_sortedItems
.at(i
));
318 kWarning() << "TODO: Emitting itemsChanged() with no information what has changed!";
319 emit
itemsChanged(KItemRangeList() << KItemRange(0, count()), QSet
<QByteArray
>());
323 QSet
<QByteArray
> KFileItemModel::roles() const
325 QSet
<QByteArray
> roles
;
326 for (int i
= 0; i
< RolesCount
; ++i
) {
327 if (m_requestRole
[i
]) {
330 case NameRole
: roles
.insert("name"); break;
331 case SizeRole
: roles
.insert("size"); break;
332 case DateRole
: roles
.insert("date"); break;
333 case PermissionsRole
: roles
.insert("permissions"); break;
334 case OwnerRole
: roles
.insert("owner"); break;
335 case GroupRole
: roles
.insert("group"); break;
336 case TypeRole
: roles
.insert("type"); break;
337 case DestinationRole
: roles
.insert("destination"); break;
338 case PathRole
: roles
.insert("path"); break;
339 case IsDirRole
: roles
.insert("isDir"); break;
340 case IsExpandedRole
: roles
.insert("isExpanded"); break;
341 case ExpansionLevelRole
: roles
.insert("expansionLevel"); break;
342 default: Q_ASSERT(false); break;
349 bool KFileItemModel::setExpanded(int index
, bool expanded
)
351 if (isExpanded(index
) == expanded
|| index
< 0 || index
>= count()) {
355 QHash
<QByteArray
, QVariant
> values
;
356 values
.insert("isExpanded", expanded
);
357 if (!setData(index
, values
)) {
361 const KUrl url
= m_sortedItems
.at(index
).url();
363 m_expandedUrls
.insert(url
);
365 KDirLister
* dirLister
= m_dirLister
.data();
367 dirLister
->openUrl(url
, KDirLister::Keep
);
371 m_expandedUrls
.remove(url
);
373 KFileItemList itemsToRemove
;
374 const int expansionLevel
= data(index
)["expansionLevel"].toInt();
376 while (index
< count() && data(index
)["expansionLevel"].toInt() > expansionLevel
) {
377 itemsToRemove
.append(m_sortedItems
.at(index
));
380 removeItems(itemsToRemove
);
387 bool KFileItemModel::isExpanded(int index
) const
389 if (index
>= 0 && index
< count()) {
390 return m_data
.at(index
).value("isExpanded").toBool();
395 bool KFileItemModel::isExpandable(int index
) const
397 if (index
>= 0 && index
< count()) {
398 return m_sortedItems
.at(index
).isDir();
403 QSet
<KUrl
> KFileItemModel::expandedUrls() const
405 return m_expandedUrls
;
408 void KFileItemModel::restoreExpandedUrls(const QSet
<KUrl
>& urls
)
410 m_restoredExpandedUrls
= urls
;
413 void KFileItemModel::onGroupedSortingChanged(bool current
)
418 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
421 m_sortRole
= roleIndex(current
);
425 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
432 void KFileItemModel::slotCompleted()
434 if (m_restoredExpandedUrls
.isEmpty() && m_minimumUpdateIntervalTimer
->isActive()) {
435 // dispatchPendingItems() will be called when the timer
437 m_pendingEmitLoadingCompleted
= true;
441 m_pendingEmitLoadingCompleted
= false;
442 dispatchPendingItemsToInsert();
444 if (!m_restoredExpandedUrls
.isEmpty()) {
445 // Try to find a URL that can be expanded.
446 // Note that the parent folder must be expanded before any of its subfolders become visible.
447 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
448 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
449 foreach(const KUrl
& url
, m_restoredExpandedUrls
) {
450 const int index
= m_items
.value(url
, -1);
452 // We have found an expandable URL. Expand it and return - when
453 // the dir lister has finished, this slot will be called again.
454 m_restoredExpandedUrls
.remove(url
);
455 setExpanded(index
, true);
460 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
461 // if these URLs have been deleted in the meantime.
462 m_restoredExpandedUrls
.clear();
465 emit
loadingCompleted();
466 m_minimumUpdateIntervalTimer
->start();
469 void KFileItemModel::slotCanceled()
471 m_minimumUpdateIntervalTimer
->stop();
472 m_maximumUpdateIntervalTimer
->stop();
473 dispatchPendingItemsToInsert();
476 void KFileItemModel::slotNewItems(const KFileItemList
& items
)
478 m_pendingItemsToInsert
.append(items
);
480 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer
->isActive()) {
481 // Assure that items get dispatched if no completed() or canceled() signal is
482 // emitted during the maximum update interval.
483 m_maximumUpdateIntervalTimer
->start();
487 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
489 if (!m_pendingItemsToInsert
.isEmpty()) {
490 insertItems(m_pendingItemsToInsert
);
491 m_pendingItemsToInsert
.clear();
496 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
498 Q_ASSERT(!items
.isEmpty());
499 #ifdef KFILEITEMMODEL_DEBUG
500 kDebug() << "Refreshing" << items
.count() << "items";
503 // Get the indexes of all items that have been refreshed
505 indexes
.reserve(items
.count());
507 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
508 while (it
.hasNext()) {
509 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
510 const int index
= m_items
.value(itemPair
.second
.url(), -1);
512 indexes
.append(index
);
516 // If the changed items have been created recently, they might not be in m_items yet.
517 // In that case, the list 'indexes' might be empty.
518 if (indexes
.isEmpty()) {
522 // Extract the item-ranges out of the changed indexes
525 KItemRangeList itemRangeList
;
528 int previousIndex
= indexes
.at(0);
530 const int maxIndex
= indexes
.count() - 1;
531 for (int i
= 1; i
<= maxIndex
; ++i
) {
532 const int currentIndex
= indexes
.at(i
);
533 if (currentIndex
== previousIndex
+ 1) {
536 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
538 rangeIndex
= currentIndex
;
541 previousIndex
= currentIndex
;
544 if (rangeCount
> 0) {
545 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
548 emit
itemsChanged(itemRangeList
, QSet
<QByteArray
>());
551 void KFileItemModel::slotClear()
553 #ifdef KFILEITEMMODEL_DEBUG
554 kDebug() << "Clearing all items";
557 m_minimumUpdateIntervalTimer
->stop();
558 m_maximumUpdateIntervalTimer
->stop();
559 m_pendingItemsToInsert
.clear();
561 m_rootExpansionLevel
= -1;
563 const int removedCount
= m_data
.count();
564 if (removedCount
> 0) {
565 m_sortedItems
.clear();
568 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
571 m_expandedUrls
.clear();
574 void KFileItemModel::slotClear(const KUrl
& url
)
579 void KFileItemModel::dispatchPendingItemsToInsert()
581 if (!m_pendingItemsToInsert
.isEmpty()) {
582 insertItems(m_pendingItemsToInsert
);
583 m_pendingItemsToInsert
.clear();
586 if (m_pendingEmitLoadingCompleted
) {
587 emit
loadingCompleted();
591 void KFileItemModel::insertItems(const KFileItemList
& items
)
593 if (items
.isEmpty()) {
597 #ifdef KFILEITEMMODEL_DEBUG
600 kDebug() << "===========================================================";
601 kDebug() << "Inserting" << items
.count() << "items";
604 KFileItemList sortedItems
= items
;
605 sort(sortedItems
.begin(), sortedItems
.end());
607 #ifdef KFILEITEMMODEL_DEBUG
608 kDebug() << "[TIME] Sorting:" << timer
.elapsed();
611 KItemRangeList itemRanges
;
614 int insertedAtIndex
= -1; // Index for the current item-range
615 int insertedCount
= 0; // Count for the current item-range
616 int previouslyInsertedCount
= 0; // Sum of previously inserted items for all ranges
617 while (sourceIndex
< sortedItems
.count()) {
618 // Find target index from m_items to insert the current item
620 const int previousTargetIndex
= targetIndex
;
621 while (targetIndex
< m_sortedItems
.count()) {
622 if (!lessThan(m_sortedItems
.at(targetIndex
), sortedItems
.at(sourceIndex
))) {
628 if (targetIndex
- previousTargetIndex
> 0 && insertedAtIndex
>= 0) {
629 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
630 previouslyInsertedCount
+= insertedCount
;
631 insertedAtIndex
= targetIndex
- previouslyInsertedCount
;
635 // Insert item at the position targetIndex
636 const KFileItem item
= sortedItems
.at(sourceIndex
);
637 m_sortedItems
.insert(targetIndex
, item
);
638 m_data
.insert(targetIndex
, retrieveData(item
));
639 // m_items will be inserted after the loop (see comment below)
642 if (insertedAtIndex
< 0) {
643 insertedAtIndex
= targetIndex
;
644 Q_ASSERT(previouslyInsertedCount
== 0);
650 // The indexes of all m_items must be adjusted, not only the index
652 for (int i
= 0; i
< m_sortedItems
.count(); ++i
) {
653 m_items
.insert(m_sortedItems
.at(i
).url(), i
);
656 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
657 emit
itemsInserted(itemRanges
);
659 #ifdef KFILEITEMMODEL_DEBUG
660 kDebug() << "[TIME] Inserting of" << items
.count() << "items:" << timer
.elapsed();
664 void KFileItemModel::removeItems(const KFileItemList
& items
)
666 if (items
.isEmpty()) {
670 #ifdef KFILEITEMMODEL_DEBUG
671 kDebug() << "Removing " << items
.count() << "items";
674 KFileItemList sortedItems
= items
;
675 sort(sortedItems
.begin(), sortedItems
.end());
677 QList
<int> indexesToRemove
;
678 indexesToRemove
.reserve(items
.count());
680 // Calculate the item ranges that will get deleted
681 KItemRangeList itemRanges
;
682 int removedAtIndex
= -1;
683 int removedCount
= 0;
685 foreach (const KFileItem
& itemToRemove
, sortedItems
) {
686 const int previousTargetIndex
= targetIndex
;
687 while (targetIndex
< m_sortedItems
.count()) {
688 if (m_sortedItems
.at(targetIndex
).url() == itemToRemove
.url()) {
693 if (targetIndex
>= m_sortedItems
.count()) {
694 kWarning() << "Item that should be deleted has not been found!";
698 if (targetIndex
- previousTargetIndex
> 0 && removedAtIndex
>= 0) {
699 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
700 removedAtIndex
= targetIndex
;
704 indexesToRemove
.append(targetIndex
);
705 if (removedAtIndex
< 0) {
706 removedAtIndex
= targetIndex
;
713 for (int i
= indexesToRemove
.count() - 1; i
>= 0; --i
) {
714 const int indexToRemove
= indexesToRemove
.at(i
);
715 m_items
.remove(m_sortedItems
.at(indexToRemove
).url());
716 m_sortedItems
.removeAt(indexToRemove
);
717 m_data
.removeAt(indexToRemove
);
720 // The indexes of all m_items must be adjusted, not only the index
721 // of the removed items
722 for (int i
= 0; i
< m_sortedItems
.count(); ++i
) {
723 m_items
.insert(m_sortedItems
.at(i
).url(), i
);
727 m_rootExpansionLevel
= -1;
730 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
731 emit
itemsRemoved(itemRanges
);
734 void KFileItemModel::resortAllItems()
736 const int itemCount
= count();
737 if (itemCount
<= 0) {
741 const KFileItemList oldSortedItems
= m_sortedItems
;
742 const QHash
<KUrl
, int> oldItems
= m_items
;
743 const QList
<QHash
<QByteArray
, QVariant
> > oldData
= m_data
;
748 sort(m_sortedItems
.begin(), m_sortedItems
.end());
750 foreach (const KFileItem
& item
, m_sortedItems
) {
751 m_items
.insert(item
.url(), index
);
753 const int oldItemIndex
= oldItems
.value(item
.url());
754 m_data
.append(oldData
.at(oldItemIndex
));
759 bool emitItemsMoved
= false;
760 QList
<int> movedToIndexes
;
761 movedToIndexes
.reserve(m_sortedItems
.count());
762 for (int i
= 0; i
< itemCount
; i
++) {
763 const int newIndex
= m_items
.value(oldSortedItems
.at(i
).url());
764 movedToIndexes
.append(newIndex
);
765 if (!emitItemsMoved
&& newIndex
!= i
) {
766 emitItemsMoved
= true;
770 if (emitItemsMoved
) {
771 emit
itemsMoved(KItemRange(0, itemCount
), movedToIndexes
);
775 void KFileItemModel::removeExpandedItems()
777 KFileItemList expandedItems
;
779 const int maxIndex
= m_data
.count() - 1;
780 for (int i
= 0; i
<= maxIndex
; ++i
) {
781 if (m_data
.at(i
).value("expansionLevel").toInt() > 0) {
782 const KFileItem fileItem
= m_sortedItems
.at(i
);
783 expandedItems
.append(fileItem
);
787 // The m_rootExpansionLevel may not get reset before all items with
788 // a bigger expansionLevel have been removed.
789 Q_ASSERT(m_rootExpansionLevel
>= 0);
790 removeItems(expandedItems
);
792 m_rootExpansionLevel
= -1;
793 m_expandedUrls
.clear();
796 void KFileItemModel::resetRoles()
798 for (int i
= 0; i
< RolesCount
; ++i
) {
799 m_requestRole
[i
] = false;
803 KFileItemModel::Role
KFileItemModel::roleIndex(const QByteArray
& role
) const
805 static QHash
<QByteArray
, Role
> rolesHash
;
806 if (rolesHash
.isEmpty()) {
807 rolesHash
.insert("name", NameRole
);
808 rolesHash
.insert("size", SizeRole
);
809 rolesHash
.insert("date", DateRole
);
810 rolesHash
.insert("permissions", PermissionsRole
);
811 rolesHash
.insert("owner", OwnerRole
);
812 rolesHash
.insert("group", GroupRole
);
813 rolesHash
.insert("type", TypeRole
);
814 rolesHash
.insert("destination", DestinationRole
);
815 rolesHash
.insert("path", PathRole
);
816 rolesHash
.insert("isDir", IsDirRole
);
817 rolesHash
.insert("isExpanded", IsExpandedRole
);
818 rolesHash
.insert("expansionLevel", ExpansionLevelRole
);
820 return rolesHash
.value(role
, NoRole
);
823 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
) const
825 // It is important to insert only roles that are fast to retrieve. E.g.
826 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
827 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
828 QHash
<QByteArray
, QVariant
> data
;
829 data
.insert("iconPixmap", QPixmap());
831 const bool isDir
= item
.isDir();
832 if (m_requestRole
[IsDirRole
]) {
833 data
.insert("isDir", isDir
);
836 if (m_requestRole
[NameRole
]) {
837 data
.insert("name", item
.name());
840 if (m_requestRole
[SizeRole
]) {
842 data
.insert("size", QVariant());
844 data
.insert("size", item
.size());
848 if (m_requestRole
[DateRole
]) {
849 // Don't use KFileItem::timeString() as this is too expensive when
850 // having several thousands of items. Instead the formatting of the
851 // date-time will be done on-demand by the view when the date will be shown.
852 const KDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
853 data
.insert("date", dateTime
.dateTime());
856 if (m_requestRole
[PermissionsRole
]) {
857 data
.insert("permissions", item
.permissionsString());
860 if (m_requestRole
[OwnerRole
]) {
861 data
.insert("owner", item
.user());
864 if (m_requestRole
[GroupRole
]) {
865 data
.insert("group", item
.group());
868 if (m_requestRole
[DestinationRole
]) {
869 QString destination
= item
.linkDest();
870 if (destination
.isEmpty()) {
871 destination
= i18nc("@item:intable", "No destination");
873 data
.insert("destination", destination
);
876 if (m_requestRole
[PathRole
]) {
877 data
.insert("path", item
.localPath());
880 if (m_requestRole
[IsExpandedRole
]) {
881 data
.insert("isExpanded", false);
884 if (m_requestRole
[ExpansionLevelRole
]) {
885 if (m_rootExpansionLevel
< 0) {
886 KDirLister
* dirLister
= m_dirLister
.data();
888 const QString rootDir
= dirLister
->url().directory(KUrl::AppendTrailingSlash
);
889 m_rootExpansionLevel
= rootDir
.count('/');
892 const QString dir
= item
.url().directory(KUrl::AppendTrailingSlash
);
893 const int level
= dir
.count('/') - m_rootExpansionLevel
- 1;
894 data
.insert("expansionLevel", level
);
897 if (item
.isMimeTypeKnown()) {
898 data
.insert("iconName", item
.iconName());
900 if (m_requestRole
[TypeRole
]) {
901 data
.insert("type", item
.mimeComment());
908 bool KFileItemModel::lessThan(const KFileItem
& a
, const KFileItem
& b
) const
912 if (m_rootExpansionLevel
>= 0) {
913 result
= expansionLevelsCompare(a
, b
);
915 // The items have parents with different expansion levels
916 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
920 if (m_sortFoldersFirst
|| m_sortRole
== SizeRole
) {
921 const bool isDirA
= a
.isDir();
922 const bool isDirB
= b
.isDir();
923 if (isDirA
&& !isDirB
) {
925 } else if (!isDirA
&& isDirB
) {
930 switch (m_sortRole
) {
932 result
= stringCompare(a
.text(), b
.text());
934 // KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
935 result
= stringCompare(a
.name(m_caseSensitivity
== Qt::CaseInsensitive
),
936 b
.name(m_caseSensitivity
== Qt::CaseInsensitive
));
942 const KDateTime dateTimeA
= a
.time(KFileItem::ModificationTime
);
943 const KDateTime dateTimeB
= b
.time(KFileItem::ModificationTime
);
944 if (dateTimeA
< dateTimeB
) {
946 } else if (dateTimeA
> dateTimeB
) {
953 // TODO: Implement sorting folders by the number of items inside.
954 // This is more tricky to get right because this number is retrieved
955 // asynchronously by KFileItemModelRolesUpdater.
956 const KIO::filesize_t sizeA
= a
.size();
957 const KIO::filesize_t sizeB
= b
.size();
960 } else if (sizeA
> sizeB
) {
971 // It must be assured that the sort order is always unique even if two values have been
972 // equal. In this case a comparison of the URL is done which is unique in all cases
973 // within KDirLister.
974 result
= QString::compare(a
.url().url(), b
.url().url(), Qt::CaseSensitive
);
977 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
980 void KFileItemModel::sort(const KFileItemList::iterator
& startIterator
, const KFileItemList::iterator
& endIterator
)
982 KFileItemList::iterator start
= startIterator
;
983 KFileItemList::iterator end
= endIterator
;
985 // The implementation is based on qSortHelper() from qalgorithms.h
986 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
987 // In opposite to qSort() it allows to use a member-function for the comparison of elements.
989 int span
= int(end
- start
);
995 KFileItemList::iterator low
= start
, high
= end
- 1;
996 KFileItemList::iterator pivot
= start
+ span
/ 2;
998 if (lessThan(*end
, *start
)) {
1005 if (lessThan(*pivot
, *start
)) {
1006 qSwap(*pivot
, *start
);
1008 if (lessThan(*end
, *pivot
)) {
1009 qSwap(*end
, *pivot
);
1015 qSwap(*pivot
, *end
);
1017 while (low
< high
) {
1018 while (low
< high
&& lessThan(*low
, *end
)) {
1022 while (high
> low
&& lessThan(*end
, *high
)) {
1034 if (lessThan(*low
, *end
)) {
1046 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
) const
1048 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1049 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1050 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1051 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1053 if (m_caseSensitivity
== Qt::CaseInsensitive
) {
1054 const int result
= m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseInsensitive
)
1055 : QString::compare(a
, b
, Qt::CaseInsensitive
);
1057 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1058 // comparison, still a deterministic sort order is required. A case sensitive
1059 // comparison is done as fallback.
1064 return m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseSensitive
)
1065 : QString::compare(a
, b
, Qt::CaseSensitive
);
1068 int KFileItemModel::expansionLevelsCompare(const KFileItem
& a
, const KFileItem
& b
) const
1070 const KUrl urlA
= a
.url();
1071 const KUrl urlB
= b
.url();
1072 if (urlA
.directory() == urlB
.directory()) {
1073 // Both items have the same directory as parent
1077 // Check whether one item is the parent of the other item
1078 if (urlA
.isParentOf(urlB
)) {
1080 } else if (urlB
.isParentOf(urlA
)) {
1084 // Determine the maximum common path of both items and
1085 // remember the index in 'index'
1086 const QString pathA
= urlA
.path();
1087 const QString pathB
= urlB
.path();
1089 const int maxIndex
= qMin(pathA
.length(), pathB
.length()) - 1;
1091 while (index
<= maxIndex
&& pathA
.at(index
) == pathB
.at(index
)) {
1094 if (index
> maxIndex
) {
1097 while ((pathA
.at(index
) != QLatin1Char('/') || pathB
.at(index
) != QLatin1Char('/')) && index
> 0) {
1101 // Determine the first sub-path after the common path and
1102 // check whether it represents a directory or already a file
1104 const QString subPathA
= subPath(a
, pathA
, index
, &isDirA
);
1106 const QString subPathB
= subPath(b
, pathB
, index
, &isDirB
);
1108 if (isDirA
&& !isDirB
) {
1110 } else if (!isDirA
&& isDirB
) {
1114 return stringCompare(subPathA
, subPathB
);
1117 QString
KFileItemModel::subPath(const KFileItem
& item
,
1118 const QString
& itemPath
,
1123 const int pathIndex
= itemPath
.indexOf('/', start
+ 1);
1124 *isDir
= (pathIndex
> 0) || item
.isDir();
1125 return itemPath
.mid(start
, pathIndex
- start
);
1128 bool KFileItemModel::useMaximumUpdateInterval() const
1130 const KDirLister
* dirLister
= m_dirLister
.data();
1131 return dirLister
&& !dirLister
->url().isLocalFile();
1134 #include "kfileitemmodel.moc"