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_rootExpansionLevel(-1)
51 m_requestRole
[NameRole
] = true;
52 m_requestRole
[IsDirRole
] = true;
56 connect(dirLister
, SIGNAL(canceled()), this, SLOT(slotCanceled()));
57 connect(dirLister
, SIGNAL(completed()), this, SLOT(slotCompleted()));
58 connect(dirLister
, SIGNAL(newItems(KFileItemList
)), this, SLOT(slotNewItems(KFileItemList
)));
59 connect(dirLister
, SIGNAL(itemsDeleted(KFileItemList
)), this, SLOT(slotItemsDeleted(KFileItemList
)));
60 connect(dirLister
, SIGNAL(refreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)), this, SLOT(slotRefreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)));
61 connect(dirLister
, SIGNAL(clear()), this, SLOT(slotClear()));
62 connect(dirLister
, SIGNAL(clear(KUrl
)), this, SLOT(slotClear(KUrl
)));
64 // Although the layout engine of KItemListView is fast it is very inefficient to e.g.
65 // emit 50 itemsInserted()-signals each 100 ms. m_minimumUpdateIntervalTimer assures that updates
66 // are done in 1 second intervals for equal operations.
67 m_minimumUpdateIntervalTimer
= new QTimer(this);
68 m_minimumUpdateIntervalTimer
->setInterval(1000);
69 m_minimumUpdateIntervalTimer
->setSingleShot(true);
70 connect(m_minimumUpdateIntervalTimer
, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
72 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
73 // before the completed() or canceled() signal has been emitted.
74 m_maximumUpdateIntervalTimer
= new QTimer(this);
75 m_maximumUpdateIntervalTimer
->setInterval(2000);
76 m_maximumUpdateIntervalTimer
->setSingleShot(true);
77 connect(m_maximumUpdateIntervalTimer
, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
79 Q_ASSERT(m_minimumUpdateIntervalTimer
->interval() <= m_maximumUpdateIntervalTimer
->interval());
82 KFileItemModel::~KFileItemModel()
86 int KFileItemModel::count() const
88 return m_data
.count();
91 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
93 if (index
>= 0 && index
< count()) {
94 return m_data
.at(index
);
96 return QHash
<QByteArray
, QVariant
>();
99 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
101 if (index
>= 0 && index
< count()) {
102 QHash
<QByteArray
, QVariant
> currentValue
= m_data
.at(index
);
104 QSet
<QByteArray
> changedRoles
;
105 QHashIterator
<QByteArray
, QVariant
> it(values
);
106 while (it
.hasNext()) {
108 const QByteArray role
= it
.key();
109 const QVariant value
= it
.value();
111 if (currentValue
[role
] != value
) {
112 currentValue
[role
] = value
;
113 changedRoles
.insert(role
);
117 if (!changedRoles
.isEmpty()) {
118 m_data
[index
] = currentValue
;
119 emit
itemsChanged(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
127 bool KFileItemModel::supportsGrouping() const
132 bool KFileItemModel::supportsSorting() const
137 QMimeData
* KFileItemModel::createMimeData(const QSet
<int>& indexes
) const
139 QMimeData
* data
= new QMimeData();
141 // The following code has been taken from KDirModel::mimeData()
142 // (kdelibs/kio/kio/kdirmodel.cpp)
143 // Copyright (C) 2006 David Faure <faure@kde.org>
145 KUrl::List mostLocalUrls
;
146 bool canUseMostLocalUrls
= true;
148 QSetIterator
<int> it(indexes
);
149 while (it
.hasNext()) {
150 const int index
= it
.next();
151 const KFileItem item
= fileItem(index
);
152 if (!item
.isNull()) {
156 mostLocalUrls
<< item
.mostLocalUrl(isLocal
);
158 canUseMostLocalUrls
= false;
163 const bool different
= canUseMostLocalUrls
&& mostLocalUrls
!= urls
;
164 urls
= KDirModel::simplifiedUrlList(urls
); // TODO: Check if we still need KDirModel for this in KDE 5.0
166 mostLocalUrls
= KDirModel::simplifiedUrlList(mostLocalUrls
);
167 urls
.populateMimeData(mostLocalUrls
, data
);
169 urls
.populateMimeData(data
);
175 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
177 startFromIndex
= qMax(0, startFromIndex
);
178 for (int i
= startFromIndex
; i
< count(); i
++) {
179 if (data(i
)["name"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
180 kDebug() << data(i
)["name"].toString();
184 for (int i
= 0; i
< startFromIndex
; i
++) {
185 if (data(i
)["name"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
186 kDebug() << data(i
)["name"].toString();
193 bool KFileItemModel::supportsDropping(int index
) const
195 const KFileItem item
= fileItem(index
);
196 return item
.isNull() ? false : item
.isDir();
199 KFileItem
KFileItemModel::fileItem(int index
) const
201 if (index
>= 0 && index
< count()) {
202 return m_sortedItems
.at(index
);
208 KFileItem
KFileItemModel::fileItem(const KUrl
& url
) const
210 const int index
= m_items
.value(url
, -1);
212 return m_sortedItems
.at(index
);
217 int KFileItemModel::index(const KFileItem
& item
) const
223 return m_items
.value(item
.url(), -1);
226 KFileItem
KFileItemModel::rootItem() const
228 const KDirLister
* dirLister
= m_dirLister
.data();
230 return dirLister
->rootItem();
235 void KFileItemModel::clear()
240 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
243 const bool supportedExpanding
= m_requestRole
[IsExpandedRole
] && m_requestRole
[ExpansionLevelRole
];
244 const bool willSupportExpanding
= roles
.contains("isExpanded") && roles
.contains("expansionLevel");
245 if (supportedExpanding
&& !willSupportExpanding
) {
246 // No expanding is supported anymore. Take care to delete all items that have an expansion level
247 // that is not 0 (and hence are part of an expanded item).
248 removeExpandedItems();
253 QSetIterator
<QByteArray
> it(roles
);
254 while (it
.hasNext()) {
255 const QByteArray
& role
= it
.next();
256 m_requestRole
[roleIndex(role
)] = true;
260 // Update m_data with the changed requested roles
261 const int maxIndex
= count() - 1;
262 for (int i
= 0; i
<= maxIndex
; ++i
) {
263 m_data
[i
] = retrieveData(m_sortedItems
.at(i
));
266 kWarning() << "TODO: Emitting itemsChanged() with no information what has changed!";
267 emit
itemsChanged(KItemRangeList() << KItemRange(0, count()), QSet
<QByteArray
>());
271 QSet
<QByteArray
> KFileItemModel::roles() const
273 QSet
<QByteArray
> roles
;
274 for (int i
= 0; i
< RolesCount
; ++i
) {
275 if (m_requestRole
[i
]) {
278 case NameRole
: roles
.insert("name"); break;
279 case SizeRole
: roles
.insert("size"); break;
280 case DateRole
: roles
.insert("date"); break;
281 case PermissionsRole
: roles
.insert("permissions"); break;
282 case OwnerRole
: roles
.insert("owner"); break;
283 case GroupRole
: roles
.insert("group"); break;
284 case TypeRole
: roles
.insert("type"); break;
285 case DestinationRole
: roles
.insert("destination"); break;
286 case PathRole
: roles
.insert("path"); break;
287 case IsDirRole
: roles
.insert("isDir"); break;
288 case IsExpandedRole
: roles
.insert("isExpanded"); break;
289 case ExpansionLevelRole
: roles
.insert("expansionLevel"); break;
290 default: Q_ASSERT(false); break;
297 bool KFileItemModel::setExpanded(int index
, bool expanded
)
299 if (isExpanded(index
) == expanded
|| index
< 0 || index
>= count()) {
303 QHash
<QByteArray
, QVariant
> values
;
304 values
.insert("isExpanded", expanded
);
305 if (!setData(index
, values
)) {
310 const KUrl url
= m_sortedItems
.at(index
).url();
311 KDirLister
* dirLister
= m_dirLister
.data();
313 dirLister
->openUrl(url
, KDirLister::Keep
);
317 KFileItemList itemsToRemove
;
318 const int expansionLevel
= data(index
)["expansionLevel"].toInt();
320 while (index
< count() && data(index
)["expansionLevel"].toInt() > expansionLevel
) {
321 itemsToRemove
.append(m_sortedItems
.at(index
));
324 removeItems(itemsToRemove
);
331 bool KFileItemModel::isExpanded(int index
) const
333 if (index
>= 0 && index
< count()) {
334 return m_data
.at(index
).value("isExpanded").toBool();
339 bool KFileItemModel::isExpandable(int index
) const
341 if (index
>= 0 && index
< count()) {
342 return m_sortedItems
.at(index
).isDir();
347 void KFileItemModel::onGroupRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
350 m_groupRole
= roleIndex(current
);
353 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
356 const int itemCount
= count();
357 if (itemCount
<= 0) {
361 m_sortRole
= roleIndex(current
);
363 KFileItemList sortedItems
= m_sortedItems
;
364 m_sortedItems
.clear();
367 emit
itemsRemoved(KItemRangeList() << KItemRange(0, itemCount
));
369 sort(sortedItems
.begin(), sortedItems
.end());
371 foreach (const KFileItem
& item
, sortedItems
) {
372 m_sortedItems
.append(item
);
373 m_items
.insert(item
.url(), index
);
374 m_data
.append(retrieveData(item
));
379 emit
itemsInserted(KItemRangeList() << KItemRange(0, itemCount
));
382 void KFileItemModel::slotCompleted()
384 if (m_minimumUpdateIntervalTimer
->isActive()) {
385 // dispatchPendingItems() will be called when the timer
390 dispatchPendingItemsToInsert();
391 m_minimumUpdateIntervalTimer
->start();
394 void KFileItemModel::slotCanceled()
396 m_minimumUpdateIntervalTimer
->stop();
397 m_maximumUpdateIntervalTimer
->stop();
398 dispatchPendingItemsToInsert();
401 void KFileItemModel::slotNewItems(const KFileItemList
& items
)
403 m_pendingItemsToInsert
.append(items
);
405 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer
->isActive()) {
406 // Assure that items get dispatched if no completed() or canceled() signal is
407 // emitted during the maximum update interval.
408 m_maximumUpdateIntervalTimer
->start();
412 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
414 if (!m_pendingItemsToInsert
.isEmpty()) {
415 insertItems(m_pendingItemsToInsert
);
416 m_pendingItemsToInsert
.clear();
421 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
423 Q_ASSERT(!items
.isEmpty());
424 #ifdef KFILEITEMMODEL_DEBUG
425 kDebug() << "Refreshing" << items
.count() << "items";
428 // Get the indexes of all items that have been refreshed
430 indexes
.reserve(items
.count());
432 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
433 while (it
.hasNext()) {
434 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
435 const int index
= m_items
.value(itemPair
.second
.url(), -1);
437 indexes
.append(index
);
441 // If the changed items have been created recently, they might not be in m_items yet.
442 // In that case, the list 'indexes' might be empty.
443 if (indexes
.isEmpty()) {
447 // Extract the item-ranges out of the changed indexes
450 KItemRangeList itemRangeList
;
453 int previousIndex
= indexes
.at(0);
455 const int maxIndex
= indexes
.count() - 1;
456 for (int i
= 1; i
<= maxIndex
; ++i
) {
457 const int currentIndex
= indexes
.at(i
);
458 if (currentIndex
== previousIndex
+ 1) {
461 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
463 rangeIndex
= currentIndex
;
466 previousIndex
= currentIndex
;
469 if (rangeCount
> 0) {
470 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
473 emit
itemsChanged(itemRangeList
, QSet
<QByteArray
>());
476 void KFileItemModel::slotClear()
478 #ifdef KFILEITEMMODEL_DEBUG
479 kDebug() << "Clearing all items";
482 m_minimumUpdateIntervalTimer
->stop();
483 m_maximumUpdateIntervalTimer
->stop();
484 m_pendingItemsToInsert
.clear();
486 m_rootExpansionLevel
= -1;
488 const int removedCount
= m_data
.count();
489 if (removedCount
> 0) {
490 m_sortedItems
.clear();
493 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
497 void KFileItemModel::slotClear(const KUrl
& url
)
502 void KFileItemModel::dispatchPendingItemsToInsert()
504 if (!m_pendingItemsToInsert
.isEmpty()) {
505 insertItems(m_pendingItemsToInsert
);
506 m_pendingItemsToInsert
.clear();
510 void KFileItemModel::insertItems(const KFileItemList
& items
)
512 if (items
.isEmpty()) {
516 #ifdef KFILEITEMMODEL_DEBUG
519 kDebug() << "===========================================================";
520 kDebug() << "Inserting" << items
.count() << "items";
523 KFileItemList sortedItems
= items
;
524 sort(sortedItems
.begin(), sortedItems
.end());
526 #ifdef KFILEITEMMODEL_DEBUG
527 kDebug() << "[TIME] Sorting:" << timer
.elapsed();
530 KItemRangeList itemRanges
;
533 int insertedAtIndex
= -1; // Index for the current item-range
534 int insertedCount
= 0; // Count for the current item-range
535 int previouslyInsertedCount
= 0; // Sum of previously inserted items for all ranges
536 while (sourceIndex
< sortedItems
.count()) {
537 // Find target index from m_items to insert the current item
539 const int previousTargetIndex
= targetIndex
;
540 while (targetIndex
< m_sortedItems
.count()) {
541 if (!lessThan(m_sortedItems
.at(targetIndex
), sortedItems
.at(sourceIndex
))) {
547 if (targetIndex
- previousTargetIndex
> 0 && insertedAtIndex
>= 0) {
548 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
549 previouslyInsertedCount
+= insertedCount
;
550 insertedAtIndex
= targetIndex
- previouslyInsertedCount
;
554 // Insert item at the position targetIndex
555 const KFileItem item
= sortedItems
.at(sourceIndex
);
556 m_sortedItems
.insert(targetIndex
, item
);
557 m_data
.insert(targetIndex
, retrieveData(item
));
558 // m_items will be inserted after the loop (see comment below)
561 if (insertedAtIndex
< 0) {
562 insertedAtIndex
= targetIndex
;
563 Q_ASSERT(previouslyInsertedCount
== 0);
569 // The indexes of all m_items must be adjusted, not only the index
571 for (int i
= 0; i
< m_sortedItems
.count(); ++i
) {
572 m_items
.insert(m_sortedItems
.at(i
).url(), i
);
575 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
576 emit
itemsInserted(itemRanges
);
578 #ifdef KFILEITEMMODEL_DEBUG
579 kDebug() << "[TIME] Inserting of" << items
.count() << "items:" << timer
.elapsed();
583 void KFileItemModel::removeItems(const KFileItemList
& items
)
585 if (items
.isEmpty()) {
589 #ifdef KFILEITEMMODEL_DEBUG
590 kDebug() << "Removing " << items
.count() << "items";
593 KFileItemList sortedItems
= items
;
594 sort(sortedItems
.begin(), sortedItems
.end());
596 QList
<int> indexesToRemove
;
597 indexesToRemove
.reserve(items
.count());
599 // Calculate the item ranges that will get deleted
600 KItemRangeList itemRanges
;
601 int removedAtIndex
= -1;
602 int removedCount
= 0;
604 foreach (const KFileItem
& itemToRemove
, sortedItems
) {
605 const int previousTargetIndex
= targetIndex
;
606 while (targetIndex
< m_sortedItems
.count()) {
607 if (m_sortedItems
.at(targetIndex
).url() == itemToRemove
.url()) {
612 if (targetIndex
>= m_sortedItems
.count()) {
613 kWarning() << "Item that should be deleted has not been found!";
617 if (targetIndex
- previousTargetIndex
> 0 && removedAtIndex
>= 0) {
618 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
619 removedAtIndex
= targetIndex
;
623 indexesToRemove
.append(targetIndex
);
624 if (removedAtIndex
< 0) {
625 removedAtIndex
= targetIndex
;
632 for (int i
= indexesToRemove
.count() - 1; i
>= 0; --i
) {
633 const int indexToRemove
= indexesToRemove
.at(i
);
634 m_items
.remove(m_sortedItems
.at(indexToRemove
).url());
635 m_sortedItems
.removeAt(indexToRemove
);
636 m_data
.removeAt(indexToRemove
);
639 // The indexes of all m_items must be adjusted, not only the index
640 // of the removed items
641 for (int i
= 0; i
< m_sortedItems
.count(); ++i
) {
642 m_items
.insert(m_sortedItems
.at(i
).url(), i
);
646 m_rootExpansionLevel
= -1;
649 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
650 emit
itemsRemoved(itemRanges
);
653 void KFileItemModel::removeExpandedItems()
656 KFileItemList expandedItems
;
658 const int maxIndex
= m_data
.count() - 1;
659 for (int i
= 0; i
<= maxIndex
; ++i
) {
660 if (m_data
.at(i
).value("expansionLevel").toInt() > 0) {
661 const KFileItem fileItem
= m_sortedItems
.at(i
);
662 expandedItems
.append(fileItem
);
666 // The m_rootExpansionLevel may not get reset before all items with
667 // a bigger expansionLevel have been removed.
668 Q_ASSERT(m_rootExpansionLevel
>= 0);
669 removeItems(expandedItems
);
671 m_rootExpansionLevel
= -1;
674 void KFileItemModel::resetRoles()
676 for (int i
= 0; i
< RolesCount
; ++i
) {
677 m_requestRole
[i
] = false;
681 KFileItemModel::Role
KFileItemModel::roleIndex(const QByteArray
& role
) const
683 static QHash
<QByteArray
, Role
> rolesHash
;
684 if (rolesHash
.isEmpty()) {
685 rolesHash
.insert("name", NameRole
);
686 rolesHash
.insert("size", SizeRole
);
687 rolesHash
.insert("date", DateRole
);
688 rolesHash
.insert("permissions", PermissionsRole
);
689 rolesHash
.insert("owner", OwnerRole
);
690 rolesHash
.insert("group", GroupRole
);
691 rolesHash
.insert("type", TypeRole
);
692 rolesHash
.insert("destination", DestinationRole
);
693 rolesHash
.insert("path", PathRole
);
694 rolesHash
.insert("isDir", IsDirRole
);
695 rolesHash
.insert("isExpanded", IsExpandedRole
);
696 rolesHash
.insert("expansionLevel", ExpansionLevelRole
);
698 return rolesHash
.value(role
, NoRole
);
701 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
) const
703 // It is important to insert only roles that are fast to retrieve. E.g.
704 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
705 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
706 QHash
<QByteArray
, QVariant
> data
;
707 data
.insert("iconPixmap", QPixmap());
709 const bool isDir
= item
.isDir();
710 if (m_requestRole
[IsDirRole
]) {
711 data
.insert("isDir", isDir
);
714 if (m_requestRole
[NameRole
]) {
715 data
.insert("name", item
.name());
718 if (m_requestRole
[SizeRole
]) {
720 data
.insert("size", QVariant());
722 data
.insert("size", item
.size());
726 if (m_requestRole
[DateRole
]) {
727 // Don't use KFileItem::timeString() as this is too expensive when
728 // having several thousands of items. Instead the formatting of the
729 // date-time will be done on-demand by the view when the date will be shown.
730 const KDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
731 data
.insert("date", dateTime
.dateTime());
734 if (m_requestRole
[PermissionsRole
]) {
735 data
.insert("permissions", item
.permissionsString());
738 if (m_requestRole
[OwnerRole
]) {
739 data
.insert("owner", item
.user());
742 if (m_requestRole
[GroupRole
]) {
743 data
.insert("group", item
.group());
746 if (m_requestRole
[DestinationRole
]) {
747 QString destination
= item
.linkDest();
748 if (destination
.isEmpty()) {
749 destination
= i18nc("@item:intable", "No destination");
751 data
.insert("destination", destination
);
754 if (m_requestRole
[PathRole
]) {
755 data
.insert("path", item
.localPath());
758 if (m_requestRole
[IsExpandedRole
]) {
759 data
.insert("isExpanded", false);
762 if (m_requestRole
[ExpansionLevelRole
]) {
763 if (m_rootExpansionLevel
< 0) {
764 KDirLister
* dirLister
= m_dirLister
.data();
766 const QString rootDir
= dirLister
->url().directory(KUrl::AppendTrailingSlash
);
767 m_rootExpansionLevel
= rootDir
.count('/');
770 const QString dir
= item
.url().directory(KUrl::AppendTrailingSlash
);
771 const int level
= dir
.count('/') - m_rootExpansionLevel
- 1;
772 data
.insert("expansionLevel", level
);
775 if (item
.isMimeTypeKnown()) {
776 data
.insert("iconName", item
.iconName());
778 if (m_requestRole
[TypeRole
]) {
779 data
.insert("type", item
.mimeComment());
786 bool KFileItemModel::lessThan(const KFileItem
& a
, const KFileItem
& b
) const
790 if (m_rootExpansionLevel
>= 0) {
791 result
= expansionLevelsCompare(a
, b
);
793 // The items have parents with different expansion levels
798 if (m_sortFoldersFirst
) {
799 const bool isDirA
= a
.isDir();
800 const bool isDirB
= b
.isDir();
801 if (isDirA
&& !isDirB
) {
803 } else if (!isDirA
&& isDirB
) {
808 switch (m_sortRole
) {
810 result
= stringCompare(a
.text(), b
.text());
812 // KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
813 result
= stringCompare(a
.name(m_caseSensitivity
== Qt::CaseInsensitive
),
814 b
.name(m_caseSensitivity
== Qt::CaseInsensitive
));
820 const KDateTime dateTimeA
= a
.time(KFileItem::ModificationTime
);
821 const KDateTime dateTimeB
= b
.time(KFileItem::ModificationTime
);
822 if (dateTimeA
< dateTimeB
) {
824 } else if (dateTimeA
> dateTimeB
) {
835 // It must be assured that the sort order is always unique even if two values have been
836 // equal. In this case a comparison of the URL is done which is unique in all cases
837 // within KDirLister.
838 result
= QString::compare(a
.url().url(), b
.url().url(), Qt::CaseSensitive
);
844 void KFileItemModel::sort(const KFileItemList::iterator
& startIterator
, const KFileItemList::iterator
& endIterator
)
846 KFileItemList::iterator start
= startIterator
;
847 KFileItemList::iterator end
= endIterator
;
849 // The implementation is based on qSortHelper() from qalgorithms.h
850 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
851 // In opposite to qSort() it allows to use a member-function for the comparison of elements.
853 int span
= int(end
- start
);
859 KFileItemList::iterator low
= start
, high
= end
- 1;
860 KFileItemList::iterator pivot
= start
+ span
/ 2;
862 if (lessThan(*end
, *start
)) {
869 if (lessThan(*pivot
, *start
)) {
870 qSwap(*pivot
, *start
);
872 if (lessThan(*end
, *pivot
)) {
882 while (low
< high
&& lessThan(*low
, *end
)) {
886 while (high
> low
&& lessThan(*end
, *high
)) {
898 if (lessThan(*low
, *end
)) {
910 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
) const
912 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
913 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
914 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
915 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
917 if (m_caseSensitivity
== Qt::CaseInsensitive
) {
918 const int result
= m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseInsensitive
)
919 : QString::compare(a
, b
, Qt::CaseInsensitive
);
921 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
922 // comparison, still a deterministic sort order is required. A case sensitive
923 // comparison is done as fallback.
928 return m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseSensitive
)
929 : QString::compare(a
, b
, Qt::CaseSensitive
);
932 int KFileItemModel::expansionLevelsCompare(const KFileItem
& a
, const KFileItem
& b
) const
934 const KUrl urlA
= a
.url();
935 const KUrl urlB
= b
.url();
936 if (urlA
.directory() == urlB
.directory()) {
937 // Both items have the same directory as parent
941 // Check whether one item is the parent of the other item
942 if (urlA
.isParentOf(urlB
)) {
944 } else if (urlB
.isParentOf(urlA
)) {
948 // Determine the maximum common path of both items and
949 // remember the index in 'index'
950 const QString pathA
= urlA
.path();
951 const QString pathB
= urlB
.path();
953 const int maxIndex
= qMin(pathA
.length(), pathB
.length()) - 1;
955 while (index
<= maxIndex
&& pathA
.at(index
) == pathB
.at(index
)) {
958 if (index
> maxIndex
) {
961 while ((pathA
.at(index
) != QLatin1Char('/') || pathB
.at(index
) != QLatin1Char('/')) && index
> 0) {
965 // Determine the first sub-path after the common path and
966 // check whether it represents a directory or already a file
968 const QString subPathA
= subPath(a
, pathA
, index
, &isDirA
);
970 const QString subPathB
= subPath(b
, pathB
, index
, &isDirB
);
972 if (isDirA
&& !isDirB
) {
974 } else if (!isDirA
&& isDirB
) {
978 return stringCompare(subPathA
, subPathB
);
981 QString
KFileItemModel::subPath(const KFileItem
& item
,
982 const QString
& itemPath
,
987 const int pathIndex
= itemPath
.indexOf('/', start
+ 1);
988 *isDir
= (pathIndex
> 0) || item
.isDir();
989 return itemPath
.mid(start
, pathIndex
- start
);
992 bool KFileItemModel::useMaximumUpdateInterval() const
994 const KDirLister
* dirLister
= m_dirLister
.data();
995 return dirLister
&& !dirLister
->url().isLocalFile();
998 #include "kfileitemmodel.moc"