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),
40 m_caseSensitivity(Qt::CaseInsensitive
),
46 m_minimumUpdateIntervalTimer(0),
47 m_maximumUpdateIntervalTimer(0),
48 m_resortAllItemsTimer(0),
49 m_pendingItemsToInsert(),
50 m_pendingEmitLoadingCompleted(false),
52 m_rootExpansionLevel(-1),
56 // Apply default roles that should be determined
58 m_requestRole
[NameRole
] = true;
59 m_requestRole
[IsDirRole
] = true;
60 m_roles
.insert("name");
61 m_roles
.insert("isDir");
65 connect(dirLister
, SIGNAL(canceled()), this, SLOT(slotCanceled()));
66 connect(dirLister
, SIGNAL(completed()), this, SLOT(slotCompleted()));
67 connect(dirLister
, SIGNAL(newItems(KFileItemList
)), this, SLOT(slotNewItems(KFileItemList
)));
68 connect(dirLister
, SIGNAL(itemsDeleted(KFileItemList
)), this, SLOT(slotItemsDeleted(KFileItemList
)));
69 connect(dirLister
, SIGNAL(refreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)), this, SLOT(slotRefreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)));
70 connect(dirLister
, SIGNAL(clear()), this, SLOT(slotClear()));
71 connect(dirLister
, SIGNAL(clear(KUrl
)), this, SLOT(slotClear(KUrl
)));
73 // Although the layout engine of KItemListView is fast it is very inefficient to e.g.
74 // emit 50 itemsInserted()-signals each 100 ms. m_minimumUpdateIntervalTimer assures that updates
75 // are done in 1 second intervals for equal operations.
76 m_minimumUpdateIntervalTimer
= new QTimer(this);
77 m_minimumUpdateIntervalTimer
->setInterval(1000);
78 m_minimumUpdateIntervalTimer
->setSingleShot(true);
79 connect(m_minimumUpdateIntervalTimer
, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
81 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
82 // before the completed() or canceled() signal has been emitted.
83 m_maximumUpdateIntervalTimer
= new QTimer(this);
84 m_maximumUpdateIntervalTimer
->setInterval(2000);
85 m_maximumUpdateIntervalTimer
->setSingleShot(true);
86 connect(m_maximumUpdateIntervalTimer
, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
88 // When changing the value of an item which represents the sort-role a resorting must be
89 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
90 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
91 // resorting is postponed until the timer has been exceeded.
92 m_resortAllItemsTimer
= new QTimer(this);
93 m_resortAllItemsTimer
->setInterval(500);
94 m_resortAllItemsTimer
->setSingleShot(true);
95 connect(m_resortAllItemsTimer
, SIGNAL(timeout()), this, SLOT(resortAllItems()));
97 Q_ASSERT(m_minimumUpdateIntervalTimer
->interval() <= m_maximumUpdateIntervalTimer
->interval());
100 KFileItemModel::~KFileItemModel()
102 qDeleteAll(m_itemData
);
106 int KFileItemModel::count() const
108 return m_itemData
.count();
111 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
113 if (index
>= 0 && index
< count()) {
114 return m_itemData
.at(index
)->values
;
116 return QHash
<QByteArray
, QVariant
>();
119 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
121 if (index
< 0 || index
>= count()) {
125 QHash
<QByteArray
, QVariant
> currentValues
= m_itemData
.at(index
)->values
;
127 // Determine which roles have been changed
128 QSet
<QByteArray
> changedRoles
;
129 QHashIterator
<QByteArray
, QVariant
> it(values
);
130 while (it
.hasNext()) {
132 const QByteArray role
= it
.key();
133 const QVariant value
= it
.value();
135 if (currentValues
[role
] != value
) {
136 currentValues
[role
] = value
;
137 changedRoles
.insert(role
);
141 if (changedRoles
.isEmpty()) {
145 m_itemData
[index
]->values
= currentValues
;
146 emit
itemsChanged(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
148 if (changedRoles
.contains(sortRole())) {
149 m_resortAllItemsTimer
->start();
155 void KFileItemModel::setSortFoldersFirst(bool foldersFirst
)
157 if (foldersFirst
!= m_sortFoldersFirst
) {
158 m_sortFoldersFirst
= foldersFirst
;
163 bool KFileItemModel::sortFoldersFirst() const
165 return m_sortFoldersFirst
;
168 QMimeData
* KFileItemModel::createMimeData(const QSet
<int>& indexes
) const
170 QMimeData
* data
= new QMimeData();
172 // The following code has been taken from KDirModel::mimeData()
173 // (kdelibs/kio/kio/kdirmodel.cpp)
174 // Copyright (C) 2006 David Faure <faure@kde.org>
176 KUrl::List mostLocalUrls
;
177 bool canUseMostLocalUrls
= true;
179 QSetIterator
<int> it(indexes
);
180 while (it
.hasNext()) {
181 const int index
= it
.next();
182 const KFileItem item
= fileItem(index
);
183 if (!item
.isNull()) {
187 mostLocalUrls
<< item
.mostLocalUrl(isLocal
);
189 canUseMostLocalUrls
= false;
194 const bool different
= canUseMostLocalUrls
&& mostLocalUrls
!= urls
;
195 urls
= KDirModel::simplifiedUrlList(urls
); // TODO: Check if we still need KDirModel for this in KDE 5.0
197 mostLocalUrls
= KDirModel::simplifiedUrlList(mostLocalUrls
);
198 urls
.populateMimeData(mostLocalUrls
, data
);
200 urls
.populateMimeData(data
);
206 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
208 startFromIndex
= qMax(0, startFromIndex
);
209 for (int i
= startFromIndex
; i
< count(); ++i
) {
210 if (data(i
)["name"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
214 for (int i
= 0; i
< startFromIndex
; ++i
) {
215 if (data(i
)["name"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
222 bool KFileItemModel::supportsDropping(int index
) const
224 const KFileItem item
= fileItem(index
);
225 return item
.isNull() ? false : item
.isDir();
228 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
232 switch (roleIndex(role
)) {
233 case NameRole
: descr
= i18nc("@item:intable", "Name"); break;
234 case SizeRole
: descr
= i18nc("@item:intable", "Size"); break;
235 case DateRole
: descr
= i18nc("@item:intable", "Date"); break;
236 case PermissionsRole
: descr
= i18nc("@item:intable", "Permissions"); break;
237 case OwnerRole
: descr
= i18nc("@item:intable", "Owner"); break;
238 case GroupRole
: descr
= i18nc("@item:intable", "Group"); break;
239 case TypeRole
: descr
= i18nc("@item:intable", "Type"); break;
240 case DestinationRole
: descr
= i18nc("@item:intable", "Destination"); break;
241 case PathRole
: descr
= i18nc("@item:intable", "Path"); break;
242 case CommentRole
: descr
= i18nc("@item:intable", "Comment"); break;
243 case TagsRole
: descr
= i18nc("@item:intable", "Tags"); break;
244 case RatingRole
: descr
= i18nc("@item:intable", "Rating"); break;
246 case IsDirRole
: break;
247 case IsExpandedRole
: break;
248 case ExpansionLevelRole
: break;
249 default: Q_ASSERT(false); break;
255 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
257 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
258 #ifdef KFILEITEMMODEL_DEBUG
262 switch (roleIndex(sortRole())) {
263 case NameRole
: m_groups
= nameRoleGroups(); break;
264 case SizeRole
: m_groups
= sizeRoleGroups(); break;
265 case DateRole
: m_groups
= dateRoleGroups(); break;
266 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
267 case OwnerRole
: m_groups
= genericStringRoleGroups("owner"); break;
268 case GroupRole
: m_groups
= genericStringRoleGroups("group"); break;
269 case TypeRole
: m_groups
= genericStringRoleGroups("type"); break;
270 case DestinationRole
: m_groups
= genericStringRoleGroups("destination"); break;
271 case PathRole
: m_groups
= genericStringRoleGroups("path"); break;
272 case CommentRole
: m_groups
= genericStringRoleGroups("comment"); break;
273 case TagsRole
: m_groups
= genericStringRoleGroups("tags"); break;
274 case RatingRole
: m_groups
= ratingRoleGroups(); break;
276 case IsDirRole
: break;
277 case IsExpandedRole
: break;
278 case ExpansionLevelRole
: break;
279 default: Q_ASSERT(false); break;
282 #ifdef KFILEITEMMODEL_DEBUG
283 kDebug() << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
290 KFileItem
KFileItemModel::fileItem(int index
) const
292 if (index
>= 0 && index
< count()) {
293 return m_itemData
.at(index
)->item
;
299 KFileItem
KFileItemModel::fileItem(const KUrl
& url
) const
301 const int index
= m_items
.value(url
, -1);
303 return m_itemData
.at(index
)->item
;
308 int KFileItemModel::index(const KFileItem
& item
) const
314 return m_items
.value(item
.url(), -1);
317 int KFileItemModel::index(const KUrl
& url
) const
319 KUrl urlToFind
= url
;
320 urlToFind
.adjustPath(KUrl::RemoveTrailingSlash
);
321 return m_items
.value(urlToFind
, -1);
324 KFileItem
KFileItemModel::rootItem() const
326 const KDirLister
* dirLister
= m_dirLister
.data();
328 return dirLister
->rootItem();
333 void KFileItemModel::clear()
338 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
343 const bool supportedExpanding
= m_requestRole
[IsExpandedRole
] && m_requestRole
[ExpansionLevelRole
];
344 const bool willSupportExpanding
= roles
.contains("isExpanded") && roles
.contains("expansionLevel");
345 if (supportedExpanding
&& !willSupportExpanding
) {
346 // No expanding is supported anymore. Take care to delete all items that have an expansion level
347 // that is not 0 (and hence are part of an expanded item).
348 removeExpandedItems();
354 QSetIterator
<QByteArray
> it(roles
);
355 while (it
.hasNext()) {
356 const QByteArray
& role
= it
.next();
357 m_requestRole
[roleIndex(role
)] = true;
361 // Update m_data with the changed requested roles
362 const int maxIndex
= count() - 1;
363 for (int i
= 0; i
<= maxIndex
; ++i
) {
364 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
);
367 kWarning() << "TODO: Emitting itemsChanged() with no information what has changed!";
368 emit
itemsChanged(KItemRangeList() << KItemRange(0, count()), QSet
<QByteArray
>());
372 QSet
<QByteArray
> KFileItemModel::roles() const
377 bool KFileItemModel::setExpanded(int index
, bool expanded
)
379 if (isExpanded(index
) == expanded
|| index
< 0 || index
>= count()) {
383 QHash
<QByteArray
, QVariant
> values
;
384 values
.insert("isExpanded", expanded
);
385 if (!setData(index
, values
)) {
389 const KUrl url
= m_itemData
.at(index
)->item
.url();
391 m_expandedUrls
.insert(url
);
393 KDirLister
* dirLister
= m_dirLister
.data();
395 dirLister
->openUrl(url
, KDirLister::Keep
);
399 m_expandedUrls
.remove(url
);
401 KFileItemList itemsToRemove
;
402 const int expansionLevel
= data(index
)["expansionLevel"].toInt();
404 while (index
< count() && data(index
)["expansionLevel"].toInt() > expansionLevel
) {
405 itemsToRemove
.append(m_itemData
.at(index
)->item
);
408 removeItems(itemsToRemove
);
415 bool KFileItemModel::isExpanded(int index
) const
417 if (index
>= 0 && index
< count()) {
418 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
423 bool KFileItemModel::isExpandable(int index
) const
425 if (index
>= 0 && index
< count()) {
426 return m_itemData
.at(index
)->item
.isDir();
431 QSet
<KUrl
> KFileItemModel::expandedUrls() const
433 return m_expandedUrls
;
436 void KFileItemModel::restoreExpandedUrls(const QSet
<KUrl
>& urls
)
438 m_urlsToExpand
= urls
;
441 void KFileItemModel::setExpanded(const QSet
<KUrl
>& urls
)
444 const KDirLister
* dirLister
= m_dirLister
.data();
449 const int pos
= dirLister
->url().url().length();
451 // Assure that each sub-path of the URLs that should be
452 // expanded is added to m_urlsToExpand too. KDirLister
453 // does not care whether the parent-URL has already been
455 QSetIterator
<KUrl
> it1(urls
);
456 while (it1
.hasNext()) {
457 const KUrl
& url
= it1
.next();
459 KUrl urlToExpand
= dirLister
->url();
460 const QStringList subDirs
= url
.url().mid(pos
).split(QDir::separator());
461 for (int i
= 0; i
< subDirs
.count(); ++i
) {
462 urlToExpand
.addPath(subDirs
.at(i
));
463 m_urlsToExpand
.insert(urlToExpand
);
467 // KDirLister::open() must called at least once to trigger an initial
468 // loading. The pending URLs that must be restored are handled
469 // in slotCompleted().
470 QSetIterator
<KUrl
> it2(m_urlsToExpand
);
471 while (it2
.hasNext()) {
472 const int idx
= index(it2
.next());
473 if (idx
>= 0 && !isExpanded(idx
)) {
474 setExpanded(idx
, true);
480 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
482 if (m_nameFilter
!= nameFilter
) {
483 // TODO #1: Assure that expanded items only can get hidden
484 // if no child item is visible
486 // TODO #2: If the user entered a '*' use a regular expression
488 m_nameFilter
= nameFilter
;
490 const QString filter
= nameFilter
.toLower();
492 // Check which shown items from m_itemData must get
493 // hidden and hence moved to m_filteredItems.
494 KFileItemList newFilteredItems
;
496 foreach (ItemData
* itemData
, m_itemData
) {
497 if (!matchesNameFilter(itemData
->item
, filter
)) {
498 m_filteredItems
.append(itemData
->item
);
499 newFilteredItems
.append(itemData
->item
);
503 if (!newFilteredItems
.isEmpty()) {
504 slotItemsDeleted(newFilteredItems
);
507 // Check which hidden items from m_filteredItems should
508 // get visible again and hence removed from m_filteredItems.
509 KFileItemList newVisibleItems
;
511 for (int i
= m_filteredItems
.count() - 1; i
>= 0; --i
) {
512 const KFileItem item
= m_filteredItems
.at(i
);
513 if (matchesNameFilter(item
, filter
)) {
514 newVisibleItems
.append(item
);
515 m_filteredItems
.removeAt(i
);
519 if (!newVisibleItems
.isEmpty()) {
520 slotNewItems(newVisibleItems
);
521 dispatchPendingItemsToInsert();
526 QString
KFileItemModel::nameFilter() const
531 void KFileItemModel::onGroupedSortingChanged(bool current
)
537 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
540 m_sortRole
= roleIndex(current
);
542 #ifdef KFILEITEMMODEL_DEBUG
543 if (!m_requestRole
[m_sortRole
]) {
544 kWarning() << "The sort-role has been changed to a role that has not been received yet";
551 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
558 void KFileItemModel::resortAllItems()
560 m_resortAllItemsTimer
->stop();
562 const int itemCount
= count();
563 if (itemCount
<= 0) {
567 #ifdef KFILEITEMMODEL_DEBUG
570 kDebug() << "===========================================================";
571 kDebug() << "Resorting" << itemCount
<< "items";
574 // Remember the order of the current URLs so
575 // that it can be determined which indexes have
576 // been moved because of the resorting.
578 oldUrls
.reserve(itemCount
);
579 foreach (const ItemData
* itemData
, m_itemData
) {
580 oldUrls
.append(itemData
->item
.url());
587 sort(m_itemData
.begin(), m_itemData
.end());
588 for (int i
= 0; i
< itemCount
; ++i
) {
589 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
592 // Determine the indexes that have been moved
593 bool emitItemsMoved
= false;
594 QList
<int> movedToIndexes
;
595 movedToIndexes
.reserve(itemCount
);
596 for (int i
= 0; i
< itemCount
; i
++) {
597 const int newIndex
= m_items
.value(oldUrls
.at(i
).url());
598 movedToIndexes
.append(newIndex
);
599 if (!emitItemsMoved
&& newIndex
!= i
) {
600 emitItemsMoved
= true;
604 if (emitItemsMoved
) {
605 emit
itemsMoved(KItemRange(0, itemCount
), movedToIndexes
);
608 #ifdef KFILEITEMMODEL_DEBUG
609 kDebug() << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
613 void KFileItemModel::slotCompleted()
615 if (m_urlsToExpand
.isEmpty() && m_minimumUpdateIntervalTimer
->isActive()) {
616 // dispatchPendingItems() will be called when the timer
618 m_pendingEmitLoadingCompleted
= true;
622 m_pendingEmitLoadingCompleted
= false;
623 dispatchPendingItemsToInsert();
625 if (!m_urlsToExpand
.isEmpty()) {
626 // Try to find a URL that can be expanded.
627 // Note that the parent folder must be expanded before any of its subfolders become visible.
628 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
629 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
630 foreach(const KUrl
& url
, m_urlsToExpand
) {
631 const int index
= m_items
.value(url
, -1);
633 m_urlsToExpand
.remove(url
);
634 if (setExpanded(index
, true)) {
635 // The dir lister has been triggered. This slot will be called
636 // again after the directory has been expanded.
642 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
643 // if these URLs have been deleted in the meantime.
644 m_urlsToExpand
.clear();
647 emit
loadingCompleted();
648 m_minimumUpdateIntervalTimer
->start();
651 void KFileItemModel::slotCanceled()
653 m_minimumUpdateIntervalTimer
->stop();
654 m_maximumUpdateIntervalTimer
->stop();
655 dispatchPendingItemsToInsert();
658 void KFileItemModel::slotNewItems(const KFileItemList
& items
)
660 m_pendingItemsToInsert
.append(items
);
662 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer
->isActive()) {
663 // Assure that items get dispatched if no completed() or canceled() signal is
664 // emitted during the maximum update interval.
665 m_maximumUpdateIntervalTimer
->start();
669 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
671 if (!m_pendingItemsToInsert
.isEmpty()) {
672 insertItems(m_pendingItemsToInsert
);
673 m_pendingItemsToInsert
.clear();
678 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
680 Q_ASSERT(!items
.isEmpty());
681 #ifdef KFILEITEMMODEL_DEBUG
682 kDebug() << "Refreshing" << items
.count() << "items";
687 // Get the indexes of all items that have been refreshed
689 indexes
.reserve(items
.count());
691 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
692 while (it
.hasNext()) {
693 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
694 const int index
= m_items
.value(itemPair
.second
.url(), -1);
696 indexes
.append(index
);
700 // If the changed items have been created recently, they might not be in m_items yet.
701 // In that case, the list 'indexes' might be empty.
702 if (indexes
.isEmpty()) {
706 // Extract the item-ranges out of the changed indexes
709 KItemRangeList itemRangeList
;
712 int previousIndex
= indexes
.at(0);
714 const int maxIndex
= indexes
.count() - 1;
715 for (int i
= 1; i
<= maxIndex
; ++i
) {
716 const int currentIndex
= indexes
.at(i
);
717 if (currentIndex
== previousIndex
+ 1) {
720 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
722 rangeIndex
= currentIndex
;
725 previousIndex
= currentIndex
;
728 if (rangeCount
> 0) {
729 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
732 emit
itemsChanged(itemRangeList
, QSet
<QByteArray
>());
735 void KFileItemModel::slotClear()
737 #ifdef KFILEITEMMODEL_DEBUG
738 kDebug() << "Clearing all items";
743 m_minimumUpdateIntervalTimer
->stop();
744 m_maximumUpdateIntervalTimer
->stop();
745 m_resortAllItemsTimer
->stop();
746 m_pendingItemsToInsert
.clear();
748 m_rootExpansionLevel
= -1;
750 const int removedCount
= m_itemData
.count();
751 if (removedCount
> 0) {
752 qDeleteAll(m_itemData
);
755 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
758 m_expandedUrls
.clear();
761 void KFileItemModel::slotClear(const KUrl
& url
)
766 void KFileItemModel::dispatchPendingItemsToInsert()
768 if (!m_pendingItemsToInsert
.isEmpty()) {
769 insertItems(m_pendingItemsToInsert
);
770 m_pendingItemsToInsert
.clear();
773 if (m_pendingEmitLoadingCompleted
) {
774 emit
loadingCompleted();
778 void KFileItemModel::insertItems(const KFileItemList
& items
)
780 if (items
.isEmpty()) {
784 #ifdef KFILEITEMMODEL_DEBUG
787 kDebug() << "===========================================================";
788 kDebug() << "Inserting" << items
.count() << "items";
793 QList
<ItemData
*> sortedItems
= createItemDataList(items
);
794 sort(sortedItems
.begin(), sortedItems
.end());
796 #ifdef KFILEITEMMODEL_DEBUG
797 kDebug() << "[TIME] Sorting:" << timer
.elapsed();
800 KItemRangeList itemRanges
;
803 int insertedAtIndex
= -1; // Index for the current item-range
804 int insertedCount
= 0; // Count for the current item-range
805 int previouslyInsertedCount
= 0; // Sum of previously inserted items for all ranges
806 while (sourceIndex
< sortedItems
.count()) {
807 // Find target index from m_items to insert the current item
809 const int previousTargetIndex
= targetIndex
;
810 while (targetIndex
< m_itemData
.count()) {
811 if (!lessThan(m_itemData
.at(targetIndex
), sortedItems
.at(sourceIndex
))) {
817 if (targetIndex
- previousTargetIndex
> 0 && insertedAtIndex
>= 0) {
818 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
819 previouslyInsertedCount
+= insertedCount
;
820 insertedAtIndex
= targetIndex
- previouslyInsertedCount
;
824 // Insert item at the position targetIndex by transfering
825 // the ownership of the item-data from sortedItems to m_itemData.
826 // m_items will be inserted after the loop (see comment below)
827 m_itemData
.insert(targetIndex
, sortedItems
.at(sourceIndex
));
830 if (insertedAtIndex
< 0) {
831 insertedAtIndex
= targetIndex
;
832 Q_ASSERT(previouslyInsertedCount
== 0);
838 // The indexes of all m_items must be adjusted, not only the index
840 const int itemDataCount
= m_itemData
.count();
841 for (int i
= 0; i
< itemDataCount
; ++i
) {
842 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
845 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
846 emit
itemsInserted(itemRanges
);
848 #ifdef KFILEITEMMODEL_DEBUG
849 kDebug() << "[TIME] Inserting of" << items
.count() << "items:" << timer
.elapsed();
853 void KFileItemModel::removeItems(const KFileItemList
& items
)
855 if (items
.isEmpty()) {
859 #ifdef KFILEITEMMODEL_DEBUG
860 kDebug() << "Removing " << items
.count() << "items";
865 QList
<ItemData
*> sortedItems
= createItemDataList(items
);
866 sort(sortedItems
.begin(), sortedItems
.end());
868 QList
<int> indexesToRemove
;
869 indexesToRemove
.reserve(items
.count());
871 // Calculate the item ranges that will get deleted
872 KItemRangeList itemRanges
;
873 int removedAtIndex
= -1;
874 int removedCount
= 0;
876 foreach (const ItemData
* itemData
, sortedItems
) {
877 const KFileItem
& itemToRemove
= itemData
->item
;
879 const int previousTargetIndex
= targetIndex
;
880 while (targetIndex
< m_itemData
.count()) {
881 if (m_itemData
.at(targetIndex
)->item
.url() == itemToRemove
.url()) {
886 if (targetIndex
>= m_itemData
.count()) {
887 kWarning() << "Item that should be deleted has not been found!";
891 if (targetIndex
- previousTargetIndex
> 0 && removedAtIndex
>= 0) {
892 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
893 removedAtIndex
= targetIndex
;
897 indexesToRemove
.append(targetIndex
);
898 if (removedAtIndex
< 0) {
899 removedAtIndex
= targetIndex
;
904 qDeleteAll(sortedItems
);
908 for (int i
= indexesToRemove
.count() - 1; i
>= 0; --i
) {
909 const int indexToRemove
= indexesToRemove
.at(i
);
910 delete m_itemData
.at(indexToRemove
);
911 m_itemData
.removeAt(indexToRemove
);
914 // The indexes of all m_items must be adjusted, not only the index
915 // of the removed items
916 const int itemDataCount
= m_itemData
.count();
917 for (int i
= 0; i
< itemDataCount
; ++i
) {
918 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
922 m_rootExpansionLevel
= -1;
925 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
926 emit
itemsRemoved(itemRanges
);
929 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const KFileItemList
& items
) const
931 QList
<ItemData
*> itemDataList
;
932 itemDataList
.reserve(items
.count());
934 foreach (const KFileItem
& item
, items
) {
935 ItemData
* itemData
= new ItemData();
936 itemData
->item
= item
;
937 itemData
->values
= retrieveData(item
);
938 itemDataList
.append(itemData
);
944 void KFileItemModel::removeExpandedItems()
946 KFileItemList expandedItems
;
948 const int maxIndex
= m_itemData
.count() - 1;
949 for (int i
= 0; i
<= maxIndex
; ++i
) {
950 const ItemData
* itemData
= m_itemData
.at(i
);
951 if (itemData
->values
.value("expansionLevel").toInt() > 0) {
952 expandedItems
.append(itemData
->item
);
956 // The m_rootExpansionLevel may not get reset before all items with
957 // a bigger expansionLevel have been removed.
958 Q_ASSERT(m_rootExpansionLevel
>= 0);
959 removeItems(expandedItems
);
961 m_rootExpansionLevel
= -1;
962 m_expandedUrls
.clear();
965 void KFileItemModel::resetRoles()
967 for (int i
= 0; i
< RolesCount
; ++i
) {
968 m_requestRole
[i
] = false;
972 KFileItemModel::Role
KFileItemModel::roleIndex(const QByteArray
& role
) const
974 static QHash
<QByteArray
, Role
> rolesHash
;
975 if (rolesHash
.isEmpty()) {
976 rolesHash
.insert("name", NameRole
);
977 rolesHash
.insert("size", SizeRole
);
978 rolesHash
.insert("date", DateRole
);
979 rolesHash
.insert("permissions", PermissionsRole
);
980 rolesHash
.insert("owner", OwnerRole
);
981 rolesHash
.insert("group", GroupRole
);
982 rolesHash
.insert("type", TypeRole
);
983 rolesHash
.insert("destination", DestinationRole
);
984 rolesHash
.insert("path", PathRole
);
985 rolesHash
.insert("comment", CommentRole
);
986 rolesHash
.insert("tags", TagsRole
);
987 rolesHash
.insert("rating", RatingRole
);
988 rolesHash
.insert("isDir", IsDirRole
);
989 rolesHash
.insert("isExpanded", IsExpandedRole
);
990 rolesHash
.insert("expansionLevel", ExpansionLevelRole
);
992 return rolesHash
.value(role
, NoRole
);
995 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
) const
997 // It is important to insert only roles that are fast to retrieve. E.g.
998 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
999 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1000 QHash
<QByteArray
, QVariant
> data
;
1001 data
.insert("iconPixmap", QPixmap());
1002 data
.insert("url", item
.url());
1004 const bool isDir
= item
.isDir();
1005 if (m_requestRole
[IsDirRole
]) {
1006 data
.insert("isDir", isDir
);
1009 if (m_requestRole
[NameRole
]) {
1010 data
.insert("name", item
.text());
1013 if (m_requestRole
[SizeRole
]) {
1015 data
.insert("size", QVariant());
1017 data
.insert("size", item
.size());
1021 if (m_requestRole
[DateRole
]) {
1022 // Don't use KFileItem::timeString() as this is too expensive when
1023 // having several thousands of items. Instead the formatting of the
1024 // date-time will be done on-demand by the view when the date will be shown.
1025 const KDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
1026 data
.insert("date", dateTime
.dateTime());
1029 if (m_requestRole
[PermissionsRole
]) {
1030 data
.insert("permissions", item
.permissionsString());
1033 if (m_requestRole
[OwnerRole
]) {
1034 data
.insert("owner", item
.user());
1037 if (m_requestRole
[GroupRole
]) {
1038 data
.insert("group", item
.group());
1041 if (m_requestRole
[DestinationRole
]) {
1042 QString destination
= item
.linkDest();
1043 if (destination
.isEmpty()) {
1044 destination
= i18nc("@item:intable", "No destination");
1046 data
.insert("destination", destination
);
1049 if (m_requestRole
[PathRole
]) {
1050 data
.insert("path", item
.localPath());
1053 if (m_requestRole
[IsExpandedRole
]) {
1054 data
.insert("isExpanded", false);
1057 if (m_requestRole
[ExpansionLevelRole
]) {
1058 if (m_rootExpansionLevel
< 0 && m_dirLister
.data()) {
1059 const QString rootDir
= m_dirLister
.data()->url().directory(KUrl::AppendTrailingSlash
);
1060 m_rootExpansionLevel
= rootDir
.count('/');
1061 if (m_rootExpansionLevel
== 1) {
1062 // Special case: The root is already reached and no parent is available
1063 --m_rootExpansionLevel
;
1066 const QString dir
= item
.url().directory(KUrl::AppendTrailingSlash
);
1067 const int level
= dir
.count('/') - m_rootExpansionLevel
- 1;
1068 data
.insert("expansionLevel", level
);
1071 if (item
.isMimeTypeKnown()) {
1072 data
.insert("iconName", item
.iconName());
1074 if (m_requestRole
[TypeRole
]) {
1075 data
.insert("type", item
.mimeComment());
1082 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
) const
1084 const KFileItem
& itemA
= a
->item
;
1085 const KFileItem
& itemB
= b
->item
;
1089 if (m_rootExpansionLevel
>= 0) {
1090 result
= expansionLevelsCompare(itemA
, itemB
);
1092 // The items have parents with different expansion levels
1093 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1097 if (m_sortFoldersFirst
|| m_sortRole
== SizeRole
) {
1098 const bool isDirA
= itemA
.isDir();
1099 const bool isDirB
= itemB
.isDir();
1100 if (isDirA
&& !isDirB
) {
1102 } else if (!isDirA
&& isDirB
) {
1107 switch (m_sortRole
) {
1109 result
= stringCompare(itemA
.text(), itemB
.text());
1111 // KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1112 result
= stringCompare(itemA
.name(m_caseSensitivity
== Qt::CaseInsensitive
),
1113 itemB
.name(m_caseSensitivity
== Qt::CaseInsensitive
));
1119 const KDateTime dateTimeA
= itemA
.time(KFileItem::ModificationTime
);
1120 const KDateTime dateTimeB
= itemB
.time(KFileItem::ModificationTime
);
1121 if (dateTimeA
< dateTimeB
) {
1123 } else if (dateTimeA
> dateTimeB
) {
1130 if (itemA
.isDir()) {
1131 Q_ASSERT(itemB
.isDir()); // see "if (m_sortFoldersFirst || m_sortRole == SizeRole)" above
1133 const QVariant valueA
= a
->values
.value("size");
1134 const QVariant valueB
= b
->values
.value("size");
1136 if (valueA
.isNull()) {
1138 } else if (valueB
.isNull()) {
1141 result
= valueA
.value
<KIO::filesize_t
>() - valueB
.value
<KIO::filesize_t
>();
1144 Q_ASSERT(!itemB
.isDir()); // see "if (m_sortFoldersFirst || m_sortRole == SizeRole)" above
1145 result
= itemA
.size() - itemB
.size();
1151 result
= QString::compare(a
->values
.value("type").toString(),
1152 b
->values
.value("type").toString());
1157 result
= QString::compare(a
->values
.value("comment").toString(),
1158 b
->values
.value("comment").toString());
1163 result
= QString::compare(a
->values
.value("tags").toString(),
1164 b
->values
.value("tags").toString());
1169 result
= a
->values
.value("rating").toInt() - b
->values
.value("rating").toInt();
1178 // It must be assured that the sort order is always unique even if two values have been
1179 // equal. In this case a comparison of the URL is done which is unique in all cases
1180 // within KDirLister.
1181 result
= QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1184 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1187 void KFileItemModel::sort(QList
<ItemData
*>::iterator begin
,
1188 QList
<ItemData
*>::iterator end
)
1190 // The implementation is based on qStableSortHelper() from qalgorithms.h
1191 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1192 // In opposite to qStableSort() it allows to use a member-function for the comparison of elements.
1194 const int span
= end
- begin
;
1199 const QList
<ItemData
*>::iterator middle
= begin
+ span
/ 2;
1200 sort(begin
, middle
);
1202 merge(begin
, middle
, end
);
1205 void KFileItemModel::merge(QList
<ItemData
*>::iterator begin
,
1206 QList
<ItemData
*>::iterator pivot
,
1207 QList
<ItemData
*>::iterator end
)
1209 // The implementation is based on qMerge() from qalgorithms.h
1210 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1212 const int len1
= pivot
- begin
;
1213 const int len2
= end
- pivot
;
1215 if (len1
== 0 || len2
== 0) {
1219 if (len1
+ len2
== 2) {
1220 if (lessThan(*(begin
+ 1), *(begin
))) {
1221 qSwap(*begin
, *(begin
+ 1));
1226 QList
<ItemData
*>::iterator firstCut
;
1227 QList
<ItemData
*>::iterator secondCut
;
1230 const int len1Half
= len1
/ 2;
1231 firstCut
= begin
+ len1Half
;
1232 secondCut
= lowerBound(pivot
, end
, *firstCut
);
1233 len2Half
= secondCut
- pivot
;
1235 len2Half
= len2
/ 2;
1236 secondCut
= pivot
+ len2Half
;
1237 firstCut
= upperBound(begin
, pivot
, *secondCut
);
1240 reverse(firstCut
, pivot
);
1241 reverse(pivot
, secondCut
);
1242 reverse(firstCut
, secondCut
);
1244 const QList
<ItemData
*>::iterator newPivot
= firstCut
+ len2Half
;
1245 merge(begin
, firstCut
, newPivot
);
1246 merge(newPivot
, secondCut
, end
);
1249 QList
<KFileItemModel::ItemData
*>::iterator
KFileItemModel::lowerBound(QList
<ItemData
*>::iterator begin
,
1250 QList
<ItemData
*>::iterator end
,
1251 const ItemData
* value
)
1253 // The implementation is based on qLowerBound() from qalgorithms.h
1254 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1256 QList
<ItemData
*>::iterator middle
;
1257 int n
= int(end
- begin
);
1262 middle
= begin
+ half
;
1263 if (lessThan(*middle
, value
)) {
1273 QList
<KFileItemModel::ItemData
*>::iterator
KFileItemModel::upperBound(QList
<ItemData
*>::iterator begin
,
1274 QList
<ItemData
*>::iterator end
,
1275 const ItemData
* value
)
1277 // The implementation is based on qUpperBound() from qalgorithms.h
1278 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1280 QList
<ItemData
*>::iterator middle
;
1281 int n
= end
- begin
;
1286 middle
= begin
+ half
;
1287 if (lessThan(value
, *middle
)) {
1297 void KFileItemModel::reverse(QList
<ItemData
*>::iterator begin
,
1298 QList
<ItemData
*>::iterator end
)
1300 // The implementation is based on qReverse() from qalgorithms.h
1301 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1304 while (begin
< end
) {
1305 qSwap(*begin
++, *end
--);
1309 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
) const
1311 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1312 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1313 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1314 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1316 if (m_caseSensitivity
== Qt::CaseInsensitive
) {
1317 const int result
= m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseInsensitive
)
1318 : QString::compare(a
, b
, Qt::CaseInsensitive
);
1320 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1321 // comparison, still a deterministic sort order is required. A case sensitive
1322 // comparison is done as fallback.
1327 return m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseSensitive
)
1328 : QString::compare(a
, b
, Qt::CaseSensitive
);
1331 int KFileItemModel::expansionLevelsCompare(const KFileItem
& a
, const KFileItem
& b
) const
1333 const KUrl urlA
= a
.url();
1334 const KUrl urlB
= b
.url();
1335 if (urlA
.directory() == urlB
.directory()) {
1336 // Both items have the same directory as parent
1340 // Check whether one item is the parent of the other item
1341 if (urlA
.isParentOf(urlB
)) {
1343 } else if (urlB
.isParentOf(urlA
)) {
1347 // Determine the maximum common path of both items and
1348 // remember the index in 'index'
1349 const QString pathA
= urlA
.path();
1350 const QString pathB
= urlB
.path();
1352 const int maxIndex
= qMin(pathA
.length(), pathB
.length()) - 1;
1354 while (index
<= maxIndex
&& pathA
.at(index
) == pathB
.at(index
)) {
1357 if (index
> maxIndex
) {
1360 while ((pathA
.at(index
) != QLatin1Char('/') || pathB
.at(index
) != QLatin1Char('/')) && index
> 0) {
1364 // Determine the first sub-path after the common path and
1365 // check whether it represents a directory or already a file
1367 const QString subPathA
= subPath(a
, pathA
, index
, &isDirA
);
1369 const QString subPathB
= subPath(b
, pathB
, index
, &isDirB
);
1371 if (isDirA
&& !isDirB
) {
1373 } else if (!isDirA
&& isDirB
) {
1377 return stringCompare(subPathA
, subPathB
);
1380 QString
KFileItemModel::subPath(const KFileItem
& item
,
1381 const QString
& itemPath
,
1386 const int pathIndex
= itemPath
.indexOf('/', start
+ 1);
1387 *isDir
= (pathIndex
> 0) || item
.isDir();
1388 return itemPath
.mid(start
, pathIndex
- start
);
1391 bool KFileItemModel::useMaximumUpdateInterval() const
1393 const KDirLister
* dirLister
= m_dirLister
.data();
1394 return dirLister
&& !dirLister
->url().isLocalFile();
1397 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1399 Q_ASSERT(!m_itemData
.isEmpty());
1401 const int maxIndex
= count() - 1;
1402 QList
<QPair
<int, QVariant
> > groups
;
1406 bool isLetter
= false;
1407 for (int i
= 0; i
<= maxIndex
; ++i
) {
1408 if (isChildItem(i
)) {
1412 const QString name
= m_itemData
.at(i
)->values
.value("name").toString();
1414 // Use the first character of the name as group indication
1415 QChar newFirstChar
= name
.at(0).toUpper();
1416 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1417 newFirstChar
= name
.at(1);
1420 if (firstChar
!= newFirstChar
) {
1421 QString newGroupValue
;
1422 if (newFirstChar
>= QLatin1Char('A') && newFirstChar
<= QLatin1Char('Z')) {
1423 // Apply group 'A' - 'Z'
1424 newGroupValue
= newFirstChar
;
1426 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
1427 // Apply group '0 - 9' for any name that starts with a digit
1428 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
1432 // If the current group is 'A' - 'Z' check whether a locale character
1433 // fits into the existing group.
1434 // TODO: This does not work in the case if e.g. the group 'O' starts with
1435 // an umlaut 'O' -> provide unit-test to document this known issue
1436 const QChar
prevChar(firstChar
.unicode() - ushort(1));
1437 const QChar
nextChar(firstChar
.unicode() + ushort(1));
1438 const QString
currChar(newFirstChar
);
1439 const bool partOfCurrentGroup
= currChar
.localeAwareCompare(prevChar
) > 0 &&
1440 currChar
.localeAwareCompare(nextChar
) < 0;
1441 if (partOfCurrentGroup
) {
1445 newGroupValue
= i18nc("@title:group", "Others");
1449 if (newGroupValue
!= groupValue
) {
1450 groupValue
= newGroupValue
;
1451 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1454 firstChar
= newFirstChar
;
1460 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
1462 Q_ASSERT(!m_itemData
.isEmpty());
1464 const int maxIndex
= count() - 1;
1465 QList
<QPair
<int, QVariant
> > groups
;
1468 for (int i
= 0; i
<= maxIndex
; ++i
) {
1469 if (isChildItem(i
)) {
1473 const KFileItem
& item
= m_itemData
.at(i
)->item
;
1474 const KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
1475 QString newGroupValue
;
1476 if (!item
.isNull() && item
.isDir()) {
1477 newGroupValue
= i18nc("@title:group Size", "Folders");
1478 } else if (fileSize
< 5 * 1024 * 1024) {
1479 newGroupValue
= i18nc("@title:group Size", "Small");
1480 } else if (fileSize
< 10 * 1024 * 1024) {
1481 newGroupValue
= i18nc("@title:group Size", "Medium");
1483 newGroupValue
= i18nc("@title:group Size", "Big");
1486 if (newGroupValue
!= groupValue
) {
1487 groupValue
= newGroupValue
;
1488 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1495 QList
<QPair
<int, QVariant
> > KFileItemModel::dateRoleGroups() const
1497 Q_ASSERT(!m_itemData
.isEmpty());
1499 const int maxIndex
= count() - 1;
1500 QList
<QPair
<int, QVariant
> > groups
;
1502 const QDate currentDate
= KDateTime::currentLocalDateTime().date();
1504 int yearForCurrentWeek
= 0;
1505 int currentWeek
= currentDate
.weekNumber(&yearForCurrentWeek
);
1506 if (yearForCurrentWeek
== currentDate
.year() + 1) {
1510 QDate previousModifiedDate
;
1512 for (int i
= 0; i
<= maxIndex
; ++i
) {
1513 if (isChildItem(i
)) {
1517 const KDateTime modifiedTime
= m_itemData
.at(i
)->item
.time(KFileItem::ModificationTime
);
1518 const QDate modifiedDate
= modifiedTime
.date();
1519 if (modifiedDate
== previousModifiedDate
) {
1520 // The current item is in the same group as the previous item
1523 previousModifiedDate
= modifiedDate
;
1525 const int daysDistance
= modifiedDate
.daysTo(currentDate
);
1527 int yearForModifiedWeek
= 0;
1528 int modifiedWeek
= modifiedDate
.weekNumber(&yearForModifiedWeek
);
1529 if (yearForModifiedWeek
== modifiedDate
.year() + 1) {
1533 QString newGroupValue
;
1534 if (currentDate
.year() == modifiedDate
.year() && currentDate
.month() == modifiedDate
.month()) {
1535 if (modifiedWeek
> currentWeek
) {
1536 // Usecase: modified date = 2010-01-01, current date = 2010-01-22
1537 // modified week = 53, current week = 3
1540 switch (currentWeek
- modifiedWeek
) {
1542 switch (daysDistance
) {
1543 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
1544 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
1545 default: newGroupValue
= modifiedTime
.toString(i18nc("@title:group The week day name: %A", "%A"));
1549 newGroupValue
= i18nc("@title:group Date", "Last Week");
1552 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
1555 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
1559 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
1565 const QDate lastMonthDate
= currentDate
.addMonths(-1);
1566 if (lastMonthDate
.year() == modifiedDate
.year() && lastMonthDate
.month() == modifiedDate
.month()) {
1567 if (daysDistance
== 1) {
1568 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Yesterday (%B, %Y)"));
1569 } else if (daysDistance
<= 7) {
1570 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)"));
1571 } else if (daysDistance
<= 7 * 2) {
1572 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)"));
1573 } else if (daysDistance
<= 7 * 3) {
1574 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)"));
1575 } else if (daysDistance
<= 7 * 4) {
1576 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)"));
1578 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"));
1581 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"));
1585 if (newGroupValue
!= groupValue
) {
1586 groupValue
= newGroupValue
;
1587 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1594 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
1596 Q_ASSERT(!m_itemData
.isEmpty());
1598 const int maxIndex
= count() - 1;
1599 QList
<QPair
<int, QVariant
> > groups
;
1601 QString permissionsString
;
1603 for (int i
= 0; i
<= maxIndex
; ++i
) {
1604 if (isChildItem(i
)) {
1608 const ItemData
* itemData
= m_itemData
.at(i
);
1609 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
1610 if (newPermissionsString
== permissionsString
) {
1613 permissionsString
= newPermissionsString
;
1615 const QFileInfo
info(itemData
->item
.url().pathOrUrl());
1619 if (info
.permission(QFile::ReadUser
)) {
1620 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1622 if (info
.permission(QFile::WriteUser
)) {
1623 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1625 if (info
.permission(QFile::ExeUser
)) {
1626 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1628 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
1632 if (info
.permission(QFile::ReadGroup
)) {
1633 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1635 if (info
.permission(QFile::WriteGroup
)) {
1636 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1638 if (info
.permission(QFile::ExeGroup
)) {
1639 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1641 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
1643 // Set others string
1645 if (info
.permission(QFile::ReadOther
)) {
1646 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1648 if (info
.permission(QFile::WriteOther
)) {
1649 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1651 if (info
.permission(QFile::ExeOther
)) {
1652 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1654 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
1656 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
1657 if (newGroupValue
!= groupValue
) {
1658 groupValue
= newGroupValue
;
1659 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1666 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
1668 Q_ASSERT(!m_itemData
.isEmpty());
1670 const int maxIndex
= count() - 1;
1671 QList
<QPair
<int, QVariant
> > groups
;
1674 for (int i
= 0; i
<= maxIndex
; ++i
) {
1675 if (isChildItem(i
)) {
1678 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating").toInt();
1679 if (newGroupValue
!= groupValue
) {
1680 groupValue
= newGroupValue
;
1681 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1688 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
1690 Q_ASSERT(!m_itemData
.isEmpty());
1692 const int maxIndex
= count() - 1;
1693 QList
<QPair
<int, QVariant
> > groups
;
1696 for (int i
= 0; i
<= maxIndex
; ++i
) {
1697 if (isChildItem(i
)) {
1700 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
1701 if (newGroupValue
!= groupValue
) {
1702 groupValue
= newGroupValue
;
1703 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1710 bool KFileItemModel::matchesNameFilter(const KFileItem
& item
, const QString
& nameFilter
)
1712 const QString itemText
= item
.text().toLower();
1713 return itemText
.contains(nameFilter
);
1716 #include "kfileitemmodel.moc"