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(QByteArray(), "name", parent
),
35 m_dirLister(dirLister
),
36 m_naturalSorting(true),
37 m_sortFoldersFirst(true),
40 m_caseSensitivity(Qt::CaseInsensitive
),
45 m_minimumUpdateIntervalTimer(0),
46 m_maximumUpdateIntervalTimer(0),
47 m_pendingItemsToInsert(),
48 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 bool KFileItemModel::supportsGrouping() const
135 bool KFileItemModel::supportsSorting() const
140 void KFileItemModel::setSortFoldersFirst(bool foldersFirst
)
142 if (foldersFirst
!= m_sortFoldersFirst
) {
143 m_sortFoldersFirst
= foldersFirst
;
148 bool KFileItemModel::sortFoldersFirst() const
150 return m_sortFoldersFirst
;
153 QMimeData
* KFileItemModel::createMimeData(const QSet
<int>& indexes
) const
155 QMimeData
* data
= new QMimeData();
157 // The following code has been taken from KDirModel::mimeData()
158 // (kdelibs/kio/kio/kdirmodel.cpp)
159 // Copyright (C) 2006 David Faure <faure@kde.org>
161 KUrl::List mostLocalUrls
;
162 bool canUseMostLocalUrls
= true;
164 QSetIterator
<int> it(indexes
);
165 while (it
.hasNext()) {
166 const int index
= it
.next();
167 const KFileItem item
= fileItem(index
);
168 if (!item
.isNull()) {
172 mostLocalUrls
<< item
.mostLocalUrl(isLocal
);
174 canUseMostLocalUrls
= false;
179 const bool different
= canUseMostLocalUrls
&& mostLocalUrls
!= urls
;
180 urls
= KDirModel::simplifiedUrlList(urls
); // TODO: Check if we still need KDirModel for this in KDE 5.0
182 mostLocalUrls
= KDirModel::simplifiedUrlList(mostLocalUrls
);
183 urls
.populateMimeData(mostLocalUrls
, data
);
185 urls
.populateMimeData(data
);
191 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
193 startFromIndex
= qMax(0, startFromIndex
);
194 for (int i
= startFromIndex
; i
< count(); i
++) {
195 if (data(i
)["name"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
196 kDebug() << data(i
)["name"].toString();
200 for (int i
= 0; i
< startFromIndex
; i
++) {
201 if (data(i
)["name"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
202 kDebug() << data(i
)["name"].toString();
209 bool KFileItemModel::supportsDropping(int index
) const
211 const KFileItem item
= fileItem(index
);
212 return item
.isNull() ? false : item
.isDir();
215 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
219 switch (roleIndex(role
)) {
220 case NameRole
: descr
= i18nc("@item:intable", "Name"); break;
221 case SizeRole
: descr
= i18nc("@item:intable", "Size"); break;
222 case DateRole
: descr
= i18nc("@item:intable", "Date"); break;
223 case PermissionsRole
: descr
= i18nc("@item:intable", "Permissions"); break;
224 case OwnerRole
: descr
= i18nc("@item:intable", "Owner"); break;
225 case GroupRole
: descr
= i18nc("@item:intable", "Group"); break;
226 case TypeRole
: descr
= i18nc("@item:intable", "Type"); break;
227 case DestinationRole
: descr
= i18nc("@item:intable", "Destination"); break;
228 case PathRole
: descr
= i18nc("@item:intable", "Path"); break;
230 case IsDirRole
: break;
231 case IsExpandedRole
: break;
232 case ExpansionLevelRole
: break;
233 default: Q_ASSERT(false); break;
239 KFileItem
KFileItemModel::fileItem(int index
) const
241 if (index
>= 0 && index
< count()) {
242 return m_sortedItems
.at(index
);
248 KFileItem
KFileItemModel::fileItem(const KUrl
& url
) const
250 const int index
= m_items
.value(url
, -1);
252 return m_sortedItems
.at(index
);
257 int KFileItemModel::index(const KFileItem
& item
) const
263 return m_items
.value(item
.url(), -1);
266 KFileItem
KFileItemModel::rootItem() const
268 const KDirLister
* dirLister
= m_dirLister
.data();
270 return dirLister
->rootItem();
275 void KFileItemModel::clear()
280 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
283 const bool supportedExpanding
= m_requestRole
[IsExpandedRole
] && m_requestRole
[ExpansionLevelRole
];
284 const bool willSupportExpanding
= roles
.contains("isExpanded") && roles
.contains("expansionLevel");
285 if (supportedExpanding
&& !willSupportExpanding
) {
286 // No expanding is supported anymore. Take care to delete all items that have an expansion level
287 // that is not 0 (and hence are part of an expanded item).
288 removeExpandedItems();
293 QSetIterator
<QByteArray
> it(roles
);
294 while (it
.hasNext()) {
295 const QByteArray
& role
= it
.next();
296 m_requestRole
[roleIndex(role
)] = true;
300 // Update m_data with the changed requested roles
301 const int maxIndex
= count() - 1;
302 for (int i
= 0; i
<= maxIndex
; ++i
) {
303 m_data
[i
] = retrieveData(m_sortedItems
.at(i
));
306 kWarning() << "TODO: Emitting itemsChanged() with no information what has changed!";
307 emit
itemsChanged(KItemRangeList() << KItemRange(0, count()), QSet
<QByteArray
>());
311 QSet
<QByteArray
> KFileItemModel::roles() const
313 QSet
<QByteArray
> roles
;
314 for (int i
= 0; i
< RolesCount
; ++i
) {
315 if (m_requestRole
[i
]) {
318 case NameRole
: roles
.insert("name"); break;
319 case SizeRole
: roles
.insert("size"); break;
320 case DateRole
: roles
.insert("date"); break;
321 case PermissionsRole
: roles
.insert("permissions"); break;
322 case OwnerRole
: roles
.insert("owner"); break;
323 case GroupRole
: roles
.insert("group"); break;
324 case TypeRole
: roles
.insert("type"); break;
325 case DestinationRole
: roles
.insert("destination"); break;
326 case PathRole
: roles
.insert("path"); break;
327 case IsDirRole
: roles
.insert("isDir"); break;
328 case IsExpandedRole
: roles
.insert("isExpanded"); break;
329 case ExpansionLevelRole
: roles
.insert("expansionLevel"); break;
330 default: Q_ASSERT(false); break;
337 bool KFileItemModel::setExpanded(int index
, bool expanded
)
339 if (isExpanded(index
) == expanded
|| index
< 0 || index
>= count()) {
343 QHash
<QByteArray
, QVariant
> values
;
344 values
.insert("isExpanded", expanded
);
345 if (!setData(index
, values
)) {
349 const KUrl url
= m_sortedItems
.at(index
).url();
351 m_expandedUrls
.insert(url
);
353 KDirLister
* dirLister
= m_dirLister
.data();
355 dirLister
->openUrl(url
, KDirLister::Keep
);
359 m_expandedUrls
.remove(url
);
361 KFileItemList itemsToRemove
;
362 const int expansionLevel
= data(index
)["expansionLevel"].toInt();
364 while (index
< count() && data(index
)["expansionLevel"].toInt() > expansionLevel
) {
365 itemsToRemove
.append(m_sortedItems
.at(index
));
368 removeItems(itemsToRemove
);
375 bool KFileItemModel::isExpanded(int index
) const
377 if (index
>= 0 && index
< count()) {
378 return m_data
.at(index
).value("isExpanded").toBool();
383 bool KFileItemModel::isExpandable(int index
) const
385 if (index
>= 0 && index
< count()) {
386 return m_sortedItems
.at(index
).isDir();
391 QSet
<KUrl
> KFileItemModel::expandedUrls() const
393 return m_expandedUrls
;
396 void KFileItemModel::restoreExpandedUrls(const QSet
<KUrl
>& urls
)
398 m_restoredExpandedUrls
= urls
;
401 void KFileItemModel::onGroupRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
404 m_groupRole
= roleIndex(current
);
407 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
410 m_sortRole
= roleIndex(current
);
414 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
421 void KFileItemModel::slotCompleted()
423 if (m_restoredExpandedUrls
.isEmpty() && m_minimumUpdateIntervalTimer
->isActive()) {
424 // dispatchPendingItems() will be called when the timer
426 m_pendingEmitLoadingCompleted
= true;
430 m_pendingEmitLoadingCompleted
= false;
431 dispatchPendingItemsToInsert();
433 if (!m_restoredExpandedUrls
.isEmpty()) {
434 // Try to find a URL that can be expanded.
435 // Note that the parent folder must be expanded before any of its subfolders become visible.
436 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
437 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
438 foreach(const KUrl
& url
, m_restoredExpandedUrls
) {
439 const int index
= m_items
.value(url
, -1);
441 // We have found an expandable URL. Expand it and return - when
442 // the dir lister has finished, this slot will be called again.
443 m_restoredExpandedUrls
.remove(url
);
444 setExpanded(index
, true);
449 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
450 // if these URLs have been deleted in the meantime.
451 m_restoredExpandedUrls
.clear();
454 emit
loadingCompleted();
455 m_minimumUpdateIntervalTimer
->start();
458 void KFileItemModel::slotCanceled()
460 m_minimumUpdateIntervalTimer
->stop();
461 m_maximumUpdateIntervalTimer
->stop();
462 dispatchPendingItemsToInsert();
465 void KFileItemModel::slotNewItems(const KFileItemList
& items
)
467 m_pendingItemsToInsert
.append(items
);
469 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer
->isActive()) {
470 // Assure that items get dispatched if no completed() or canceled() signal is
471 // emitted during the maximum update interval.
472 m_maximumUpdateIntervalTimer
->start();
476 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
478 if (!m_pendingItemsToInsert
.isEmpty()) {
479 insertItems(m_pendingItemsToInsert
);
480 m_pendingItemsToInsert
.clear();
485 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
487 Q_ASSERT(!items
.isEmpty());
488 #ifdef KFILEITEMMODEL_DEBUG
489 kDebug() << "Refreshing" << items
.count() << "items";
492 // Get the indexes of all items that have been refreshed
494 indexes
.reserve(items
.count());
496 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
497 while (it
.hasNext()) {
498 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
499 const int index
= m_items
.value(itemPair
.second
.url(), -1);
501 indexes
.append(index
);
505 // If the changed items have been created recently, they might not be in m_items yet.
506 // In that case, the list 'indexes' might be empty.
507 if (indexes
.isEmpty()) {
511 // Extract the item-ranges out of the changed indexes
514 KItemRangeList itemRangeList
;
517 int previousIndex
= indexes
.at(0);
519 const int maxIndex
= indexes
.count() - 1;
520 for (int i
= 1; i
<= maxIndex
; ++i
) {
521 const int currentIndex
= indexes
.at(i
);
522 if (currentIndex
== previousIndex
+ 1) {
525 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
527 rangeIndex
= currentIndex
;
530 previousIndex
= currentIndex
;
533 if (rangeCount
> 0) {
534 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
537 emit
itemsChanged(itemRangeList
, QSet
<QByteArray
>());
540 void KFileItemModel::slotClear()
542 #ifdef KFILEITEMMODEL_DEBUG
543 kDebug() << "Clearing all items";
546 m_minimumUpdateIntervalTimer
->stop();
547 m_maximumUpdateIntervalTimer
->stop();
548 m_pendingItemsToInsert
.clear();
550 m_rootExpansionLevel
= -1;
552 const int removedCount
= m_data
.count();
553 if (removedCount
> 0) {
554 m_sortedItems
.clear();
557 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
560 m_expandedUrls
.clear();
563 void KFileItemModel::slotClear(const KUrl
& url
)
568 void KFileItemModel::dispatchPendingItemsToInsert()
570 if (!m_pendingItemsToInsert
.isEmpty()) {
571 insertItems(m_pendingItemsToInsert
);
572 m_pendingItemsToInsert
.clear();
575 if (m_pendingEmitLoadingCompleted
) {
576 emit
loadingCompleted();
580 void KFileItemModel::insertItems(const KFileItemList
& items
)
582 if (items
.isEmpty()) {
586 #ifdef KFILEITEMMODEL_DEBUG
589 kDebug() << "===========================================================";
590 kDebug() << "Inserting" << items
.count() << "items";
593 KFileItemList sortedItems
= items
;
594 sort(sortedItems
.begin(), sortedItems
.end());
596 #ifdef KFILEITEMMODEL_DEBUG
597 kDebug() << "[TIME] Sorting:" << timer
.elapsed();
600 KItemRangeList itemRanges
;
603 int insertedAtIndex
= -1; // Index for the current item-range
604 int insertedCount
= 0; // Count for the current item-range
605 int previouslyInsertedCount
= 0; // Sum of previously inserted items for all ranges
606 while (sourceIndex
< sortedItems
.count()) {
607 // Find target index from m_items to insert the current item
609 const int previousTargetIndex
= targetIndex
;
610 while (targetIndex
< m_sortedItems
.count()) {
611 if (!lessThan(m_sortedItems
.at(targetIndex
), sortedItems
.at(sourceIndex
))) {
617 if (targetIndex
- previousTargetIndex
> 0 && insertedAtIndex
>= 0) {
618 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
619 previouslyInsertedCount
+= insertedCount
;
620 insertedAtIndex
= targetIndex
- previouslyInsertedCount
;
624 // Insert item at the position targetIndex
625 const KFileItem item
= sortedItems
.at(sourceIndex
);
626 m_sortedItems
.insert(targetIndex
, item
);
627 m_data
.insert(targetIndex
, retrieveData(item
));
628 // m_items will be inserted after the loop (see comment below)
631 if (insertedAtIndex
< 0) {
632 insertedAtIndex
= targetIndex
;
633 Q_ASSERT(previouslyInsertedCount
== 0);
639 // The indexes of all m_items must be adjusted, not only the index
641 for (int i
= 0; i
< m_sortedItems
.count(); ++i
) {
642 m_items
.insert(m_sortedItems
.at(i
).url(), i
);
645 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
646 emit
itemsInserted(itemRanges
);
648 #ifdef KFILEITEMMODEL_DEBUG
649 kDebug() << "[TIME] Inserting of" << items
.count() << "items:" << timer
.elapsed();
653 void KFileItemModel::removeItems(const KFileItemList
& items
)
655 if (items
.isEmpty()) {
659 #ifdef KFILEITEMMODEL_DEBUG
660 kDebug() << "Removing " << items
.count() << "items";
663 KFileItemList sortedItems
= items
;
664 sort(sortedItems
.begin(), sortedItems
.end());
666 QList
<int> indexesToRemove
;
667 indexesToRemove
.reserve(items
.count());
669 // Calculate the item ranges that will get deleted
670 KItemRangeList itemRanges
;
671 int removedAtIndex
= -1;
672 int removedCount
= 0;
674 foreach (const KFileItem
& itemToRemove
, sortedItems
) {
675 const int previousTargetIndex
= targetIndex
;
676 while (targetIndex
< m_sortedItems
.count()) {
677 if (m_sortedItems
.at(targetIndex
).url() == itemToRemove
.url()) {
682 if (targetIndex
>= m_sortedItems
.count()) {
683 kWarning() << "Item that should be deleted has not been found!";
687 if (targetIndex
- previousTargetIndex
> 0 && removedAtIndex
>= 0) {
688 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
689 removedAtIndex
= targetIndex
;
693 indexesToRemove
.append(targetIndex
);
694 if (removedAtIndex
< 0) {
695 removedAtIndex
= targetIndex
;
702 for (int i
= indexesToRemove
.count() - 1; i
>= 0; --i
) {
703 const int indexToRemove
= indexesToRemove
.at(i
);
704 m_items
.remove(m_sortedItems
.at(indexToRemove
).url());
705 m_sortedItems
.removeAt(indexToRemove
);
706 m_data
.removeAt(indexToRemove
);
709 // The indexes of all m_items must be adjusted, not only the index
710 // of the removed items
711 for (int i
= 0; i
< m_sortedItems
.count(); ++i
) {
712 m_items
.insert(m_sortedItems
.at(i
).url(), i
);
716 m_rootExpansionLevel
= -1;
719 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
720 emit
itemsRemoved(itemRanges
);
723 void KFileItemModel::resortAllItems()
725 const int itemCount
= count();
726 if (itemCount
<= 0) {
730 KFileItemList sortedItems
= m_sortedItems
;
731 m_sortedItems
.clear();
734 emit
itemsRemoved(KItemRangeList() << KItemRange(0, itemCount
));
736 sort(sortedItems
.begin(), sortedItems
.end());
738 foreach (const KFileItem
& item
, sortedItems
) {
739 m_sortedItems
.append(item
);
740 m_items
.insert(item
.url(), index
);
741 m_data
.append(retrieveData(item
));
746 emit
itemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
749 void KFileItemModel::removeExpandedItems()
752 KFileItemList expandedItems
;
754 const int maxIndex
= m_data
.count() - 1;
755 for (int i
= 0; i
<= maxIndex
; ++i
) {
756 if (m_data
.at(i
).value("expansionLevel").toInt() > 0) {
757 const KFileItem fileItem
= m_sortedItems
.at(i
);
758 expandedItems
.append(fileItem
);
762 // The m_rootExpansionLevel may not get reset before all items with
763 // a bigger expansionLevel have been removed.
764 Q_ASSERT(m_rootExpansionLevel
>= 0);
765 removeItems(expandedItems
);
767 m_rootExpansionLevel
= -1;
768 m_expandedUrls
.clear();
771 void KFileItemModel::resetRoles()
773 for (int i
= 0; i
< RolesCount
; ++i
) {
774 m_requestRole
[i
] = false;
778 KFileItemModel::Role
KFileItemModel::roleIndex(const QByteArray
& role
) const
780 static QHash
<QByteArray
, Role
> rolesHash
;
781 if (rolesHash
.isEmpty()) {
782 rolesHash
.insert("name", NameRole
);
783 rolesHash
.insert("size", SizeRole
);
784 rolesHash
.insert("date", DateRole
);
785 rolesHash
.insert("permissions", PermissionsRole
);
786 rolesHash
.insert("owner", OwnerRole
);
787 rolesHash
.insert("group", GroupRole
);
788 rolesHash
.insert("type", TypeRole
);
789 rolesHash
.insert("destination", DestinationRole
);
790 rolesHash
.insert("path", PathRole
);
791 rolesHash
.insert("isDir", IsDirRole
);
792 rolesHash
.insert("isExpanded", IsExpandedRole
);
793 rolesHash
.insert("expansionLevel", ExpansionLevelRole
);
795 return rolesHash
.value(role
, NoRole
);
798 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
) const
800 // It is important to insert only roles that are fast to retrieve. E.g.
801 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
802 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
803 QHash
<QByteArray
, QVariant
> data
;
804 data
.insert("iconPixmap", QPixmap());
806 const bool isDir
= item
.isDir();
807 if (m_requestRole
[IsDirRole
]) {
808 data
.insert("isDir", isDir
);
811 if (m_requestRole
[NameRole
]) {
812 data
.insert("name", item
.name());
815 if (m_requestRole
[SizeRole
]) {
817 data
.insert("size", QVariant());
819 data
.insert("size", item
.size());
823 if (m_requestRole
[DateRole
]) {
824 // Don't use KFileItem::timeString() as this is too expensive when
825 // having several thousands of items. Instead the formatting of the
826 // date-time will be done on-demand by the view when the date will be shown.
827 const KDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
828 data
.insert("date", dateTime
.dateTime());
831 if (m_requestRole
[PermissionsRole
]) {
832 data
.insert("permissions", item
.permissionsString());
835 if (m_requestRole
[OwnerRole
]) {
836 data
.insert("owner", item
.user());
839 if (m_requestRole
[GroupRole
]) {
840 data
.insert("group", item
.group());
843 if (m_requestRole
[DestinationRole
]) {
844 QString destination
= item
.linkDest();
845 if (destination
.isEmpty()) {
846 destination
= i18nc("@item:intable", "No destination");
848 data
.insert("destination", destination
);
851 if (m_requestRole
[PathRole
]) {
852 data
.insert("path", item
.localPath());
855 if (m_requestRole
[IsExpandedRole
]) {
856 data
.insert("isExpanded", false);
859 if (m_requestRole
[ExpansionLevelRole
]) {
860 if (m_rootExpansionLevel
< 0) {
861 KDirLister
* dirLister
= m_dirLister
.data();
863 const QString rootDir
= dirLister
->url().directory(KUrl::AppendTrailingSlash
);
864 m_rootExpansionLevel
= rootDir
.count('/');
867 const QString dir
= item
.url().directory(KUrl::AppendTrailingSlash
);
868 const int level
= dir
.count('/') - m_rootExpansionLevel
- 1;
869 data
.insert("expansionLevel", level
);
872 if (item
.isMimeTypeKnown()) {
873 data
.insert("iconName", item
.iconName());
875 if (m_requestRole
[TypeRole
]) {
876 data
.insert("type", item
.mimeComment());
883 bool KFileItemModel::lessThan(const KFileItem
& a
, const KFileItem
& b
) const
887 if (m_rootExpansionLevel
>= 0) {
888 result
= expansionLevelsCompare(a
, b
);
890 // The items have parents with different expansion levels
891 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
895 if (m_sortFoldersFirst
|| m_sortRole
== SizeRole
) {
896 const bool isDirA
= a
.isDir();
897 const bool isDirB
= b
.isDir();
898 if (isDirA
&& !isDirB
) {
900 } else if (!isDirA
&& isDirB
) {
905 switch (m_sortRole
) {
907 result
= stringCompare(a
.text(), b
.text());
909 // KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
910 result
= stringCompare(a
.name(m_caseSensitivity
== Qt::CaseInsensitive
),
911 b
.name(m_caseSensitivity
== Qt::CaseInsensitive
));
917 const KDateTime dateTimeA
= a
.time(KFileItem::ModificationTime
);
918 const KDateTime dateTimeB
= b
.time(KFileItem::ModificationTime
);
919 if (dateTimeA
< dateTimeB
) {
921 } else if (dateTimeA
> dateTimeB
) {
928 // TODO: Implement sorting folders by the number of items inside.
929 // This is more tricky to get right because this number is retrieved
930 // asynchronously by KFileItemModelRolesUpdater.
931 const KIO::filesize_t sizeA
= a
.size();
932 const KIO::filesize_t sizeB
= b
.size();
935 } else if (sizeA
> sizeB
) {
946 // It must be assured that the sort order is always unique even if two values have been
947 // equal. In this case a comparison of the URL is done which is unique in all cases
948 // within KDirLister.
949 result
= QString::compare(a
.url().url(), b
.url().url(), Qt::CaseSensitive
);
952 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
955 void KFileItemModel::sort(const KFileItemList::iterator
& startIterator
, const KFileItemList::iterator
& endIterator
)
957 KFileItemList::iterator start
= startIterator
;
958 KFileItemList::iterator end
= endIterator
;
960 // The implementation is based on qSortHelper() from qalgorithms.h
961 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
962 // In opposite to qSort() it allows to use a member-function for the comparison of elements.
964 int span
= int(end
- start
);
970 KFileItemList::iterator low
= start
, high
= end
- 1;
971 KFileItemList::iterator pivot
= start
+ span
/ 2;
973 if (lessThan(*end
, *start
)) {
980 if (lessThan(*pivot
, *start
)) {
981 qSwap(*pivot
, *start
);
983 if (lessThan(*end
, *pivot
)) {
993 while (low
< high
&& lessThan(*low
, *end
)) {
997 while (high
> low
&& lessThan(*end
, *high
)) {
1009 if (lessThan(*low
, *end
)) {
1021 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
) const
1023 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1024 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1025 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1026 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1028 if (m_caseSensitivity
== Qt::CaseInsensitive
) {
1029 const int result
= m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseInsensitive
)
1030 : QString::compare(a
, b
, Qt::CaseInsensitive
);
1032 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1033 // comparison, still a deterministic sort order is required. A case sensitive
1034 // comparison is done as fallback.
1039 return m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseSensitive
)
1040 : QString::compare(a
, b
, Qt::CaseSensitive
);
1043 int KFileItemModel::expansionLevelsCompare(const KFileItem
& a
, const KFileItem
& b
) const
1045 const KUrl urlA
= a
.url();
1046 const KUrl urlB
= b
.url();
1047 if (urlA
.directory() == urlB
.directory()) {
1048 // Both items have the same directory as parent
1052 // Check whether one item is the parent of the other item
1053 if (urlA
.isParentOf(urlB
)) {
1055 } else if (urlB
.isParentOf(urlA
)) {
1059 // Determine the maximum common path of both items and
1060 // remember the index in 'index'
1061 const QString pathA
= urlA
.path();
1062 const QString pathB
= urlB
.path();
1064 const int maxIndex
= qMin(pathA
.length(), pathB
.length()) - 1;
1066 while (index
<= maxIndex
&& pathA
.at(index
) == pathB
.at(index
)) {
1069 if (index
> maxIndex
) {
1072 while ((pathA
.at(index
) != QLatin1Char('/') || pathB
.at(index
) != QLatin1Char('/')) && index
> 0) {
1076 // Determine the first sub-path after the common path and
1077 // check whether it represents a directory or already a file
1079 const QString subPathA
= subPath(a
, pathA
, index
, &isDirA
);
1081 const QString subPathB
= subPath(b
, pathB
, index
, &isDirB
);
1083 if (isDirA
&& !isDirB
) {
1085 } else if (!isDirA
&& isDirB
) {
1089 return stringCompare(subPathA
, subPathB
);
1092 QString
KFileItemModel::subPath(const KFileItem
& item
,
1093 const QString
& itemPath
,
1098 const int pathIndex
= itemPath
.indexOf('/', start
+ 1);
1099 *isDir
= (pathIndex
> 0) || item
.isDir();
1100 return itemPath
.mid(start
, pathIndex
- start
);
1103 bool KFileItemModel::useMaximumUpdateInterval() const
1105 const KDirLister
* dirLister
= m_dirLister
.data();
1106 return dirLister
&& !dirLister
->url().isLocalFile();
1109 #include "kfileitemmodel.moc"