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 dispatchPendingItemsToInsert();
485 m_nameFilter
= nameFilter
;
487 // Check which shown items from m_itemData must get
488 // hidden and hence moved to m_filteredItems.
489 KFileItemList newFilteredItems
;
491 foreach (ItemData
* itemData
, m_itemData
) {
492 if (!matchesNameFilter(itemData
->item
)) {
493 newFilteredItems
.append(itemData
->item
);
494 m_filteredItems
.insert(itemData
->item
);
498 removeItems(newFilteredItems
);
500 // Check which hidden items from m_filteredItems should
501 // get visible again and hence removed from m_filteredItems.
502 KFileItemList newVisibleItems
;
504 QMutableSetIterator
<KFileItem
> it(m_filteredItems
);
505 while (it
.hasNext()) {
506 const KFileItem item
= it
.next();
507 if (matchesNameFilter(item
)) {
508 newVisibleItems
.append(item
);
509 m_filteredItems
.remove(item
);
513 insertItems(newVisibleItems
);
517 QString
KFileItemModel::nameFilter() const
522 void KFileItemModel::onGroupedSortingChanged(bool current
)
528 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
531 m_sortRole
= roleIndex(current
);
533 #ifdef KFILEITEMMODEL_DEBUG
534 if (!m_requestRole
[m_sortRole
]) {
535 kWarning() << "The sort-role has been changed to a role that has not been received yet";
542 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
549 void KFileItemModel::resortAllItems()
551 m_resortAllItemsTimer
->stop();
553 const int itemCount
= count();
554 if (itemCount
<= 0) {
558 #ifdef KFILEITEMMODEL_DEBUG
561 kDebug() << "===========================================================";
562 kDebug() << "Resorting" << itemCount
<< "items";
565 // Remember the order of the current URLs so
566 // that it can be determined which indexes have
567 // been moved because of the resorting.
569 oldUrls
.reserve(itemCount
);
570 foreach (const ItemData
* itemData
, m_itemData
) {
571 oldUrls
.append(itemData
->item
.url());
578 sort(m_itemData
.begin(), m_itemData
.end());
579 for (int i
= 0; i
< itemCount
; ++i
) {
580 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
583 // Determine the indexes that have been moved
584 bool emitItemsMoved
= false;
585 QList
<int> movedToIndexes
;
586 movedToIndexes
.reserve(itemCount
);
587 for (int i
= 0; i
< itemCount
; i
++) {
588 const int newIndex
= m_items
.value(oldUrls
.at(i
).url());
589 movedToIndexes
.append(newIndex
);
590 if (!emitItemsMoved
&& newIndex
!= i
) {
591 emitItemsMoved
= true;
595 if (emitItemsMoved
) {
596 emit
itemsMoved(KItemRange(0, itemCount
), movedToIndexes
);
599 #ifdef KFILEITEMMODEL_DEBUG
600 kDebug() << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
604 void KFileItemModel::slotCompleted()
606 if (m_urlsToExpand
.isEmpty() && m_minimumUpdateIntervalTimer
->isActive()) {
607 // dispatchPendingItems() will be called when the timer
609 m_pendingEmitLoadingCompleted
= true;
613 m_pendingEmitLoadingCompleted
= false;
614 dispatchPendingItemsToInsert();
616 if (!m_urlsToExpand
.isEmpty()) {
617 // Try to find a URL that can be expanded.
618 // Note that the parent folder must be expanded before any of its subfolders become visible.
619 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
620 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
621 foreach(const KUrl
& url
, m_urlsToExpand
) {
622 const int index
= m_items
.value(url
, -1);
624 m_urlsToExpand
.remove(url
);
625 if (setExpanded(index
, true)) {
626 // The dir lister has been triggered. This slot will be called
627 // again after the directory has been expanded.
633 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
634 // if these URLs have been deleted in the meantime.
635 m_urlsToExpand
.clear();
638 emit
loadingCompleted();
639 m_minimumUpdateIntervalTimer
->start();
642 void KFileItemModel::slotCanceled()
644 m_minimumUpdateIntervalTimer
->stop();
645 m_maximumUpdateIntervalTimer
->stop();
646 dispatchPendingItemsToInsert();
649 void KFileItemModel::slotNewItems(const KFileItemList
& items
)
651 if (m_nameFilter
.isEmpty()) {
652 m_pendingItemsToInsert
.append(items
);
654 // The name-filter is active. Hide filtered items
655 // before inserting them into the model and remember
656 // the filtered items in m_filteredItems.
657 KFileItemList filteredItems
;
658 foreach (const KFileItem
& item
, items
) {
659 if (matchesNameFilter(item
)) {
660 filteredItems
.append(item
);
662 m_filteredItems
.insert(item
);
666 m_pendingItemsToInsert
.append(filteredItems
);
669 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer
->isActive()) {
670 // Assure that items get dispatched if no completed() or canceled() signal is
671 // emitted during the maximum update interval.
672 m_maximumUpdateIntervalTimer
->start();
676 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
678 dispatchPendingItemsToInsert();
680 if (!m_filteredItems
.isEmpty()) {
681 foreach (const KFileItem
& item
, items
) {
682 m_filteredItems
.remove(item
);
689 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
691 Q_ASSERT(!items
.isEmpty());
692 #ifdef KFILEITEMMODEL_DEBUG
693 kDebug() << "Refreshing" << items
.count() << "items";
698 // Get the indexes of all items that have been refreshed
700 indexes
.reserve(items
.count());
702 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
703 while (it
.hasNext()) {
704 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
705 const KFileItem
& oldItem
= itemPair
.first
;
706 const KFileItem
& newItem
= itemPair
.second
;
707 const int index
= m_items
.value(oldItem
.url(), -1);
709 m_itemData
[index
]->item
= newItem
;
710 m_itemData
[index
]->values
= retrieveData(newItem
);
711 m_items
.remove(oldItem
.url());
712 m_items
.insert(newItem
.url(), index
);
713 indexes
.append(index
);
717 // If the changed items have been created recently, they might not be in m_items yet.
718 // In that case, the list 'indexes' might be empty.
719 if (indexes
.isEmpty()) {
723 // Extract the item-ranges out of the changed indexes
726 KItemRangeList itemRangeList
;
727 int previousIndex
= indexes
.at(0);
728 int rangeIndex
= previousIndex
;
731 const int maxIndex
= indexes
.count() - 1;
732 for (int i
= 1; i
<= maxIndex
; ++i
) {
733 const int currentIndex
= indexes
.at(i
);
734 if (currentIndex
== previousIndex
+ 1) {
737 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
739 rangeIndex
= currentIndex
;
742 previousIndex
= currentIndex
;
745 if (rangeCount
> 0) {
746 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
749 emit
itemsChanged(itemRangeList
, m_roles
);
752 void KFileItemModel::slotClear()
754 #ifdef KFILEITEMMODEL_DEBUG
755 kDebug() << "Clearing all items";
758 m_filteredItems
.clear();
761 m_minimumUpdateIntervalTimer
->stop();
762 m_maximumUpdateIntervalTimer
->stop();
763 m_resortAllItemsTimer
->stop();
764 m_pendingItemsToInsert
.clear();
766 m_rootExpansionLevel
= -1;
768 const int removedCount
= m_itemData
.count();
769 if (removedCount
> 0) {
770 qDeleteAll(m_itemData
);
773 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
776 m_expandedUrls
.clear();
779 void KFileItemModel::slotClear(const KUrl
& url
)
784 void KFileItemModel::dispatchPendingItemsToInsert()
786 if (!m_pendingItemsToInsert
.isEmpty()) {
787 insertItems(m_pendingItemsToInsert
);
788 m_pendingItemsToInsert
.clear();
791 if (m_pendingEmitLoadingCompleted
) {
792 emit
loadingCompleted();
796 void KFileItemModel::insertItems(const KFileItemList
& items
)
798 if (items
.isEmpty()) {
802 #ifdef KFILEITEMMODEL_DEBUG
805 kDebug() << "===========================================================";
806 kDebug() << "Inserting" << items
.count() << "items";
811 QList
<ItemData
*> sortedItems
= createItemDataList(items
);
812 sort(sortedItems
.begin(), sortedItems
.end());
814 #ifdef KFILEITEMMODEL_DEBUG
815 kDebug() << "[TIME] Sorting:" << timer
.elapsed();
818 KItemRangeList itemRanges
;
821 int insertedAtIndex
= -1; // Index for the current item-range
822 int insertedCount
= 0; // Count for the current item-range
823 int previouslyInsertedCount
= 0; // Sum of previously inserted items for all ranges
824 while (sourceIndex
< sortedItems
.count()) {
825 // Find target index from m_items to insert the current item
827 const int previousTargetIndex
= targetIndex
;
828 while (targetIndex
< m_itemData
.count()) {
829 if (!lessThan(m_itemData
.at(targetIndex
), sortedItems
.at(sourceIndex
))) {
835 if (targetIndex
- previousTargetIndex
> 0 && insertedAtIndex
>= 0) {
836 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
837 previouslyInsertedCount
+= insertedCount
;
838 insertedAtIndex
= targetIndex
- previouslyInsertedCount
;
842 // Insert item at the position targetIndex by transfering
843 // the ownership of the item-data from sortedItems to m_itemData.
844 // m_items will be inserted after the loop (see comment below)
845 m_itemData
.insert(targetIndex
, sortedItems
.at(sourceIndex
));
848 if (insertedAtIndex
< 0) {
849 insertedAtIndex
= targetIndex
;
850 Q_ASSERT(previouslyInsertedCount
== 0);
856 // The indexes of all m_items must be adjusted, not only the index
858 const int itemDataCount
= m_itemData
.count();
859 for (int i
= 0; i
< itemDataCount
; ++i
) {
860 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
863 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
864 emit
itemsInserted(itemRanges
);
866 #ifdef KFILEITEMMODEL_DEBUG
867 kDebug() << "[TIME] Inserting of" << items
.count() << "items:" << timer
.elapsed();
871 void KFileItemModel::removeItems(const KFileItemList
& items
)
873 if (items
.isEmpty()) {
877 #ifdef KFILEITEMMODEL_DEBUG
878 kDebug() << "Removing " << items
.count() << "items";
883 QList
<ItemData
*> sortedItems
= createItemDataList(items
);
884 sort(sortedItems
.begin(), sortedItems
.end());
886 QList
<int> indexesToRemove
;
887 indexesToRemove
.reserve(items
.count());
889 // Calculate the item ranges that will get deleted
890 KItemRangeList itemRanges
;
891 int removedAtIndex
= -1;
892 int removedCount
= 0;
894 foreach (const ItemData
* itemData
, sortedItems
) {
895 const KFileItem
& itemToRemove
= itemData
->item
;
897 const int previousTargetIndex
= targetIndex
;
898 while (targetIndex
< m_itemData
.count()) {
899 if (m_itemData
.at(targetIndex
)->item
.url() == itemToRemove
.url()) {
904 if (targetIndex
>= m_itemData
.count()) {
905 kWarning() << "Item that should be deleted has not been found!";
909 if (targetIndex
- previousTargetIndex
> 0 && removedAtIndex
>= 0) {
910 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
911 removedAtIndex
= targetIndex
;
915 indexesToRemove
.append(targetIndex
);
916 if (removedAtIndex
< 0) {
917 removedAtIndex
= targetIndex
;
922 qDeleteAll(sortedItems
);
926 for (int i
= indexesToRemove
.count() - 1; i
>= 0; --i
) {
927 const int indexToRemove
= indexesToRemove
.at(i
);
928 ItemData
* data
= m_itemData
.at(indexToRemove
);
930 m_items
.remove(data
->item
.url());
933 m_itemData
.removeAt(indexToRemove
);
936 // The indexes of all m_items must be adjusted, not only the index
937 // of the removed items
938 const int itemDataCount
= m_itemData
.count();
939 for (int i
= 0; i
< itemDataCount
; ++i
) {
940 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
944 m_rootExpansionLevel
= -1;
947 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
948 emit
itemsRemoved(itemRanges
);
951 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const KFileItemList
& items
) const
953 QList
<ItemData
*> itemDataList
;
954 itemDataList
.reserve(items
.count());
956 foreach (const KFileItem
& item
, items
) {
957 ItemData
* itemData
= new ItemData();
958 itemData
->item
= item
;
959 itemData
->values
= retrieveData(item
);
960 itemDataList
.append(itemData
);
966 void KFileItemModel::removeExpandedItems()
968 KFileItemList expandedItems
;
970 const int maxIndex
= m_itemData
.count() - 1;
971 for (int i
= 0; i
<= maxIndex
; ++i
) {
972 const ItemData
* itemData
= m_itemData
.at(i
);
973 if (itemData
->values
.value("expansionLevel").toInt() > 0) {
974 expandedItems
.append(itemData
->item
);
978 // The m_rootExpansionLevel may not get reset before all items with
979 // a bigger expansionLevel have been removed.
980 Q_ASSERT(m_rootExpansionLevel
>= 0);
981 removeItems(expandedItems
);
983 m_rootExpansionLevel
= -1;
984 m_expandedUrls
.clear();
987 void KFileItemModel::resetRoles()
989 for (int i
= 0; i
< RolesCount
; ++i
) {
990 m_requestRole
[i
] = false;
994 KFileItemModel::Role
KFileItemModel::roleIndex(const QByteArray
& role
) const
996 static QHash
<QByteArray
, Role
> rolesHash
;
997 if (rolesHash
.isEmpty()) {
998 rolesHash
.insert("name", NameRole
);
999 rolesHash
.insert("size", SizeRole
);
1000 rolesHash
.insert("date", DateRole
);
1001 rolesHash
.insert("permissions", PermissionsRole
);
1002 rolesHash
.insert("owner", OwnerRole
);
1003 rolesHash
.insert("group", GroupRole
);
1004 rolesHash
.insert("type", TypeRole
);
1005 rolesHash
.insert("destination", DestinationRole
);
1006 rolesHash
.insert("path", PathRole
);
1007 rolesHash
.insert("comment", CommentRole
);
1008 rolesHash
.insert("tags", TagsRole
);
1009 rolesHash
.insert("rating", RatingRole
);
1010 rolesHash
.insert("isDir", IsDirRole
);
1011 rolesHash
.insert("isExpanded", IsExpandedRole
);
1012 rolesHash
.insert("expansionLevel", ExpansionLevelRole
);
1014 return rolesHash
.value(role
, NoRole
);
1017 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
) const
1019 // It is important to insert only roles that are fast to retrieve. E.g.
1020 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1021 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1022 QHash
<QByteArray
, QVariant
> data
;
1023 data
.insert("iconPixmap", QPixmap());
1024 data
.insert("url", item
.url());
1026 const bool isDir
= item
.isDir();
1027 if (m_requestRole
[IsDirRole
]) {
1028 data
.insert("isDir", isDir
);
1031 if (m_requestRole
[NameRole
]) {
1032 data
.insert("name", item
.text());
1035 if (m_requestRole
[SizeRole
]) {
1037 data
.insert("size", QVariant());
1039 data
.insert("size", item
.size());
1043 if (m_requestRole
[DateRole
]) {
1044 // Don't use KFileItem::timeString() as this is too expensive when
1045 // having several thousands of items. Instead the formatting of the
1046 // date-time will be done on-demand by the view when the date will be shown.
1047 const KDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
1048 data
.insert("date", dateTime
.dateTime());
1051 if (m_requestRole
[PermissionsRole
]) {
1052 data
.insert("permissions", item
.permissionsString());
1055 if (m_requestRole
[OwnerRole
]) {
1056 data
.insert("owner", item
.user());
1059 if (m_requestRole
[GroupRole
]) {
1060 data
.insert("group", item
.group());
1063 if (m_requestRole
[DestinationRole
]) {
1064 QString destination
= item
.linkDest();
1065 if (destination
.isEmpty()) {
1066 destination
= i18nc("@item:intable", "No destination");
1068 data
.insert("destination", destination
);
1071 if (m_requestRole
[PathRole
]) {
1072 data
.insert("path", item
.localPath());
1075 if (m_requestRole
[IsExpandedRole
]) {
1076 data
.insert("isExpanded", false);
1079 if (m_requestRole
[ExpansionLevelRole
]) {
1080 if (m_rootExpansionLevel
< 0 && m_dirLister
.data()) {
1081 const QString rootDir
= m_dirLister
.data()->url().directory(KUrl::AppendTrailingSlash
);
1082 m_rootExpansionLevel
= rootDir
.count('/');
1083 if (m_rootExpansionLevel
== 1) {
1084 // Special case: The root is already reached and no parent is available
1085 --m_rootExpansionLevel
;
1088 const QString dir
= item
.url().directory(KUrl::AppendTrailingSlash
);
1089 const int level
= dir
.count('/') - m_rootExpansionLevel
- 1;
1090 data
.insert("expansionLevel", level
);
1093 if (item
.isMimeTypeKnown()) {
1094 data
.insert("iconName", item
.iconName());
1096 if (m_requestRole
[TypeRole
]) {
1097 data
.insert("type", item
.mimeComment());
1104 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
) const
1106 const KFileItem
& itemA
= a
->item
;
1107 const KFileItem
& itemB
= b
->item
;
1111 if (m_rootExpansionLevel
>= 0) {
1112 result
= expansionLevelsCompare(itemA
, itemB
);
1114 // The items have parents with different expansion levels
1115 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1119 if (m_sortFoldersFirst
|| m_sortRole
== SizeRole
) {
1120 const bool isDirA
= itemA
.isDir();
1121 const bool isDirB
= itemB
.isDir();
1122 if (isDirA
&& !isDirB
) {
1124 } else if (!isDirA
&& isDirB
) {
1129 switch (m_sortRole
) {
1131 result
= stringCompare(itemA
.text(), itemB
.text());
1133 // KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1134 result
= stringCompare(itemA
.name(m_caseSensitivity
== Qt::CaseInsensitive
),
1135 itemB
.name(m_caseSensitivity
== Qt::CaseInsensitive
));
1141 const KDateTime dateTimeA
= itemA
.time(KFileItem::ModificationTime
);
1142 const KDateTime dateTimeB
= itemB
.time(KFileItem::ModificationTime
);
1143 if (dateTimeA
< dateTimeB
) {
1145 } else if (dateTimeA
> dateTimeB
) {
1152 if (itemA
.isDir()) {
1153 Q_ASSERT(itemB
.isDir()); // see "if (m_sortFoldersFirst || m_sortRole == SizeRole)" above
1155 const QVariant valueA
= a
->values
.value("size");
1156 const QVariant valueB
= b
->values
.value("size");
1158 if (valueA
.isNull()) {
1160 } else if (valueB
.isNull()) {
1163 result
= valueA
.value
<KIO::filesize_t
>() - valueB
.value
<KIO::filesize_t
>();
1166 Q_ASSERT(!itemB
.isDir()); // see "if (m_sortFoldersFirst || m_sortRole == SizeRole)" above
1167 result
= itemA
.size() - itemB
.size();
1173 result
= QString::compare(a
->values
.value("type").toString(),
1174 b
->values
.value("type").toString());
1179 result
= QString::compare(a
->values
.value("comment").toString(),
1180 b
->values
.value("comment").toString());
1185 result
= QString::compare(a
->values
.value("tags").toString(),
1186 b
->values
.value("tags").toString());
1191 result
= a
->values
.value("rating").toInt() - b
->values
.value("rating").toInt();
1200 // It must be assured that the sort order is always unique even if two values have been
1201 // equal. In this case a comparison of the URL is done which is unique in all cases
1202 // within KDirLister.
1203 result
= QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1206 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1209 void KFileItemModel::sort(QList
<ItemData
*>::iterator begin
,
1210 QList
<ItemData
*>::iterator end
)
1212 // The implementation is based on qStableSortHelper() from qalgorithms.h
1213 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1214 // In opposite to qStableSort() it allows to use a member-function for the comparison of elements.
1216 const int span
= end
- begin
;
1221 const QList
<ItemData
*>::iterator middle
= begin
+ span
/ 2;
1222 sort(begin
, middle
);
1224 merge(begin
, middle
, end
);
1227 void KFileItemModel::merge(QList
<ItemData
*>::iterator begin
,
1228 QList
<ItemData
*>::iterator pivot
,
1229 QList
<ItemData
*>::iterator end
)
1231 // The implementation is based on qMerge() from qalgorithms.h
1232 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1234 const int len1
= pivot
- begin
;
1235 const int len2
= end
- pivot
;
1237 if (len1
== 0 || len2
== 0) {
1241 if (len1
+ len2
== 2) {
1242 if (lessThan(*(begin
+ 1), *(begin
))) {
1243 qSwap(*begin
, *(begin
+ 1));
1248 QList
<ItemData
*>::iterator firstCut
;
1249 QList
<ItemData
*>::iterator secondCut
;
1252 const int len1Half
= len1
/ 2;
1253 firstCut
= begin
+ len1Half
;
1254 secondCut
= lowerBound(pivot
, end
, *firstCut
);
1255 len2Half
= secondCut
- pivot
;
1257 len2Half
= len2
/ 2;
1258 secondCut
= pivot
+ len2Half
;
1259 firstCut
= upperBound(begin
, pivot
, *secondCut
);
1262 reverse(firstCut
, pivot
);
1263 reverse(pivot
, secondCut
);
1264 reverse(firstCut
, secondCut
);
1266 const QList
<ItemData
*>::iterator newPivot
= firstCut
+ len2Half
;
1267 merge(begin
, firstCut
, newPivot
);
1268 merge(newPivot
, secondCut
, end
);
1271 QList
<KFileItemModel::ItemData
*>::iterator
KFileItemModel::lowerBound(QList
<ItemData
*>::iterator begin
,
1272 QList
<ItemData
*>::iterator end
,
1273 const ItemData
* value
)
1275 // The implementation is based on qLowerBound() from qalgorithms.h
1276 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1278 QList
<ItemData
*>::iterator middle
;
1279 int n
= int(end
- begin
);
1284 middle
= begin
+ half
;
1285 if (lessThan(*middle
, value
)) {
1295 QList
<KFileItemModel::ItemData
*>::iterator
KFileItemModel::upperBound(QList
<ItemData
*>::iterator begin
,
1296 QList
<ItemData
*>::iterator end
,
1297 const ItemData
* value
)
1299 // The implementation is based on qUpperBound() from qalgorithms.h
1300 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1302 QList
<ItemData
*>::iterator middle
;
1303 int n
= end
- begin
;
1308 middle
= begin
+ half
;
1309 if (lessThan(value
, *middle
)) {
1319 void KFileItemModel::reverse(QList
<ItemData
*>::iterator begin
,
1320 QList
<ItemData
*>::iterator end
)
1322 // The implementation is based on qReverse() from qalgorithms.h
1323 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1326 while (begin
< end
) {
1327 qSwap(*begin
++, *end
--);
1331 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
) const
1333 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1334 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1335 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1336 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1338 if (m_caseSensitivity
== Qt::CaseInsensitive
) {
1339 const int result
= m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseInsensitive
)
1340 : QString::compare(a
, b
, Qt::CaseInsensitive
);
1342 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1343 // comparison, still a deterministic sort order is required. A case sensitive
1344 // comparison is done as fallback.
1349 return m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseSensitive
)
1350 : QString::compare(a
, b
, Qt::CaseSensitive
);
1353 int KFileItemModel::expansionLevelsCompare(const KFileItem
& a
, const KFileItem
& b
) const
1355 const KUrl urlA
= a
.url();
1356 const KUrl urlB
= b
.url();
1357 if (urlA
.directory() == urlB
.directory()) {
1358 // Both items have the same directory as parent
1362 // Check whether one item is the parent of the other item
1363 if (urlA
.isParentOf(urlB
)) {
1365 } else if (urlB
.isParentOf(urlA
)) {
1369 // Determine the maximum common path of both items and
1370 // remember the index in 'index'
1371 const QString pathA
= urlA
.path();
1372 const QString pathB
= urlB
.path();
1374 const int maxIndex
= qMin(pathA
.length(), pathB
.length()) - 1;
1376 while (index
<= maxIndex
&& pathA
.at(index
) == pathB
.at(index
)) {
1379 if (index
> maxIndex
) {
1382 while ((pathA
.at(index
) != QLatin1Char('/') || pathB
.at(index
) != QLatin1Char('/')) && index
> 0) {
1386 // Determine the first sub-path after the common path and
1387 // check whether it represents a directory or already a file
1389 const QString subPathA
= subPath(a
, pathA
, index
, &isDirA
);
1391 const QString subPathB
= subPath(b
, pathB
, index
, &isDirB
);
1393 if (isDirA
&& !isDirB
) {
1395 } else if (!isDirA
&& isDirB
) {
1399 return stringCompare(subPathA
, subPathB
);
1402 QString
KFileItemModel::subPath(const KFileItem
& item
,
1403 const QString
& itemPath
,
1408 const int pathIndex
= itemPath
.indexOf('/', start
+ 1);
1409 *isDir
= (pathIndex
> 0) || item
.isDir();
1410 return itemPath
.mid(start
, pathIndex
- start
);
1413 bool KFileItemModel::useMaximumUpdateInterval() const
1415 const KDirLister
* dirLister
= m_dirLister
.data();
1416 return dirLister
&& !dirLister
->url().isLocalFile();
1419 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1421 Q_ASSERT(!m_itemData
.isEmpty());
1423 const int maxIndex
= count() - 1;
1424 QList
<QPair
<int, QVariant
> > groups
;
1428 bool isLetter
= false;
1429 for (int i
= 0; i
<= maxIndex
; ++i
) {
1430 if (isChildItem(i
)) {
1434 const QString name
= m_itemData
.at(i
)->values
.value("name").toString();
1436 // Use the first character of the name as group indication
1437 QChar newFirstChar
= name
.at(0).toUpper();
1438 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1439 newFirstChar
= name
.at(1);
1442 if (firstChar
!= newFirstChar
) {
1443 QString newGroupValue
;
1444 if (newFirstChar
>= QLatin1Char('A') && newFirstChar
<= QLatin1Char('Z')) {
1445 // Apply group 'A' - 'Z'
1446 newGroupValue
= newFirstChar
;
1448 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
1449 // Apply group '0 - 9' for any name that starts with a digit
1450 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
1454 // If the current group is 'A' - 'Z' check whether a locale character
1455 // fits into the existing group.
1456 // TODO: This does not work in the case if e.g. the group 'O' starts with
1457 // an umlaut 'O' -> provide unit-test to document this known issue
1458 const QChar
prevChar(firstChar
.unicode() - ushort(1));
1459 const QChar
nextChar(firstChar
.unicode() + ushort(1));
1460 const QString
currChar(newFirstChar
);
1461 const bool partOfCurrentGroup
= currChar
.localeAwareCompare(prevChar
) > 0 &&
1462 currChar
.localeAwareCompare(nextChar
) < 0;
1463 if (partOfCurrentGroup
) {
1467 newGroupValue
= i18nc("@title:group", "Others");
1471 if (newGroupValue
!= groupValue
) {
1472 groupValue
= newGroupValue
;
1473 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1476 firstChar
= newFirstChar
;
1482 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
1484 Q_ASSERT(!m_itemData
.isEmpty());
1486 const int maxIndex
= count() - 1;
1487 QList
<QPair
<int, QVariant
> > groups
;
1490 for (int i
= 0; i
<= maxIndex
; ++i
) {
1491 if (isChildItem(i
)) {
1495 const KFileItem
& item
= m_itemData
.at(i
)->item
;
1496 const KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
1497 QString newGroupValue
;
1498 if (!item
.isNull() && item
.isDir()) {
1499 newGroupValue
= i18nc("@title:group Size", "Folders");
1500 } else if (fileSize
< 5 * 1024 * 1024) {
1501 newGroupValue
= i18nc("@title:group Size", "Small");
1502 } else if (fileSize
< 10 * 1024 * 1024) {
1503 newGroupValue
= i18nc("@title:group Size", "Medium");
1505 newGroupValue
= i18nc("@title:group Size", "Big");
1508 if (newGroupValue
!= groupValue
) {
1509 groupValue
= newGroupValue
;
1510 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1517 QList
<QPair
<int, QVariant
> > KFileItemModel::dateRoleGroups() const
1519 Q_ASSERT(!m_itemData
.isEmpty());
1521 const int maxIndex
= count() - 1;
1522 QList
<QPair
<int, QVariant
> > groups
;
1524 const QDate currentDate
= KDateTime::currentLocalDateTime().date();
1526 int yearForCurrentWeek
= 0;
1527 int currentWeek
= currentDate
.weekNumber(&yearForCurrentWeek
);
1528 if (yearForCurrentWeek
== currentDate
.year() + 1) {
1532 QDate previousModifiedDate
;
1534 for (int i
= 0; i
<= maxIndex
; ++i
) {
1535 if (isChildItem(i
)) {
1539 const KDateTime modifiedTime
= m_itemData
.at(i
)->item
.time(KFileItem::ModificationTime
);
1540 const QDate modifiedDate
= modifiedTime
.date();
1541 if (modifiedDate
== previousModifiedDate
) {
1542 // The current item is in the same group as the previous item
1545 previousModifiedDate
= modifiedDate
;
1547 const int daysDistance
= modifiedDate
.daysTo(currentDate
);
1549 int yearForModifiedWeek
= 0;
1550 int modifiedWeek
= modifiedDate
.weekNumber(&yearForModifiedWeek
);
1551 if (yearForModifiedWeek
== modifiedDate
.year() + 1) {
1555 QString newGroupValue
;
1556 if (currentDate
.year() == modifiedDate
.year() && currentDate
.month() == modifiedDate
.month()) {
1557 if (modifiedWeek
> currentWeek
) {
1558 // Usecase: modified date = 2010-01-01, current date = 2010-01-22
1559 // modified week = 53, current week = 3
1562 switch (currentWeek
- modifiedWeek
) {
1564 switch (daysDistance
) {
1565 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
1566 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
1567 default: newGroupValue
= modifiedTime
.toString(i18nc("@title:group The week day name: %A", "%A"));
1571 newGroupValue
= i18nc("@title:group Date", "Last Week");
1574 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
1577 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
1581 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
1587 const QDate lastMonthDate
= currentDate
.addMonths(-1);
1588 if (lastMonthDate
.year() == modifiedDate
.year() && lastMonthDate
.month() == modifiedDate
.month()) {
1589 if (daysDistance
== 1) {
1590 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Yesterday (%B, %Y)"));
1591 } else if (daysDistance
<= 7) {
1592 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)"));
1593 } else if (daysDistance
<= 7 * 2) {
1594 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)"));
1595 } else if (daysDistance
<= 7 * 3) {
1596 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)"));
1597 } else if (daysDistance
<= 7 * 4) {
1598 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)"));
1600 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"));
1603 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"));
1607 if (newGroupValue
!= groupValue
) {
1608 groupValue
= newGroupValue
;
1609 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1616 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
1618 Q_ASSERT(!m_itemData
.isEmpty());
1620 const int maxIndex
= count() - 1;
1621 QList
<QPair
<int, QVariant
> > groups
;
1623 QString permissionsString
;
1625 for (int i
= 0; i
<= maxIndex
; ++i
) {
1626 if (isChildItem(i
)) {
1630 const ItemData
* itemData
= m_itemData
.at(i
);
1631 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
1632 if (newPermissionsString
== permissionsString
) {
1635 permissionsString
= newPermissionsString
;
1637 const QFileInfo
info(itemData
->item
.url().pathOrUrl());
1641 if (info
.permission(QFile::ReadUser
)) {
1642 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1644 if (info
.permission(QFile::WriteUser
)) {
1645 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1647 if (info
.permission(QFile::ExeUser
)) {
1648 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1650 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
1654 if (info
.permission(QFile::ReadGroup
)) {
1655 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1657 if (info
.permission(QFile::WriteGroup
)) {
1658 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1660 if (info
.permission(QFile::ExeGroup
)) {
1661 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1663 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
1665 // Set others string
1667 if (info
.permission(QFile::ReadOther
)) {
1668 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1670 if (info
.permission(QFile::WriteOther
)) {
1671 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1673 if (info
.permission(QFile::ExeOther
)) {
1674 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1676 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
1678 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
1679 if (newGroupValue
!= groupValue
) {
1680 groupValue
= newGroupValue
;
1681 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1688 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() 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 int newGroupValue
= m_itemData
.at(i
)->values
.value("rating").toInt();
1701 if (newGroupValue
!= groupValue
) {
1702 groupValue
= newGroupValue
;
1703 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1710 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
1712 Q_ASSERT(!m_itemData
.isEmpty());
1714 const int maxIndex
= count() - 1;
1715 QList
<QPair
<int, QVariant
> > groups
;
1718 for (int i
= 0; i
<= maxIndex
; ++i
) {
1719 if (isChildItem(i
)) {
1722 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
1723 if (newGroupValue
!= groupValue
) {
1724 groupValue
= newGroupValue
;
1725 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1732 bool KFileItemModel::matchesNameFilter(const KFileItem
& item
) const
1734 // TODO #1: A performance improvement would be possible by caching m_nameFilter.toLower().
1735 // Before adding yet-another-member it should be checked whether it brings a noticable
1736 // improvement at all.
1738 // TODO #2: If the user entered a '*' use a regular expression
1739 const QString itemText
= item
.text().toLower();
1740 return itemText
.contains(m_nameFilter
.toLower());
1743 #include "kfileitemmodel.moc"