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
= genericStringRoleGroups("owner"); break;
240 case GroupRole
: m_groups
= genericStringRoleGroups("group"); break;
241 case TypeRole
: m_groups
= genericStringRoleGroups("type"); break;
242 case DestinationRole
: m_groups
= genericStringRoleGroups("destination"); break;
243 case PathRole
: m_groups
= genericStringRoleGroups("path"); 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) {
765 const KFileItemList oldSortedItems
= m_sortedItems
;
766 const QHash
<KUrl
, int> oldItems
= m_items
;
767 const QList
<QHash
<QByteArray
, QVariant
> > oldData
= m_data
;
773 sort(m_sortedItems
.begin(), m_sortedItems
.end());
775 foreach (const KFileItem
& item
, m_sortedItems
) {
776 m_items
.insert(item
.url(), index
);
778 const int oldItemIndex
= oldItems
.value(item
.url());
779 m_data
.append(oldData
.at(oldItemIndex
));
784 bool emitItemsMoved
= false;
785 QList
<int> movedToIndexes
;
786 movedToIndexes
.reserve(m_sortedItems
.count());
787 for (int i
= 0; i
< itemCount
; i
++) {
788 const int newIndex
= m_items
.value(oldSortedItems
.at(i
).url());
789 movedToIndexes
.append(newIndex
);
790 if (!emitItemsMoved
&& newIndex
!= i
) {
791 emitItemsMoved
= true;
795 if (emitItemsMoved
) {
796 emit
itemsMoved(KItemRange(0, itemCount
), movedToIndexes
);
800 void KFileItemModel::removeExpandedItems()
802 KFileItemList expandedItems
;
804 const int maxIndex
= m_data
.count() - 1;
805 for (int i
= 0; i
<= maxIndex
; ++i
) {
806 if (m_data
.at(i
).value("expansionLevel").toInt() > 0) {
807 const KFileItem fileItem
= m_sortedItems
.at(i
);
808 expandedItems
.append(fileItem
);
812 // The m_rootExpansionLevel may not get reset before all items with
813 // a bigger expansionLevel have been removed.
814 Q_ASSERT(m_rootExpansionLevel
>= 0);
815 removeItems(expandedItems
);
817 m_rootExpansionLevel
= -1;
818 m_expandedUrls
.clear();
821 void KFileItemModel::resetRoles()
823 for (int i
= 0; i
< RolesCount
; ++i
) {
824 m_requestRole
[i
] = false;
828 KFileItemModel::Role
KFileItemModel::roleIndex(const QByteArray
& role
) const
830 static QHash
<QByteArray
, Role
> rolesHash
;
831 if (rolesHash
.isEmpty()) {
832 rolesHash
.insert("name", NameRole
);
833 rolesHash
.insert("size", SizeRole
);
834 rolesHash
.insert("date", DateRole
);
835 rolesHash
.insert("permissions", PermissionsRole
);
836 rolesHash
.insert("owner", OwnerRole
);
837 rolesHash
.insert("group", GroupRole
);
838 rolesHash
.insert("type", TypeRole
);
839 rolesHash
.insert("destination", DestinationRole
);
840 rolesHash
.insert("path", PathRole
);
841 rolesHash
.insert("isDir", IsDirRole
);
842 rolesHash
.insert("isExpanded", IsExpandedRole
);
843 rolesHash
.insert("expansionLevel", ExpansionLevelRole
);
845 return rolesHash
.value(role
, NoRole
);
848 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
) const
850 // It is important to insert only roles that are fast to retrieve. E.g.
851 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
852 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
853 QHash
<QByteArray
, QVariant
> data
;
854 data
.insert("iconPixmap", QPixmap());
856 const bool isDir
= item
.isDir();
857 if (m_requestRole
[IsDirRole
]) {
858 data
.insert("isDir", isDir
);
861 if (m_requestRole
[NameRole
]) {
862 data
.insert("name", item
.name());
865 if (m_requestRole
[SizeRole
]) {
867 data
.insert("size", QVariant());
869 data
.insert("size", item
.size());
873 if (m_requestRole
[DateRole
]) {
874 // Don't use KFileItem::timeString() as this is too expensive when
875 // having several thousands of items. Instead the formatting of the
876 // date-time will be done on-demand by the view when the date will be shown.
877 const KDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
878 data
.insert("date", dateTime
.dateTime());
881 if (m_requestRole
[PermissionsRole
]) {
882 data
.insert("permissions", item
.permissionsString());
885 if (m_requestRole
[OwnerRole
]) {
886 data
.insert("owner", item
.user());
889 if (m_requestRole
[GroupRole
]) {
890 data
.insert("group", item
.group());
893 if (m_requestRole
[DestinationRole
]) {
894 QString destination
= item
.linkDest();
895 if (destination
.isEmpty()) {
896 destination
= i18nc("@item:intable", "No destination");
898 data
.insert("destination", destination
);
901 if (m_requestRole
[PathRole
]) {
902 data
.insert("path", item
.localPath());
905 if (m_requestRole
[IsExpandedRole
]) {
906 data
.insert("isExpanded", false);
909 if (m_requestRole
[ExpansionLevelRole
]) {
910 if (m_rootExpansionLevel
< 0) {
911 KDirLister
* dirLister
= m_dirLister
.data();
913 const QString rootDir
= dirLister
->url().directory(KUrl::AppendTrailingSlash
);
914 m_rootExpansionLevel
= rootDir
.count('/');
917 const QString dir
= item
.url().directory(KUrl::AppendTrailingSlash
);
918 const int level
= dir
.count('/') - m_rootExpansionLevel
- 1;
919 data
.insert("expansionLevel", level
);
922 if (item
.isMimeTypeKnown()) {
923 data
.insert("iconName", item
.iconName());
925 if (m_requestRole
[TypeRole
]) {
926 data
.insert("type", item
.mimeComment());
933 bool KFileItemModel::lessThan(const KFileItem
& a
, const KFileItem
& b
) const
937 if (m_rootExpansionLevel
>= 0) {
938 result
= expansionLevelsCompare(a
, b
);
940 // The items have parents with different expansion levels
941 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
945 if (m_sortFoldersFirst
|| m_sortRole
== SizeRole
) {
946 const bool isDirA
= a
.isDir();
947 const bool isDirB
= b
.isDir();
948 if (isDirA
&& !isDirB
) {
950 } else if (!isDirA
&& isDirB
) {
955 switch (m_sortRole
) {
957 result
= stringCompare(a
.text(), b
.text());
959 // KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
960 result
= stringCompare(a
.name(m_caseSensitivity
== Qt::CaseInsensitive
),
961 b
.name(m_caseSensitivity
== Qt::CaseInsensitive
));
967 const KDateTime dateTimeA
= a
.time(KFileItem::ModificationTime
);
968 const KDateTime dateTimeB
= b
.time(KFileItem::ModificationTime
);
969 if (dateTimeA
< dateTimeB
) {
971 } else if (dateTimeA
> dateTimeB
) {
978 // TODO: Implement sorting folders by the number of items inside.
979 // This is more tricky to get right because this number is retrieved
980 // asynchronously by KFileItemModelRolesUpdater.
981 const KIO::filesize_t sizeA
= a
.size();
982 const KIO::filesize_t sizeB
= b
.size();
985 } else if (sizeA
> sizeB
) {
996 // It must be assured that the sort order is always unique even if two values have been
997 // equal. In this case a comparison of the URL is done which is unique in all cases
998 // within KDirLister.
999 result
= QString::compare(a
.url().url(), b
.url().url(), Qt::CaseSensitive
);
1002 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1005 void KFileItemModel::sort(const KFileItemList::iterator
& startIterator
, const KFileItemList::iterator
& endIterator
)
1007 KFileItemList::iterator start
= startIterator
;
1008 KFileItemList::iterator end
= endIterator
;
1010 // The implementation is based on qSortHelper() from qalgorithms.h
1011 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1012 // In opposite to qSort() it allows to use a member-function for the comparison of elements.
1014 int span
= int(end
- start
);
1020 KFileItemList::iterator low
= start
, high
= end
- 1;
1021 KFileItemList::iterator pivot
= start
+ span
/ 2;
1023 if (lessThan(*end
, *start
)) {
1024 qSwap(*end
, *start
);
1030 if (lessThan(*pivot
, *start
)) {
1031 qSwap(*pivot
, *start
);
1033 if (lessThan(*end
, *pivot
)) {
1034 qSwap(*end
, *pivot
);
1040 qSwap(*pivot
, *end
);
1042 while (low
< high
) {
1043 while (low
< high
&& lessThan(*low
, *end
)) {
1047 while (high
> low
&& lessThan(*end
, *high
)) {
1059 if (lessThan(*low
, *end
)) {
1071 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
) const
1073 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1074 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1075 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1076 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1078 if (m_caseSensitivity
== Qt::CaseInsensitive
) {
1079 const int result
= m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseInsensitive
)
1080 : QString::compare(a
, b
, Qt::CaseInsensitive
);
1082 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1083 // comparison, still a deterministic sort order is required. A case sensitive
1084 // comparison is done as fallback.
1089 return m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseSensitive
)
1090 : QString::compare(a
, b
, Qt::CaseSensitive
);
1093 int KFileItemModel::expansionLevelsCompare(const KFileItem
& a
, const KFileItem
& b
) const
1095 const KUrl urlA
= a
.url();
1096 const KUrl urlB
= b
.url();
1097 if (urlA
.directory() == urlB
.directory()) {
1098 // Both items have the same directory as parent
1102 // Check whether one item is the parent of the other item
1103 if (urlA
.isParentOf(urlB
)) {
1105 } else if (urlB
.isParentOf(urlA
)) {
1109 // Determine the maximum common path of both items and
1110 // remember the index in 'index'
1111 const QString pathA
= urlA
.path();
1112 const QString pathB
= urlB
.path();
1114 const int maxIndex
= qMin(pathA
.length(), pathB
.length()) - 1;
1116 while (index
<= maxIndex
&& pathA
.at(index
) == pathB
.at(index
)) {
1119 if (index
> maxIndex
) {
1122 while ((pathA
.at(index
) != QLatin1Char('/') || pathB
.at(index
) != QLatin1Char('/')) && index
> 0) {
1126 // Determine the first sub-path after the common path and
1127 // check whether it represents a directory or already a file
1129 const QString subPathA
= subPath(a
, pathA
, index
, &isDirA
);
1131 const QString subPathB
= subPath(b
, pathB
, index
, &isDirB
);
1133 if (isDirA
&& !isDirB
) {
1135 } else if (!isDirA
&& isDirB
) {
1139 return stringCompare(subPathA
, subPathB
);
1142 QString
KFileItemModel::subPath(const KFileItem
& item
,
1143 const QString
& itemPath
,
1148 const int pathIndex
= itemPath
.indexOf('/', start
+ 1);
1149 *isDir
= (pathIndex
> 0) || item
.isDir();
1150 return itemPath
.mid(start
, pathIndex
- start
);
1153 bool KFileItemModel::useMaximumUpdateInterval() const
1155 const KDirLister
* dirLister
= m_dirLister
.data();
1156 return dirLister
&& !dirLister
->url().isLocalFile();
1159 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1161 Q_ASSERT(!m_data
.isEmpty());
1163 const int maxIndex
= count() - 1;
1164 QList
<QPair
<int, QVariant
> > groups
;
1168 bool isLetter
= false;
1169 for (int i
= 0; i
<= maxIndex
; ++i
) {
1170 if (isChildItem(i
)) {
1174 const QString name
= m_data
.at(i
).value("name").toString();
1176 // Use the first character of the name as group indication
1177 QChar newFirstChar
= name
.at(0).toUpper();
1178 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1179 newFirstChar
= name
.at(1);
1182 if (firstChar
!= newFirstChar
) {
1183 QString newGroupValue
;
1184 if (newFirstChar
>= QLatin1Char('A') && newFirstChar
<= QLatin1Char('Z')) {
1185 // Apply group 'A' - 'Z'
1186 newGroupValue
= newFirstChar
;
1188 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
1189 // Apply group '0 - 9' for any name that starts with a digit
1190 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
1194 // If the current group is 'A' - 'Z' check whether a locale character
1195 // fits into the existing group.
1196 // TODO: This does not work in the case if e.g. the group 'O' starts with
1197 // an umlaut 'O' -> provide unit-test to document this known issue
1198 const QChar
prevChar(firstChar
.unicode() - ushort(1));
1199 const QChar
nextChar(firstChar
.unicode() + ushort(1));
1200 const QString
currChar(newFirstChar
);
1201 const bool partOfCurrentGroup
= currChar
.localeAwareCompare(prevChar
) > 0 &&
1202 currChar
.localeAwareCompare(nextChar
) < 0;
1203 if (partOfCurrentGroup
) {
1207 newGroupValue
= i18nc("@title:group", "Others");
1211 if (newGroupValue
!= groupValue
) {
1212 groupValue
= newGroupValue
;
1213 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1216 firstChar
= newFirstChar
;
1222 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
1224 Q_ASSERT(!m_data
.isEmpty());
1226 const int maxIndex
= count() - 1;
1227 QList
<QPair
<int, QVariant
> > groups
;
1230 for (int i
= 0; i
<= maxIndex
; ++i
) {
1231 if (isChildItem(i
)) {
1235 const KFileItem
& item
= m_sortedItems
.at(i
);
1236 const KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
1237 QString newGroupValue
;
1238 if (!item
.isNull() && item
.isDir()) {
1239 newGroupValue
= i18nc("@title:group Size", "Folders");
1240 } else if (fileSize
< 5 * 1024 * 1024) {
1241 newGroupValue
= i18nc("@title:group Size", "Small");
1242 } else if (fileSize
< 10 * 1024 * 1024) {
1243 newGroupValue
= i18nc("@title:group Size", "Medium");
1245 newGroupValue
= i18nc("@title:group Size", "Big");
1248 if (newGroupValue
!= groupValue
) {
1249 groupValue
= newGroupValue
;
1250 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1257 QList
<QPair
<int, QVariant
> > KFileItemModel::dateRoleGroups() const
1259 Q_ASSERT(!m_data
.isEmpty());
1261 const int maxIndex
= count() - 1;
1262 QList
<QPair
<int, QVariant
> > groups
;
1264 const QDate currentDate
= KDateTime::currentLocalDateTime().date();
1266 int yearForCurrentWeek
= 0;
1267 int currentWeek
= currentDate
.weekNumber(&yearForCurrentWeek
);
1268 if (yearForCurrentWeek
== currentDate
.year() + 1) {
1272 QDate previousModifiedDate
;
1274 for (int i
= 0; i
<= maxIndex
; ++i
) {
1275 if (isChildItem(i
)) {
1279 const KDateTime modifiedTime
= m_sortedItems
.at(i
).time(KFileItem::ModificationTime
);
1280 const QDate modifiedDate
= modifiedTime
.date();
1281 if (modifiedDate
== previousModifiedDate
) {
1282 // The current item is in the same group as the previous item
1285 previousModifiedDate
= modifiedDate
;
1287 const int daysDistance
= modifiedDate
.daysTo(currentDate
);
1289 int yearForModifiedWeek
= 0;
1290 int modifiedWeek
= modifiedDate
.weekNumber(&yearForModifiedWeek
);
1291 if (yearForModifiedWeek
== modifiedDate
.year() + 1) {
1295 QString newGroupValue
;
1296 if (currentDate
.year() == modifiedDate
.year() && currentDate
.month() == modifiedDate
.month()) {
1297 if (modifiedWeek
> currentWeek
) {
1298 // Usecase: modified date = 2010-01-01, current date = 2010-01-22
1299 // modified week = 53, current week = 3
1302 switch (currentWeek
- modifiedWeek
) {
1304 switch (daysDistance
) {
1305 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
1306 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
1307 default: newGroupValue
= modifiedTime
.toString(i18nc("@title:group The week day name: %A", "%A"));
1311 newGroupValue
= i18nc("@title:group Date", "Last Week");
1314 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
1317 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
1321 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
1327 const QDate lastMonthDate
= currentDate
.addMonths(-1);
1328 if (lastMonthDate
.year() == modifiedDate
.year() && lastMonthDate
.month() == modifiedDate
.month()) {
1329 if (daysDistance
== 1) {
1330 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Yesterday (%B, %Y)"));
1331 } else if (daysDistance
<= 7) {
1332 newGroupValue
= modifiedTime
.toString(i18nc("@title:group The week day name: %A, %B is full month name in current locale, and %Y is full year number", "%A (%B, %Y)"));
1333 } else if (daysDistance
<= 7 * 2) {
1334 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Last Week (%B, %Y)"));
1335 } else if (daysDistance
<= 7 * 3) {
1336 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Two Weeks Ago (%B, %Y)"));
1337 } else if (daysDistance
<= 7 * 4) {
1338 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Three Weeks Ago (%B, %Y)"));
1340 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Earlier on %B, %Y"));
1343 newGroupValue
= modifiedTime
.toString(i18nc("@title:group The month and year: %B is full month name in current locale, and %Y is full year number", "%B, %Y"));
1347 if (newGroupValue
!= groupValue
) {
1348 groupValue
= newGroupValue
;
1349 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1356 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
1358 Q_ASSERT(!m_data
.isEmpty());
1360 const int maxIndex
= count() - 1;
1361 QList
<QPair
<int, QVariant
> > groups
;
1363 QString permissionsString
;
1365 for (int i
= 0; i
<= maxIndex
; ++i
) {
1366 if (isChildItem(i
)) {
1370 const QString newPermissionsString
= m_data
.at(i
).value("permissions").toString();
1371 if (newPermissionsString
== permissionsString
) {
1374 permissionsString
= newPermissionsString
;
1376 const QFileInfo
info(m_sortedItems
.at(i
).url().pathOrUrl());
1380 if (info
.permission(QFile::ReadUser
)) {
1381 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1383 if (info
.permission(QFile::WriteUser
)) {
1384 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1386 if (info
.permission(QFile::ExeUser
)) {
1387 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1389 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
1393 if (info
.permission(QFile::ReadGroup
)) {
1394 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1396 if (info
.permission(QFile::WriteGroup
)) {
1397 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1399 if (info
.permission(QFile::ExeGroup
)) {
1400 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1402 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
1404 // Set others string
1406 if (info
.permission(QFile::ReadOther
)) {
1407 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1409 if (info
.permission(QFile::WriteOther
)) {
1410 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1412 if (info
.permission(QFile::ExeOther
)) {
1413 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1415 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
1417 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
1418 if (newGroupValue
!= groupValue
) {
1419 groupValue
= newGroupValue
;
1420 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1427 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
1429 Q_ASSERT(!m_data
.isEmpty());
1431 const int maxIndex
= count() - 1;
1432 QList
<QPair
<int, QVariant
> > groups
;
1435 for (int i
= 0; i
<= maxIndex
; ++i
) {
1436 if (isChildItem(i
)) {
1439 const QString newGroupValue
= m_data
.at(i
).value(role
).toString();
1440 if (newGroupValue
!= groupValue
) {
1441 groupValue
= newGroupValue
;
1442 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1449 #include "kfileitemmodel.moc"