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),
49 m_rootExpansionLevel(-1),
51 m_restoredExpandedUrls()
54 m_requestRole
[NameRole
] = true;
55 m_requestRole
[IsDirRole
] = true;
59 connect(dirLister
, SIGNAL(canceled()), this, SLOT(slotCanceled()));
60 connect(dirLister
, SIGNAL(completed()), this, SLOT(slotCompleted()));
61 connect(dirLister
, SIGNAL(newItems(KFileItemList
)), this, SLOT(slotNewItems(KFileItemList
)));
62 connect(dirLister
, SIGNAL(itemsDeleted(KFileItemList
)), this, SLOT(slotItemsDeleted(KFileItemList
)));
63 connect(dirLister
, SIGNAL(refreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)), this, SLOT(slotRefreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)));
64 connect(dirLister
, SIGNAL(clear()), this, SLOT(slotClear()));
65 connect(dirLister
, SIGNAL(clear(KUrl
)), this, SLOT(slotClear(KUrl
)));
67 // Although the layout engine of KItemListView is fast it is very inefficient to e.g.
68 // emit 50 itemsInserted()-signals each 100 ms. m_minimumUpdateIntervalTimer assures that updates
69 // are done in 1 second intervals for equal operations.
70 m_minimumUpdateIntervalTimer
= new QTimer(this);
71 m_minimumUpdateIntervalTimer
->setInterval(1000);
72 m_minimumUpdateIntervalTimer
->setSingleShot(true);
73 connect(m_minimumUpdateIntervalTimer
, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
75 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
76 // before the completed() or canceled() signal has been emitted.
77 m_maximumUpdateIntervalTimer
= new QTimer(this);
78 m_maximumUpdateIntervalTimer
->setInterval(2000);
79 m_maximumUpdateIntervalTimer
->setSingleShot(true);
80 connect(m_maximumUpdateIntervalTimer
, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
82 Q_ASSERT(m_minimumUpdateIntervalTimer
->interval() <= m_maximumUpdateIntervalTimer
->interval());
85 KFileItemModel::~KFileItemModel()
89 int KFileItemModel::count() const
91 return m_data
.count();
94 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
96 if (index
>= 0 && index
< count()) {
97 return m_data
.at(index
);
99 return QHash
<QByteArray
, QVariant
>();
102 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
104 if (index
>= 0 && index
< count()) {
105 QHash
<QByteArray
, QVariant
> currentValue
= m_data
.at(index
);
107 QSet
<QByteArray
> changedRoles
;
108 QHashIterator
<QByteArray
, QVariant
> it(values
);
109 while (it
.hasNext()) {
111 const QByteArray role
= it
.key();
112 const QVariant value
= it
.value();
114 if (currentValue
[role
] != value
) {
115 currentValue
[role
] = value
;
116 changedRoles
.insert(role
);
120 if (!changedRoles
.isEmpty()) {
121 m_data
[index
] = currentValue
;
122 emit
itemsChanged(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
130 void KFileItemModel::setSortFoldersFirst(bool foldersFirst
)
132 if (foldersFirst
!= m_sortFoldersFirst
) {
133 m_sortFoldersFirst
= foldersFirst
;
138 bool KFileItemModel::sortFoldersFirst() const
140 return m_sortFoldersFirst
;
143 QMimeData
* KFileItemModel::createMimeData(const QSet
<int>& indexes
) const
145 QMimeData
* data
= new QMimeData();
147 // The following code has been taken from KDirModel::mimeData()
148 // (kdelibs/kio/kio/kdirmodel.cpp)
149 // Copyright (C) 2006 David Faure <faure@kde.org>
151 KUrl::List mostLocalUrls
;
152 bool canUseMostLocalUrls
= true;
154 QSetIterator
<int> it(indexes
);
155 while (it
.hasNext()) {
156 const int index
= it
.next();
157 const KFileItem item
= fileItem(index
);
158 if (!item
.isNull()) {
162 mostLocalUrls
<< item
.mostLocalUrl(isLocal
);
164 canUseMostLocalUrls
= false;
169 const bool different
= canUseMostLocalUrls
&& mostLocalUrls
!= urls
;
170 urls
= KDirModel::simplifiedUrlList(urls
); // TODO: Check if we still need KDirModel for this in KDE 5.0
172 mostLocalUrls
= KDirModel::simplifiedUrlList(mostLocalUrls
);
173 urls
.populateMimeData(mostLocalUrls
, data
);
175 urls
.populateMimeData(data
);
181 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
183 startFromIndex
= qMax(0, startFromIndex
);
184 for (int i
= startFromIndex
; i
< count(); ++i
) {
185 if (data(i
)["name"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
189 for (int i
= 0; i
< startFromIndex
; ++i
) {
190 if (data(i
)["name"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
197 bool KFileItemModel::supportsDropping(int index
) const
199 const KFileItem item
= fileItem(index
);
200 return item
.isNull() ? false : item
.isDir();
203 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
207 switch (roleIndex(role
)) {
208 case NameRole
: descr
= i18nc("@item:intable", "Name"); break;
209 case SizeRole
: descr
= i18nc("@item:intable", "Size"); break;
210 case DateRole
: descr
= i18nc("@item:intable", "Date"); break;
211 case PermissionsRole
: descr
= i18nc("@item:intable", "Permissions"); break;
212 case OwnerRole
: descr
= i18nc("@item:intable", "Owner"); break;
213 case GroupRole
: descr
= i18nc("@item:intable", "Group"); break;
214 case TypeRole
: descr
= i18nc("@item:intable", "Type"); break;
215 case DestinationRole
: descr
= i18nc("@item:intable", "Destination"); break;
216 case PathRole
: descr
= i18nc("@item:intable", "Path"); break;
218 case IsDirRole
: break;
219 case IsExpandedRole
: break;
220 case ExpansionLevelRole
: break;
221 default: Q_ASSERT(false); break;
227 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
229 if (!m_data
.isEmpty() && m_groups
.isEmpty()) {
230 #ifdef KFILEITEMMODEL_DEBUG
234 switch (roleIndex(sortRole())) {
235 case NameRole
: m_groups
= nameRoleGroups(); break;
236 case SizeRole
: m_groups
= sizeRoleGroups(); break;
237 case DateRole
: m_groups
= dateRoleGroups(); break;
238 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
239 case OwnerRole
: m_groups
= ownerRoleGroups(); break;
240 case GroupRole
: m_groups
= groupRoleGroups(); break;
241 case TypeRole
: m_groups
= typeRoleGroups(); break;
242 case DestinationRole
: m_groups
= destinationRoleGroups(); break;
243 case PathRole
: m_groups
= pathRoleGroups(); break;
245 case IsDirRole
: break;
246 case IsExpandedRole
: break;
247 case ExpansionLevelRole
: break;
248 default: Q_ASSERT(false); break;
251 #ifdef KFILEITEMMODEL_DEBUG
252 kDebug() << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
259 KFileItem
KFileItemModel::fileItem(int index
) const
261 if (index
>= 0 && index
< count()) {
262 return m_sortedItems
.at(index
);
268 KFileItem
KFileItemModel::fileItem(const KUrl
& url
) const
270 const int index
= m_items
.value(url
, -1);
272 return m_sortedItems
.at(index
);
277 int KFileItemModel::index(const KFileItem
& item
) const
283 return m_items
.value(item
.url(), -1);
286 int KFileItemModel::index(const KUrl
& url
) const
288 KUrl urlToFind
= url
;
289 urlToFind
.adjustPath(KUrl::RemoveTrailingSlash
);
290 return m_items
.value(urlToFind
, -1);
293 KFileItem
KFileItemModel::rootItem() const
295 const KDirLister
* dirLister
= m_dirLister
.data();
297 return dirLister
->rootItem();
302 void KFileItemModel::clear()
307 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
310 const bool supportedExpanding
= m_requestRole
[IsExpandedRole
] && m_requestRole
[ExpansionLevelRole
];
311 const bool willSupportExpanding
= roles
.contains("isExpanded") && roles
.contains("expansionLevel");
312 if (supportedExpanding
&& !willSupportExpanding
) {
313 // No expanding is supported anymore. Take care to delete all items that have an expansion level
314 // that is not 0 (and hence are part of an expanded item).
315 removeExpandedItems();
320 QSetIterator
<QByteArray
> it(roles
);
321 while (it
.hasNext()) {
322 const QByteArray
& role
= it
.next();
323 m_requestRole
[roleIndex(role
)] = true;
327 // Update m_data with the changed requested roles
328 const int maxIndex
= count() - 1;
329 for (int i
= 0; i
<= maxIndex
; ++i
) {
330 m_data
[i
] = retrieveData(m_sortedItems
.at(i
));
333 kWarning() << "TODO: Emitting itemsChanged() with no information what has changed!";
334 emit
itemsChanged(KItemRangeList() << KItemRange(0, count()), QSet
<QByteArray
>());
338 QSet
<QByteArray
> KFileItemModel::roles() const
340 QSet
<QByteArray
> roles
;
341 for (int i
= 0; i
< RolesCount
; ++i
) {
342 if (m_requestRole
[i
]) {
345 case NameRole
: roles
.insert("name"); break;
346 case SizeRole
: roles
.insert("size"); break;
347 case DateRole
: roles
.insert("date"); break;
348 case PermissionsRole
: roles
.insert("permissions"); break;
349 case OwnerRole
: roles
.insert("owner"); break;
350 case GroupRole
: roles
.insert("group"); break;
351 case TypeRole
: roles
.insert("type"); break;
352 case DestinationRole
: roles
.insert("destination"); break;
353 case PathRole
: roles
.insert("path"); break;
354 case IsDirRole
: roles
.insert("isDir"); break;
355 case IsExpandedRole
: roles
.insert("isExpanded"); break;
356 case ExpansionLevelRole
: roles
.insert("expansionLevel"); break;
357 default: Q_ASSERT(false); break;
364 bool KFileItemModel::setExpanded(int index
, bool expanded
)
366 if (isExpanded(index
) == expanded
|| index
< 0 || index
>= count()) {
370 QHash
<QByteArray
, QVariant
> values
;
371 values
.insert("isExpanded", expanded
);
372 if (!setData(index
, values
)) {
376 const KUrl url
= m_sortedItems
.at(index
).url();
378 m_expandedUrls
.insert(url
);
380 KDirLister
* dirLister
= m_dirLister
.data();
382 dirLister
->openUrl(url
, KDirLister::Keep
);
386 m_expandedUrls
.remove(url
);
388 KFileItemList itemsToRemove
;
389 const int expansionLevel
= data(index
)["expansionLevel"].toInt();
391 while (index
< count() && data(index
)["expansionLevel"].toInt() > expansionLevel
) {
392 itemsToRemove
.append(m_sortedItems
.at(index
));
395 removeItems(itemsToRemove
);
402 bool KFileItemModel::isExpanded(int index
) const
404 if (index
>= 0 && index
< count()) {
405 return m_data
.at(index
).value("isExpanded").toBool();
410 bool KFileItemModel::isExpandable(int index
) const
412 if (index
>= 0 && index
< count()) {
413 return m_sortedItems
.at(index
).isDir();
418 QSet
<KUrl
> KFileItemModel::expandedUrls() const
420 return m_expandedUrls
;
423 void KFileItemModel::restoreExpandedUrls(const QSet
<KUrl
>& urls
)
425 m_restoredExpandedUrls
= urls
;
428 void KFileItemModel::onGroupedSortingChanged(bool current
)
434 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
437 m_sortRole
= roleIndex(current
);
441 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
448 void KFileItemModel::slotCompleted()
450 if (m_restoredExpandedUrls
.isEmpty() && m_minimumUpdateIntervalTimer
->isActive()) {
451 // dispatchPendingItems() will be called when the timer
453 m_pendingEmitLoadingCompleted
= true;
457 m_pendingEmitLoadingCompleted
= false;
458 dispatchPendingItemsToInsert();
460 if (!m_restoredExpandedUrls
.isEmpty()) {
461 // Try to find a URL that can be expanded.
462 // Note that the parent folder must be expanded before any of its subfolders become visible.
463 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
464 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
465 foreach(const KUrl
& url
, m_restoredExpandedUrls
) {
466 const int index
= m_items
.value(url
, -1);
468 // We have found an expandable URL. Expand it and return - when
469 // the dir lister has finished, this slot will be called again.
470 m_restoredExpandedUrls
.remove(url
);
471 setExpanded(index
, true);
476 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
477 // if these URLs have been deleted in the meantime.
478 m_restoredExpandedUrls
.clear();
481 emit
loadingCompleted();
482 m_minimumUpdateIntervalTimer
->start();
485 void KFileItemModel::slotCanceled()
487 m_minimumUpdateIntervalTimer
->stop();
488 m_maximumUpdateIntervalTimer
->stop();
489 dispatchPendingItemsToInsert();
492 void KFileItemModel::slotNewItems(const KFileItemList
& items
)
494 m_pendingItemsToInsert
.append(items
);
496 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer
->isActive()) {
497 // Assure that items get dispatched if no completed() or canceled() signal is
498 // emitted during the maximum update interval.
499 m_maximumUpdateIntervalTimer
->start();
503 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
505 if (!m_pendingItemsToInsert
.isEmpty()) {
506 insertItems(m_pendingItemsToInsert
);
507 m_pendingItemsToInsert
.clear();
512 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
514 Q_ASSERT(!items
.isEmpty());
515 #ifdef KFILEITEMMODEL_DEBUG
516 kDebug() << "Refreshing" << items
.count() << "items";
521 // Get the indexes of all items that have been refreshed
523 indexes
.reserve(items
.count());
525 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
526 while (it
.hasNext()) {
527 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
528 const int index
= m_items
.value(itemPair
.second
.url(), -1);
530 indexes
.append(index
);
534 // If the changed items have been created recently, they might not be in m_items yet.
535 // In that case, the list 'indexes' might be empty.
536 if (indexes
.isEmpty()) {
540 // Extract the item-ranges out of the changed indexes
543 KItemRangeList itemRangeList
;
546 int previousIndex
= indexes
.at(0);
548 const int maxIndex
= indexes
.count() - 1;
549 for (int i
= 1; i
<= maxIndex
; ++i
) {
550 const int currentIndex
= indexes
.at(i
);
551 if (currentIndex
== previousIndex
+ 1) {
554 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
556 rangeIndex
= currentIndex
;
559 previousIndex
= currentIndex
;
562 if (rangeCount
> 0) {
563 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
566 emit
itemsChanged(itemRangeList
, QSet
<QByteArray
>());
569 void KFileItemModel::slotClear()
571 #ifdef KFILEITEMMODEL_DEBUG
572 kDebug() << "Clearing all items";
577 m_minimumUpdateIntervalTimer
->stop();
578 m_maximumUpdateIntervalTimer
->stop();
579 m_pendingItemsToInsert
.clear();
581 m_rootExpansionLevel
= -1;
583 const int removedCount
= m_data
.count();
584 if (removedCount
> 0) {
585 m_sortedItems
.clear();
588 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
591 m_expandedUrls
.clear();
594 void KFileItemModel::slotClear(const KUrl
& url
)
599 void KFileItemModel::dispatchPendingItemsToInsert()
601 if (!m_pendingItemsToInsert
.isEmpty()) {
602 insertItems(m_pendingItemsToInsert
);
603 m_pendingItemsToInsert
.clear();
606 if (m_pendingEmitLoadingCompleted
) {
607 emit
loadingCompleted();
611 void KFileItemModel::insertItems(const KFileItemList
& items
)
613 if (items
.isEmpty()) {
617 #ifdef KFILEITEMMODEL_DEBUG
620 kDebug() << "===========================================================";
621 kDebug() << "Inserting" << items
.count() << "items";
626 KFileItemList sortedItems
= items
;
627 sort(sortedItems
.begin(), sortedItems
.end());
629 #ifdef KFILEITEMMODEL_DEBUG
630 kDebug() << "[TIME] Sorting:" << timer
.elapsed();
633 KItemRangeList itemRanges
;
636 int insertedAtIndex
= -1; // Index for the current item-range
637 int insertedCount
= 0; // Count for the current item-range
638 int previouslyInsertedCount
= 0; // Sum of previously inserted items for all ranges
639 while (sourceIndex
< sortedItems
.count()) {
640 // Find target index from m_items to insert the current item
642 const int previousTargetIndex
= targetIndex
;
643 while (targetIndex
< m_sortedItems
.count()) {
644 if (!lessThan(m_sortedItems
.at(targetIndex
), sortedItems
.at(sourceIndex
))) {
650 if (targetIndex
- previousTargetIndex
> 0 && insertedAtIndex
>= 0) {
651 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
652 previouslyInsertedCount
+= insertedCount
;
653 insertedAtIndex
= targetIndex
- previouslyInsertedCount
;
657 // Insert item at the position targetIndex
658 const KFileItem item
= sortedItems
.at(sourceIndex
);
659 m_sortedItems
.insert(targetIndex
, item
);
660 m_data
.insert(targetIndex
, retrieveData(item
));
661 // m_items will be inserted after the loop (see comment below)
664 if (insertedAtIndex
< 0) {
665 insertedAtIndex
= targetIndex
;
666 Q_ASSERT(previouslyInsertedCount
== 0);
672 // The indexes of all m_items must be adjusted, not only the index
674 for (int i
= 0; i
< m_sortedItems
.count(); ++i
) {
675 m_items
.insert(m_sortedItems
.at(i
).url(), i
);
678 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
679 emit
itemsInserted(itemRanges
);
681 #ifdef KFILEITEMMODEL_DEBUG
682 kDebug() << "[TIME] Inserting of" << items
.count() << "items:" << timer
.elapsed();
686 void KFileItemModel::removeItems(const KFileItemList
& items
)
688 if (items
.isEmpty()) {
692 #ifdef KFILEITEMMODEL_DEBUG
693 kDebug() << "Removing " << items
.count() << "items";
698 KFileItemList sortedItems
= items
;
699 sort(sortedItems
.begin(), sortedItems
.end());
701 QList
<int> indexesToRemove
;
702 indexesToRemove
.reserve(items
.count());
704 // Calculate the item ranges that will get deleted
705 KItemRangeList itemRanges
;
706 int removedAtIndex
= -1;
707 int removedCount
= 0;
709 foreach (const KFileItem
& itemToRemove
, sortedItems
) {
710 const int previousTargetIndex
= targetIndex
;
711 while (targetIndex
< m_sortedItems
.count()) {
712 if (m_sortedItems
.at(targetIndex
).url() == itemToRemove
.url()) {
717 if (targetIndex
>= m_sortedItems
.count()) {
718 kWarning() << "Item that should be deleted has not been found!";
722 if (targetIndex
- previousTargetIndex
> 0 && removedAtIndex
>= 0) {
723 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
724 removedAtIndex
= targetIndex
;
728 indexesToRemove
.append(targetIndex
);
729 if (removedAtIndex
< 0) {
730 removedAtIndex
= targetIndex
;
737 for (int i
= indexesToRemove
.count() - 1; i
>= 0; --i
) {
738 const int indexToRemove
= indexesToRemove
.at(i
);
739 m_items
.remove(m_sortedItems
.at(indexToRemove
).url());
740 m_sortedItems
.removeAt(indexToRemove
);
741 m_data
.removeAt(indexToRemove
);
744 // The indexes of all m_items must be adjusted, not only the index
745 // of the removed items
746 for (int i
= 0; i
< m_sortedItems
.count(); ++i
) {
747 m_items
.insert(m_sortedItems
.at(i
).url(), i
);
751 m_rootExpansionLevel
= -1;
754 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
755 emit
itemsRemoved(itemRanges
);
758 void KFileItemModel::resortAllItems()
760 const int itemCount
= count();
761 if (itemCount
<= 0) {
767 const KFileItemList oldSortedItems
= m_sortedItems
;
768 const QHash
<KUrl
, int> oldItems
= m_items
;
769 const QList
<QHash
<QByteArray
, QVariant
> > oldData
= m_data
;
774 sort(m_sortedItems
.begin(), m_sortedItems
.end());
776 foreach (const KFileItem
& item
, m_sortedItems
) {
777 m_items
.insert(item
.url(), index
);
779 const int oldItemIndex
= oldItems
.value(item
.url());
780 m_data
.append(oldData
.at(oldItemIndex
));
785 bool emitItemsMoved
= false;
786 QList
<int> movedToIndexes
;
787 movedToIndexes
.reserve(m_sortedItems
.count());
788 for (int i
= 0; i
< itemCount
; i
++) {
789 const int newIndex
= m_items
.value(oldSortedItems
.at(i
).url());
790 movedToIndexes
.append(newIndex
);
791 if (!emitItemsMoved
&& newIndex
!= i
) {
792 emitItemsMoved
= true;
796 if (emitItemsMoved
) {
797 emit
itemsMoved(KItemRange(0, itemCount
), movedToIndexes
);
801 void KFileItemModel::removeExpandedItems()
803 KFileItemList expandedItems
;
805 const int maxIndex
= m_data
.count() - 1;
806 for (int i
= 0; i
<= maxIndex
; ++i
) {
807 if (m_data
.at(i
).value("expansionLevel").toInt() > 0) {
808 const KFileItem fileItem
= m_sortedItems
.at(i
);
809 expandedItems
.append(fileItem
);
813 // The m_rootExpansionLevel may not get reset before all items with
814 // a bigger expansionLevel have been removed.
815 Q_ASSERT(m_rootExpansionLevel
>= 0);
816 removeItems(expandedItems
);
818 m_rootExpansionLevel
= -1;
819 m_expandedUrls
.clear();
822 void KFileItemModel::resetRoles()
824 for (int i
= 0; i
< RolesCount
; ++i
) {
825 m_requestRole
[i
] = false;
829 KFileItemModel::Role
KFileItemModel::roleIndex(const QByteArray
& role
) const
831 static QHash
<QByteArray
, Role
> rolesHash
;
832 if (rolesHash
.isEmpty()) {
833 rolesHash
.insert("name", NameRole
);
834 rolesHash
.insert("size", SizeRole
);
835 rolesHash
.insert("date", DateRole
);
836 rolesHash
.insert("permissions", PermissionsRole
);
837 rolesHash
.insert("owner", OwnerRole
);
838 rolesHash
.insert("group", GroupRole
);
839 rolesHash
.insert("type", TypeRole
);
840 rolesHash
.insert("destination", DestinationRole
);
841 rolesHash
.insert("path", PathRole
);
842 rolesHash
.insert("isDir", IsDirRole
);
843 rolesHash
.insert("isExpanded", IsExpandedRole
);
844 rolesHash
.insert("expansionLevel", ExpansionLevelRole
);
846 return rolesHash
.value(role
, NoRole
);
849 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
) const
851 // It is important to insert only roles that are fast to retrieve. E.g.
852 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
853 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
854 QHash
<QByteArray
, QVariant
> data
;
855 data
.insert("iconPixmap", QPixmap());
857 const bool isDir
= item
.isDir();
858 if (m_requestRole
[IsDirRole
]) {
859 data
.insert("isDir", isDir
);
862 if (m_requestRole
[NameRole
]) {
863 data
.insert("name", item
.name());
866 if (m_requestRole
[SizeRole
]) {
868 data
.insert("size", QVariant());
870 data
.insert("size", item
.size());
874 if (m_requestRole
[DateRole
]) {
875 // Don't use KFileItem::timeString() as this is too expensive when
876 // having several thousands of items. Instead the formatting of the
877 // date-time will be done on-demand by the view when the date will be shown.
878 const KDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
879 data
.insert("date", dateTime
.dateTime());
882 if (m_requestRole
[PermissionsRole
]) {
883 data
.insert("permissions", item
.permissionsString());
886 if (m_requestRole
[OwnerRole
]) {
887 data
.insert("owner", item
.user());
890 if (m_requestRole
[GroupRole
]) {
891 data
.insert("group", item
.group());
894 if (m_requestRole
[DestinationRole
]) {
895 QString destination
= item
.linkDest();
896 if (destination
.isEmpty()) {
897 destination
= i18nc("@item:intable", "No destination");
899 data
.insert("destination", destination
);
902 if (m_requestRole
[PathRole
]) {
903 data
.insert("path", item
.localPath());
906 if (m_requestRole
[IsExpandedRole
]) {
907 data
.insert("isExpanded", false);
910 if (m_requestRole
[ExpansionLevelRole
]) {
911 if (m_rootExpansionLevel
< 0) {
912 KDirLister
* dirLister
= m_dirLister
.data();
914 const QString rootDir
= dirLister
->url().directory(KUrl::AppendTrailingSlash
);
915 m_rootExpansionLevel
= rootDir
.count('/');
918 const QString dir
= item
.url().directory(KUrl::AppendTrailingSlash
);
919 const int level
= dir
.count('/') - m_rootExpansionLevel
- 1;
920 data
.insert("expansionLevel", level
);
923 if (item
.isMimeTypeKnown()) {
924 data
.insert("iconName", item
.iconName());
926 if (m_requestRole
[TypeRole
]) {
927 data
.insert("type", item
.mimeComment());
934 bool KFileItemModel::lessThan(const KFileItem
& a
, const KFileItem
& b
) const
938 if (m_rootExpansionLevel
>= 0) {
939 result
= expansionLevelsCompare(a
, b
);
941 // The items have parents with different expansion levels
942 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
946 if (m_sortFoldersFirst
|| m_sortRole
== SizeRole
) {
947 const bool isDirA
= a
.isDir();
948 const bool isDirB
= b
.isDir();
949 if (isDirA
&& !isDirB
) {
951 } else if (!isDirA
&& isDirB
) {
956 switch (m_sortRole
) {
958 result
= stringCompare(a
.text(), b
.text());
960 // KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
961 result
= stringCompare(a
.name(m_caseSensitivity
== Qt::CaseInsensitive
),
962 b
.name(m_caseSensitivity
== Qt::CaseInsensitive
));
968 const KDateTime dateTimeA
= a
.time(KFileItem::ModificationTime
);
969 const KDateTime dateTimeB
= b
.time(KFileItem::ModificationTime
);
970 if (dateTimeA
< dateTimeB
) {
972 } else if (dateTimeA
> dateTimeB
) {
979 // TODO: Implement sorting folders by the number of items inside.
980 // This is more tricky to get right because this number is retrieved
981 // asynchronously by KFileItemModelRolesUpdater.
982 const KIO::filesize_t sizeA
= a
.size();
983 const KIO::filesize_t sizeB
= b
.size();
986 } else if (sizeA
> sizeB
) {
997 // It must be assured that the sort order is always unique even if two values have been
998 // equal. In this case a comparison of the URL is done which is unique in all cases
999 // within KDirLister.
1000 result
= QString::compare(a
.url().url(), b
.url().url(), Qt::CaseSensitive
);
1003 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1006 void KFileItemModel::sort(const KFileItemList::iterator
& startIterator
, const KFileItemList::iterator
& endIterator
)
1008 KFileItemList::iterator start
= startIterator
;
1009 KFileItemList::iterator end
= endIterator
;
1011 // The implementation is based on qSortHelper() from qalgorithms.h
1012 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1013 // In opposite to qSort() it allows to use a member-function for the comparison of elements.
1015 int span
= int(end
- start
);
1021 KFileItemList::iterator low
= start
, high
= end
- 1;
1022 KFileItemList::iterator pivot
= start
+ span
/ 2;
1024 if (lessThan(*end
, *start
)) {
1025 qSwap(*end
, *start
);
1031 if (lessThan(*pivot
, *start
)) {
1032 qSwap(*pivot
, *start
);
1034 if (lessThan(*end
, *pivot
)) {
1035 qSwap(*end
, *pivot
);
1041 qSwap(*pivot
, *end
);
1043 while (low
< high
) {
1044 while (low
< high
&& lessThan(*low
, *end
)) {
1048 while (high
> low
&& lessThan(*end
, *high
)) {
1060 if (lessThan(*low
, *end
)) {
1072 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
) const
1074 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1075 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1076 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1077 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1079 if (m_caseSensitivity
== Qt::CaseInsensitive
) {
1080 const int result
= m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseInsensitive
)
1081 : QString::compare(a
, b
, Qt::CaseInsensitive
);
1083 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1084 // comparison, still a deterministic sort order is required. A case sensitive
1085 // comparison is done as fallback.
1090 return m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseSensitive
)
1091 : QString::compare(a
, b
, Qt::CaseSensitive
);
1094 int KFileItemModel::expansionLevelsCompare(const KFileItem
& a
, const KFileItem
& b
) const
1096 const KUrl urlA
= a
.url();
1097 const KUrl urlB
= b
.url();
1098 if (urlA
.directory() == urlB
.directory()) {
1099 // Both items have the same directory as parent
1103 // Check whether one item is the parent of the other item
1104 if (urlA
.isParentOf(urlB
)) {
1106 } else if (urlB
.isParentOf(urlA
)) {
1110 // Determine the maximum common path of both items and
1111 // remember the index in 'index'
1112 const QString pathA
= urlA
.path();
1113 const QString pathB
= urlB
.path();
1115 const int maxIndex
= qMin(pathA
.length(), pathB
.length()) - 1;
1117 while (index
<= maxIndex
&& pathA
.at(index
) == pathB
.at(index
)) {
1120 if (index
> maxIndex
) {
1123 while ((pathA
.at(index
) != QLatin1Char('/') || pathB
.at(index
) != QLatin1Char('/')) && index
> 0) {
1127 // Determine the first sub-path after the common path and
1128 // check whether it represents a directory or already a file
1130 const QString subPathA
= subPath(a
, pathA
, index
, &isDirA
);
1132 const QString subPathB
= subPath(b
, pathB
, index
, &isDirB
);
1134 if (isDirA
&& !isDirB
) {
1136 } else if (!isDirA
&& isDirB
) {
1140 return stringCompare(subPathA
, subPathB
);
1143 QString
KFileItemModel::subPath(const KFileItem
& item
,
1144 const QString
& itemPath
,
1149 const int pathIndex
= itemPath
.indexOf('/', start
+ 1);
1150 *isDir
= (pathIndex
> 0) || item
.isDir();
1151 return itemPath
.mid(start
, pathIndex
- start
);
1154 bool KFileItemModel::useMaximumUpdateInterval() const
1156 const KDirLister
* dirLister
= m_dirLister
.data();
1157 return dirLister
&& !dirLister
->url().isLocalFile();
1160 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1162 Q_ASSERT(!m_data
.isEmpty());
1164 const int maxIndex
= count() - 1;
1165 QList
<QPair
<int, QVariant
> > groups
;
1169 bool isLetter
= false;
1170 for (int i
= 0; i
<= maxIndex
; ++i
) {
1171 if (m_requestRole
[ExpansionLevelRole
] && m_data
.at(i
).value("expansionLevel").toInt() > 0) {
1172 // KItemListView would be capable to show sub-groups in groups but
1173 // in typical usecases this results in visual clutter, hence we
1174 // just ignore sub-groups.
1178 const QString name
= m_data
.at(i
).value("name").toString();
1180 // Use the first character of the name as group indication
1181 QChar newFirstChar
= name
.at(0).toUpper();
1182 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1183 newFirstChar
= name
.at(1);
1186 if (firstChar
!= newFirstChar
) {
1187 QString newGroupValue
;
1188 if (newFirstChar
>= QLatin1Char('A') && newFirstChar
<= QLatin1Char('Z')) {
1189 // Apply group 'A' - 'Z'
1190 newGroupValue
= newFirstChar
;
1192 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
1193 // Apply group '0 - 9' for any name that starts with a digit
1194 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
1198 // If the current group is 'A' - 'Z' check whether a locale character
1199 // fits into the existing group.
1200 // TODO: This does not work in the case if e.g. the group 'O' starts with
1201 // an umlaut 'O' -> provide unit-test to document this known issue
1202 const QChar
prevChar(firstChar
.unicode() - ushort(1));
1203 const QChar
nextChar(firstChar
.unicode() + ushort(1));
1204 const QString
currChar(newFirstChar
);
1205 const bool partOfCurrentGroup
= currChar
.localeAwareCompare(prevChar
) > 0 &&
1206 currChar
.localeAwareCompare(nextChar
) < 0;
1207 if (partOfCurrentGroup
) {
1211 newGroupValue
= i18nc("@title:group", "Others");
1215 if (newGroupValue
!= groupValue
) {
1216 groupValue
= newGroupValue
;
1217 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1220 firstChar
= newFirstChar
;
1226 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
1228 Q_ASSERT(!m_data
.isEmpty());
1230 return QList
<QPair
<int, QVariant
> >();
1233 QList
<QPair
<int, QVariant
> > KFileItemModel::dateRoleGroups() const
1235 Q_ASSERT(!m_data
.isEmpty());
1236 return QList
<QPair
<int, QVariant
> >();
1239 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
1241 Q_ASSERT(!m_data
.isEmpty());
1242 return QList
<QPair
<int, QVariant
> >();
1245 QList
<QPair
<int, QVariant
> > KFileItemModel::ownerRoleGroups() const
1247 Q_ASSERT(!m_data
.isEmpty());
1248 return QList
<QPair
<int, QVariant
> >();
1251 QList
<QPair
<int, QVariant
> > KFileItemModel::groupRoleGroups() const
1253 Q_ASSERT(!m_data
.isEmpty());
1254 return QList
<QPair
<int, QVariant
> >();
1257 QList
<QPair
<int, QVariant
> > KFileItemModel::typeRoleGroups() const
1259 Q_ASSERT(!m_data
.isEmpty());
1260 return QList
<QPair
<int, QVariant
> >();
1263 QList
<QPair
<int, QVariant
> > KFileItemModel::destinationRoleGroups() const
1265 Q_ASSERT(!m_data
.isEmpty());
1266 return QList
<QPair
<int, QVariant
> >();
1269 QList
<QPair
<int, QVariant
> > KFileItemModel::pathRoleGroups() const
1271 Q_ASSERT(!m_data
.isEmpty());
1272 return QList
<QPair
<int, QVariant
> >();
1275 #include "kfileitemmodel.moc"