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 void KFileItemModel::setShowHiddenFiles(bool show
)
170 KDirLister
* dirLister
= m_dirLister
.data();
172 dirLister
->setShowingDotFiles(show
);
173 dirLister
->emitChanges();
180 bool KFileItemModel::showHiddenFiles() const
182 const KDirLister
* dirLister
= m_dirLister
.data();
183 return dirLister
? dirLister
->showingDotFiles() : false;
186 QMimeData
* KFileItemModel::createMimeData(const QSet
<int>& indexes
) const
188 QMimeData
* data
= new QMimeData();
190 // The following code has been taken from KDirModel::mimeData()
191 // (kdelibs/kio/kio/kdirmodel.cpp)
192 // Copyright (C) 2006 David Faure <faure@kde.org>
194 KUrl::List mostLocalUrls
;
195 bool canUseMostLocalUrls
= true;
197 QSetIterator
<int> it(indexes
);
198 while (it
.hasNext()) {
199 const int index
= it
.next();
200 const KFileItem item
= fileItem(index
);
201 if (!item
.isNull()) {
205 mostLocalUrls
<< item
.mostLocalUrl(isLocal
);
207 canUseMostLocalUrls
= false;
212 const bool different
= canUseMostLocalUrls
&& mostLocalUrls
!= urls
;
213 urls
= KDirModel::simplifiedUrlList(urls
); // TODO: Check if we still need KDirModel for this in KDE 5.0
215 mostLocalUrls
= KDirModel::simplifiedUrlList(mostLocalUrls
);
216 urls
.populateMimeData(mostLocalUrls
, data
);
218 urls
.populateMimeData(data
);
224 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
226 startFromIndex
= qMax(0, startFromIndex
);
227 for (int i
= startFromIndex
; i
< count(); ++i
) {
228 if (data(i
)["name"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
232 for (int i
= 0; i
< startFromIndex
; ++i
) {
233 if (data(i
)["name"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
240 bool KFileItemModel::supportsDropping(int index
) const
242 const KFileItem item
= fileItem(index
);
243 return item
.isNull() ? false : item
.isDir();
246 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
250 switch (roleIndex(role
)) {
251 case NameRole
: descr
= i18nc("@item:intable", "Name"); break;
252 case SizeRole
: descr
= i18nc("@item:intable", "Size"); break;
253 case DateRole
: descr
= i18nc("@item:intable", "Date"); break;
254 case PermissionsRole
: descr
= i18nc("@item:intable", "Permissions"); break;
255 case OwnerRole
: descr
= i18nc("@item:intable", "Owner"); break;
256 case GroupRole
: descr
= i18nc("@item:intable", "Group"); break;
257 case TypeRole
: descr
= i18nc("@item:intable", "Type"); break;
258 case DestinationRole
: descr
= i18nc("@item:intable", "Destination"); break;
259 case PathRole
: descr
= i18nc("@item:intable", "Path"); break;
260 case CommentRole
: descr
= i18nc("@item:intable", "Comment"); break;
261 case TagsRole
: descr
= i18nc("@item:intable", "Tags"); break;
262 case RatingRole
: descr
= i18nc("@item:intable", "Rating"); break;
264 case IsDirRole
: break;
265 case IsExpandedRole
: break;
266 case ExpansionLevelRole
: break;
267 default: Q_ASSERT(false); break;
273 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
275 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
276 #ifdef KFILEITEMMODEL_DEBUG
280 switch (roleIndex(sortRole())) {
281 case NameRole
: m_groups
= nameRoleGroups(); break;
282 case SizeRole
: m_groups
= sizeRoleGroups(); break;
283 case DateRole
: m_groups
= dateRoleGroups(); break;
284 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
285 case OwnerRole
: m_groups
= genericStringRoleGroups("owner"); break;
286 case GroupRole
: m_groups
= genericStringRoleGroups("group"); break;
287 case TypeRole
: m_groups
= genericStringRoleGroups("type"); break;
288 case DestinationRole
: m_groups
= genericStringRoleGroups("destination"); break;
289 case PathRole
: m_groups
= genericStringRoleGroups("path"); break;
290 case CommentRole
: m_groups
= genericStringRoleGroups("comment"); break;
291 case TagsRole
: m_groups
= genericStringRoleGroups("tags"); break;
292 case RatingRole
: m_groups
= ratingRoleGroups(); break;
294 case IsDirRole
: break;
295 case IsExpandedRole
: break;
296 case ExpansionLevelRole
: break;
297 default: Q_ASSERT(false); break;
300 #ifdef KFILEITEMMODEL_DEBUG
301 kDebug() << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
308 KFileItem
KFileItemModel::fileItem(int index
) const
310 if (index
>= 0 && index
< count()) {
311 return m_itemData
.at(index
)->item
;
317 KFileItem
KFileItemModel::fileItem(const KUrl
& url
) const
319 const int index
= m_items
.value(url
, -1);
321 return m_itemData
.at(index
)->item
;
326 int KFileItemModel::index(const KFileItem
& item
) const
332 return m_items
.value(item
.url(), -1);
335 int KFileItemModel::index(const KUrl
& url
) const
337 KUrl urlToFind
= url
;
338 urlToFind
.adjustPath(KUrl::RemoveTrailingSlash
);
339 return m_items
.value(urlToFind
, -1);
342 KFileItem
KFileItemModel::rootItem() const
344 const KDirLister
* dirLister
= m_dirLister
.data();
346 return dirLister
->rootItem();
351 void KFileItemModel::clear()
356 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
361 const bool supportedExpanding
= m_requestRole
[IsExpandedRole
] && m_requestRole
[ExpansionLevelRole
];
362 const bool willSupportExpanding
= roles
.contains("isExpanded") && roles
.contains("expansionLevel");
363 if (supportedExpanding
&& !willSupportExpanding
) {
364 // No expanding is supported anymore. Take care to delete all items that have an expansion level
365 // that is not 0 (and hence are part of an expanded item).
366 removeExpandedItems();
372 QSetIterator
<QByteArray
> it(roles
);
373 while (it
.hasNext()) {
374 const QByteArray
& role
= it
.next();
375 m_requestRole
[roleIndex(role
)] = true;
379 // Update m_data with the changed requested roles
380 const int maxIndex
= count() - 1;
381 for (int i
= 0; i
<= maxIndex
; ++i
) {
382 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
);
385 kWarning() << "TODO: Emitting itemsChanged() with no information what has changed!";
386 emit
itemsChanged(KItemRangeList() << KItemRange(0, count()), QSet
<QByteArray
>());
390 QSet
<QByteArray
> KFileItemModel::roles() const
395 bool KFileItemModel::setExpanded(int index
, bool expanded
)
397 if (isExpanded(index
) == expanded
|| index
< 0 || index
>= count()) {
401 QHash
<QByteArray
, QVariant
> values
;
402 values
.insert("isExpanded", expanded
);
403 if (!setData(index
, values
)) {
407 const KUrl url
= m_itemData
.at(index
)->item
.url();
409 m_expandedUrls
.insert(url
);
411 KDirLister
* dirLister
= m_dirLister
.data();
413 dirLister
->openUrl(url
, KDirLister::Keep
);
417 m_expandedUrls
.remove(url
);
419 KFileItemList itemsToRemove
;
420 const int expansionLevel
= data(index
)["expansionLevel"].toInt();
422 while (index
< count() && data(index
)["expansionLevel"].toInt() > expansionLevel
) {
423 itemsToRemove
.append(m_itemData
.at(index
)->item
);
426 removeItems(itemsToRemove
);
433 bool KFileItemModel::isExpanded(int index
) const
435 if (index
>= 0 && index
< count()) {
436 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
441 bool KFileItemModel::isExpandable(int index
) const
443 if (index
>= 0 && index
< count()) {
444 return m_itemData
.at(index
)->item
.isDir();
449 QSet
<KUrl
> KFileItemModel::expandedUrls() const
451 return m_expandedUrls
;
454 void KFileItemModel::restoreExpandedUrls(const QSet
<KUrl
>& urls
)
456 m_urlsToExpand
= urls
;
459 void KFileItemModel::setExpanded(const QSet
<KUrl
>& urls
)
462 const KDirLister
* dirLister
= m_dirLister
.data();
467 const int pos
= dirLister
->url().url().length();
469 // Assure that each sub-path of the URLs that should be
470 // expanded is added to m_urlsToExpand too. KDirLister
471 // does not care whether the parent-URL has already been
473 QSetIterator
<KUrl
> it1(urls
);
474 while (it1
.hasNext()) {
475 const KUrl
& url
= it1
.next();
477 KUrl urlToExpand
= dirLister
->url();
478 const QStringList subDirs
= url
.url().mid(pos
).split(QDir::separator());
479 for (int i
= 0; i
< subDirs
.count(); ++i
) {
480 urlToExpand
.addPath(subDirs
.at(i
));
481 m_urlsToExpand
.insert(urlToExpand
);
485 // KDirLister::open() must called at least once to trigger an initial
486 // loading. The pending URLs that must be restored are handled
487 // in slotCompleted().
488 QSetIterator
<KUrl
> it2(m_urlsToExpand
);
489 while (it2
.hasNext()) {
490 const int idx
= index(it2
.next());
491 if (idx
>= 0 && !isExpanded(idx
)) {
492 setExpanded(idx
, true);
498 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
500 if (m_nameFilter
!= nameFilter
) {
501 dispatchPendingItemsToInsert();
503 m_nameFilter
= nameFilter
;
505 // Check which shown items from m_itemData must get
506 // hidden and hence moved to m_filteredItems.
507 KFileItemList newFilteredItems
;
509 foreach (ItemData
* itemData
, m_itemData
) {
510 if (!matchesNameFilter(itemData
->item
)) {
511 newFilteredItems
.append(itemData
->item
);
512 m_filteredItems
.insert(itemData
->item
);
516 removeItems(newFilteredItems
);
518 // Check which hidden items from m_filteredItems should
519 // get visible again and hence removed from m_filteredItems.
520 KFileItemList newVisibleItems
;
522 QMutableSetIterator
<KFileItem
> it(m_filteredItems
);
523 while (it
.hasNext()) {
524 const KFileItem item
= it
.next();
525 if (matchesNameFilter(item
)) {
526 newVisibleItems
.append(item
);
527 m_filteredItems
.remove(item
);
531 insertItems(newVisibleItems
);
535 QString
KFileItemModel::nameFilter() const
540 void KFileItemModel::onGroupedSortingChanged(bool current
)
546 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
549 m_sortRole
= roleIndex(current
);
551 #ifdef KFILEITEMMODEL_DEBUG
552 if (!m_requestRole
[m_sortRole
]) {
553 kWarning() << "The sort-role has been changed to a role that has not been received yet";
560 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
567 void KFileItemModel::resortAllItems()
569 m_resortAllItemsTimer
->stop();
571 const int itemCount
= count();
572 if (itemCount
<= 0) {
576 #ifdef KFILEITEMMODEL_DEBUG
579 kDebug() << "===========================================================";
580 kDebug() << "Resorting" << itemCount
<< "items";
583 // Remember the order of the current URLs so
584 // that it can be determined which indexes have
585 // been moved because of the resorting.
587 oldUrls
.reserve(itemCount
);
588 foreach (const ItemData
* itemData
, m_itemData
) {
589 oldUrls
.append(itemData
->item
.url());
596 sort(m_itemData
.begin(), m_itemData
.end());
597 for (int i
= 0; i
< itemCount
; ++i
) {
598 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
601 // Determine the indexes that have been moved
602 bool emitItemsMoved
= false;
603 QList
<int> movedToIndexes
;
604 movedToIndexes
.reserve(itemCount
);
605 for (int i
= 0; i
< itemCount
; i
++) {
606 const int newIndex
= m_items
.value(oldUrls
.at(i
).url());
607 movedToIndexes
.append(newIndex
);
608 if (!emitItemsMoved
&& newIndex
!= i
) {
609 emitItemsMoved
= true;
613 if (emitItemsMoved
) {
614 emit
itemsMoved(KItemRange(0, itemCount
), movedToIndexes
);
617 #ifdef KFILEITEMMODEL_DEBUG
618 kDebug() << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
622 void KFileItemModel::slotCompleted()
624 if (m_urlsToExpand
.isEmpty() && m_minimumUpdateIntervalTimer
->isActive()) {
625 // dispatchPendingItems() will be called when the timer
627 m_pendingEmitLoadingCompleted
= true;
631 m_pendingEmitLoadingCompleted
= false;
632 dispatchPendingItemsToInsert();
634 if (!m_urlsToExpand
.isEmpty()) {
635 // Try to find a URL that can be expanded.
636 // Note that the parent folder must be expanded before any of its subfolders become visible.
637 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
638 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
639 foreach(const KUrl
& url
, m_urlsToExpand
) {
640 const int index
= m_items
.value(url
, -1);
642 m_urlsToExpand
.remove(url
);
643 if (setExpanded(index
, true)) {
644 // The dir lister has been triggered. This slot will be called
645 // again after the directory has been expanded.
651 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
652 // if these URLs have been deleted in the meantime.
653 m_urlsToExpand
.clear();
656 emit
loadingCompleted();
657 m_minimumUpdateIntervalTimer
->start();
660 void KFileItemModel::slotCanceled()
662 m_minimumUpdateIntervalTimer
->stop();
663 m_maximumUpdateIntervalTimer
->stop();
664 dispatchPendingItemsToInsert();
667 void KFileItemModel::slotNewItems(const KFileItemList
& items
)
669 if (m_nameFilter
.isEmpty()) {
670 m_pendingItemsToInsert
.append(items
);
672 // The name-filter is active. Hide filtered items
673 // before inserting them into the model and remember
674 // the filtered items in m_filteredItems.
675 KFileItemList filteredItems
;
676 foreach (const KFileItem
& item
, items
) {
677 if (matchesNameFilter(item
)) {
678 filteredItems
.append(item
);
680 m_filteredItems
.insert(item
);
684 m_pendingItemsToInsert
.append(filteredItems
);
687 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer
->isActive()) {
688 // Assure that items get dispatched if no completed() or canceled() signal is
689 // emitted during the maximum update interval.
690 m_maximumUpdateIntervalTimer
->start();
694 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
696 dispatchPendingItemsToInsert();
698 if (!m_filteredItems
.isEmpty()) {
699 foreach (const KFileItem
& item
, items
) {
700 m_filteredItems
.remove(item
);
707 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
709 Q_ASSERT(!items
.isEmpty());
710 #ifdef KFILEITEMMODEL_DEBUG
711 kDebug() << "Refreshing" << items
.count() << "items";
716 // Get the indexes of all items that have been refreshed
718 indexes
.reserve(items
.count());
720 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
721 while (it
.hasNext()) {
722 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
723 const KFileItem
& oldItem
= itemPair
.first
;
724 const KFileItem
& newItem
= itemPair
.second
;
725 const int index
= m_items
.value(oldItem
.url(), -1);
727 m_itemData
[index
]->item
= newItem
;
728 m_itemData
[index
]->values
= retrieveData(newItem
);
729 m_items
.remove(oldItem
.url());
730 m_items
.insert(newItem
.url(), index
);
731 indexes
.append(index
);
735 // If the changed items have been created recently, they might not be in m_items yet.
736 // In that case, the list 'indexes' might be empty.
737 if (indexes
.isEmpty()) {
741 // Extract the item-ranges out of the changed indexes
744 KItemRangeList itemRangeList
;
745 int previousIndex
= indexes
.at(0);
746 int rangeIndex
= previousIndex
;
749 const int maxIndex
= indexes
.count() - 1;
750 for (int i
= 1; i
<= maxIndex
; ++i
) {
751 const int currentIndex
= indexes
.at(i
);
752 if (currentIndex
== previousIndex
+ 1) {
755 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
757 rangeIndex
= currentIndex
;
760 previousIndex
= currentIndex
;
763 if (rangeCount
> 0) {
764 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
767 emit
itemsChanged(itemRangeList
, m_roles
);
770 void KFileItemModel::slotClear()
772 #ifdef KFILEITEMMODEL_DEBUG
773 kDebug() << "Clearing all items";
776 m_filteredItems
.clear();
779 m_minimumUpdateIntervalTimer
->stop();
780 m_maximumUpdateIntervalTimer
->stop();
781 m_resortAllItemsTimer
->stop();
782 m_pendingItemsToInsert
.clear();
784 m_rootExpansionLevel
= -1;
786 const int removedCount
= m_itemData
.count();
787 if (removedCount
> 0) {
788 qDeleteAll(m_itemData
);
791 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
794 m_expandedUrls
.clear();
797 void KFileItemModel::slotClear(const KUrl
& url
)
802 void KFileItemModel::dispatchPendingItemsToInsert()
804 if (!m_pendingItemsToInsert
.isEmpty()) {
805 insertItems(m_pendingItemsToInsert
);
806 m_pendingItemsToInsert
.clear();
809 if (m_pendingEmitLoadingCompleted
) {
810 emit
loadingCompleted();
814 void KFileItemModel::insertItems(const KFileItemList
& items
)
816 if (items
.isEmpty()) {
820 #ifdef KFILEITEMMODEL_DEBUG
823 kDebug() << "===========================================================";
824 kDebug() << "Inserting" << items
.count() << "items";
829 QList
<ItemData
*> sortedItems
= createItemDataList(items
);
830 sort(sortedItems
.begin(), sortedItems
.end());
832 #ifdef KFILEITEMMODEL_DEBUG
833 kDebug() << "[TIME] Sorting:" << timer
.elapsed();
836 KItemRangeList itemRanges
;
839 int insertedAtIndex
= -1; // Index for the current item-range
840 int insertedCount
= 0; // Count for the current item-range
841 int previouslyInsertedCount
= 0; // Sum of previously inserted items for all ranges
842 while (sourceIndex
< sortedItems
.count()) {
843 // Find target index from m_items to insert the current item
845 const int previousTargetIndex
= targetIndex
;
846 while (targetIndex
< m_itemData
.count()) {
847 if (!lessThan(m_itemData
.at(targetIndex
), sortedItems
.at(sourceIndex
))) {
853 if (targetIndex
- previousTargetIndex
> 0 && insertedAtIndex
>= 0) {
854 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
855 previouslyInsertedCount
+= insertedCount
;
856 insertedAtIndex
= targetIndex
- previouslyInsertedCount
;
860 // Insert item at the position targetIndex by transfering
861 // the ownership of the item-data from sortedItems to m_itemData.
862 // m_items will be inserted after the loop (see comment below)
863 m_itemData
.insert(targetIndex
, sortedItems
.at(sourceIndex
));
866 if (insertedAtIndex
< 0) {
867 insertedAtIndex
= targetIndex
;
868 Q_ASSERT(previouslyInsertedCount
== 0);
874 // The indexes of all m_items must be adjusted, not only the index
876 const int itemDataCount
= m_itemData
.count();
877 for (int i
= 0; i
< itemDataCount
; ++i
) {
878 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
881 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
882 emit
itemsInserted(itemRanges
);
884 #ifdef KFILEITEMMODEL_DEBUG
885 kDebug() << "[TIME] Inserting of" << items
.count() << "items:" << timer
.elapsed();
889 void KFileItemModel::removeItems(const KFileItemList
& items
)
891 if (items
.isEmpty()) {
895 #ifdef KFILEITEMMODEL_DEBUG
896 kDebug() << "Removing " << items
.count() << "items";
901 QList
<ItemData
*> sortedItems
= createItemDataList(items
);
902 sort(sortedItems
.begin(), sortedItems
.end());
904 QList
<int> indexesToRemove
;
905 indexesToRemove
.reserve(items
.count());
907 // Calculate the item ranges that will get deleted
908 KItemRangeList itemRanges
;
909 int removedAtIndex
= -1;
910 int removedCount
= 0;
912 foreach (const ItemData
* itemData
, sortedItems
) {
913 const KFileItem
& itemToRemove
= itemData
->item
;
915 const int previousTargetIndex
= targetIndex
;
916 while (targetIndex
< m_itemData
.count()) {
917 if (m_itemData
.at(targetIndex
)->item
.url() == itemToRemove
.url()) {
922 if (targetIndex
>= m_itemData
.count()) {
923 kWarning() << "Item that should be deleted has not been found!";
927 if (targetIndex
- previousTargetIndex
> 0 && removedAtIndex
>= 0) {
928 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
929 removedAtIndex
= targetIndex
;
933 indexesToRemove
.append(targetIndex
);
934 if (removedAtIndex
< 0) {
935 removedAtIndex
= targetIndex
;
940 qDeleteAll(sortedItems
);
944 for (int i
= indexesToRemove
.count() - 1; i
>= 0; --i
) {
945 const int indexToRemove
= indexesToRemove
.at(i
);
946 ItemData
* data
= m_itemData
.at(indexToRemove
);
948 m_items
.remove(data
->item
.url());
951 m_itemData
.removeAt(indexToRemove
);
954 // The indexes of all m_items must be adjusted, not only the index
955 // of the removed items
956 const int itemDataCount
= m_itemData
.count();
957 for (int i
= 0; i
< itemDataCount
; ++i
) {
958 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
962 m_rootExpansionLevel
= -1;
965 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
966 emit
itemsRemoved(itemRanges
);
969 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const KFileItemList
& items
) const
971 QList
<ItemData
*> itemDataList
;
972 itemDataList
.reserve(items
.count());
974 foreach (const KFileItem
& item
, items
) {
975 ItemData
* itemData
= new ItemData();
976 itemData
->item
= item
;
977 itemData
->values
= retrieveData(item
);
978 itemDataList
.append(itemData
);
984 void KFileItemModel::removeExpandedItems()
986 KFileItemList expandedItems
;
988 const int maxIndex
= m_itemData
.count() - 1;
989 for (int i
= 0; i
<= maxIndex
; ++i
) {
990 const ItemData
* itemData
= m_itemData
.at(i
);
991 if (itemData
->values
.value("expansionLevel").toInt() > 0) {
992 expandedItems
.append(itemData
->item
);
996 // The m_rootExpansionLevel may not get reset before all items with
997 // a bigger expansionLevel have been removed.
998 Q_ASSERT(m_rootExpansionLevel
>= 0);
999 removeItems(expandedItems
);
1001 m_rootExpansionLevel
= -1;
1002 m_expandedUrls
.clear();
1005 void KFileItemModel::resetRoles()
1007 for (int i
= 0; i
< RolesCount
; ++i
) {
1008 m_requestRole
[i
] = false;
1012 KFileItemModel::Role
KFileItemModel::roleIndex(const QByteArray
& role
) const
1014 static QHash
<QByteArray
, Role
> rolesHash
;
1015 if (rolesHash
.isEmpty()) {
1016 rolesHash
.insert("name", NameRole
);
1017 rolesHash
.insert("size", SizeRole
);
1018 rolesHash
.insert("date", DateRole
);
1019 rolesHash
.insert("permissions", PermissionsRole
);
1020 rolesHash
.insert("owner", OwnerRole
);
1021 rolesHash
.insert("group", GroupRole
);
1022 rolesHash
.insert("type", TypeRole
);
1023 rolesHash
.insert("destination", DestinationRole
);
1024 rolesHash
.insert("path", PathRole
);
1025 rolesHash
.insert("comment", CommentRole
);
1026 rolesHash
.insert("tags", TagsRole
);
1027 rolesHash
.insert("rating", RatingRole
);
1028 rolesHash
.insert("isDir", IsDirRole
);
1029 rolesHash
.insert("isExpanded", IsExpandedRole
);
1030 rolesHash
.insert("expansionLevel", ExpansionLevelRole
);
1032 return rolesHash
.value(role
, NoRole
);
1035 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
) const
1037 // It is important to insert only roles that are fast to retrieve. E.g.
1038 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1039 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1040 QHash
<QByteArray
, QVariant
> data
;
1041 data
.insert("iconPixmap", QPixmap());
1042 data
.insert("url", item
.url());
1044 const bool isDir
= item
.isDir();
1045 if (m_requestRole
[IsDirRole
]) {
1046 data
.insert("isDir", isDir
);
1049 if (m_requestRole
[NameRole
]) {
1050 data
.insert("name", item
.text());
1053 if (m_requestRole
[SizeRole
]) {
1055 data
.insert("size", QVariant());
1057 data
.insert("size", item
.size());
1061 if (m_requestRole
[DateRole
]) {
1062 // Don't use KFileItem::timeString() as this is too expensive when
1063 // having several thousands of items. Instead the formatting of the
1064 // date-time will be done on-demand by the view when the date will be shown.
1065 const KDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
1066 data
.insert("date", dateTime
.dateTime());
1069 if (m_requestRole
[PermissionsRole
]) {
1070 data
.insert("permissions", item
.permissionsString());
1073 if (m_requestRole
[OwnerRole
]) {
1074 data
.insert("owner", item
.user());
1077 if (m_requestRole
[GroupRole
]) {
1078 data
.insert("group", item
.group());
1081 if (m_requestRole
[DestinationRole
]) {
1082 QString destination
= item
.linkDest();
1083 if (destination
.isEmpty()) {
1084 destination
= i18nc("@item:intable", "No destination");
1086 data
.insert("destination", destination
);
1089 if (m_requestRole
[PathRole
]) {
1090 data
.insert("path", item
.localPath());
1093 if (m_requestRole
[IsExpandedRole
]) {
1094 data
.insert("isExpanded", false);
1097 if (m_requestRole
[ExpansionLevelRole
]) {
1098 if (m_rootExpansionLevel
< 0 && m_dirLister
.data()) {
1099 const QString rootDir
= m_dirLister
.data()->url().directory(KUrl::AppendTrailingSlash
);
1100 m_rootExpansionLevel
= rootDir
.count('/');
1101 if (m_rootExpansionLevel
== 1) {
1102 // Special case: The root is already reached and no parent is available
1103 --m_rootExpansionLevel
;
1106 const QString dir
= item
.url().directory(KUrl::AppendTrailingSlash
);
1107 const int level
= dir
.count('/') - m_rootExpansionLevel
- 1;
1108 data
.insert("expansionLevel", level
);
1111 if (item
.isMimeTypeKnown()) {
1112 data
.insert("iconName", item
.iconName());
1114 if (m_requestRole
[TypeRole
]) {
1115 data
.insert("type", item
.mimeComment());
1122 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
) const
1124 const KFileItem
& itemA
= a
->item
;
1125 const KFileItem
& itemB
= b
->item
;
1129 if (m_rootExpansionLevel
>= 0) {
1130 result
= expansionLevelsCompare(itemA
, itemB
);
1132 // The items have parents with different expansion levels
1133 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1137 if (m_sortFoldersFirst
|| m_sortRole
== SizeRole
) {
1138 const bool isDirA
= itemA
.isDir();
1139 const bool isDirB
= itemB
.isDir();
1140 if (isDirA
&& !isDirB
) {
1142 } else if (!isDirA
&& isDirB
) {
1147 switch (m_sortRole
) {
1149 result
= stringCompare(itemA
.text(), itemB
.text());
1151 // KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1152 result
= stringCompare(itemA
.name(m_caseSensitivity
== Qt::CaseInsensitive
),
1153 itemB
.name(m_caseSensitivity
== Qt::CaseInsensitive
));
1159 const KDateTime dateTimeA
= itemA
.time(KFileItem::ModificationTime
);
1160 const KDateTime dateTimeB
= itemB
.time(KFileItem::ModificationTime
);
1161 if (dateTimeA
< dateTimeB
) {
1163 } else if (dateTimeA
> dateTimeB
) {
1170 if (itemA
.isDir()) {
1171 Q_ASSERT(itemB
.isDir()); // see "if (m_sortFoldersFirst || m_sortRole == SizeRole)" above
1173 const QVariant valueA
= a
->values
.value("size");
1174 const QVariant valueB
= b
->values
.value("size");
1176 if (valueA
.isNull()) {
1178 } else if (valueB
.isNull()) {
1181 result
= valueA
.value
<KIO::filesize_t
>() - valueB
.value
<KIO::filesize_t
>();
1184 Q_ASSERT(!itemB
.isDir()); // see "if (m_sortFoldersFirst || m_sortRole == SizeRole)" above
1185 result
= itemA
.size() - itemB
.size();
1191 result
= QString::compare(a
->values
.value("type").toString(),
1192 b
->values
.value("type").toString());
1197 result
= QString::compare(a
->values
.value("comment").toString(),
1198 b
->values
.value("comment").toString());
1203 result
= QString::compare(a
->values
.value("tags").toString(),
1204 b
->values
.value("tags").toString());
1209 result
= a
->values
.value("rating").toInt() - b
->values
.value("rating").toInt();
1218 // It must be assured that the sort order is always unique even if two values have been
1219 // equal. In this case a comparison of the URL is done which is unique in all cases
1220 // within KDirLister.
1221 result
= QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1224 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1227 void KFileItemModel::sort(QList
<ItemData
*>::iterator begin
,
1228 QList
<ItemData
*>::iterator end
)
1230 // The implementation is based on qStableSortHelper() from qalgorithms.h
1231 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1232 // In opposite to qStableSort() it allows to use a member-function for the comparison of elements.
1234 const int span
= end
- begin
;
1239 const QList
<ItemData
*>::iterator middle
= begin
+ span
/ 2;
1240 sort(begin
, middle
);
1242 merge(begin
, middle
, end
);
1245 void KFileItemModel::merge(QList
<ItemData
*>::iterator begin
,
1246 QList
<ItemData
*>::iterator pivot
,
1247 QList
<ItemData
*>::iterator end
)
1249 // The implementation is based on qMerge() from qalgorithms.h
1250 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1252 const int len1
= pivot
- begin
;
1253 const int len2
= end
- pivot
;
1255 if (len1
== 0 || len2
== 0) {
1259 if (len1
+ len2
== 2) {
1260 if (lessThan(*(begin
+ 1), *(begin
))) {
1261 qSwap(*begin
, *(begin
+ 1));
1266 QList
<ItemData
*>::iterator firstCut
;
1267 QList
<ItemData
*>::iterator secondCut
;
1270 const int len1Half
= len1
/ 2;
1271 firstCut
= begin
+ len1Half
;
1272 secondCut
= lowerBound(pivot
, end
, *firstCut
);
1273 len2Half
= secondCut
- pivot
;
1275 len2Half
= len2
/ 2;
1276 secondCut
= pivot
+ len2Half
;
1277 firstCut
= upperBound(begin
, pivot
, *secondCut
);
1280 reverse(firstCut
, pivot
);
1281 reverse(pivot
, secondCut
);
1282 reverse(firstCut
, secondCut
);
1284 const QList
<ItemData
*>::iterator newPivot
= firstCut
+ len2Half
;
1285 merge(begin
, firstCut
, newPivot
);
1286 merge(newPivot
, secondCut
, end
);
1289 QList
<KFileItemModel::ItemData
*>::iterator
KFileItemModel::lowerBound(QList
<ItemData
*>::iterator begin
,
1290 QList
<ItemData
*>::iterator end
,
1291 const ItemData
* value
)
1293 // The implementation is based on qLowerBound() from qalgorithms.h
1294 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1296 QList
<ItemData
*>::iterator middle
;
1297 int n
= int(end
- begin
);
1302 middle
= begin
+ half
;
1303 if (lessThan(*middle
, value
)) {
1313 QList
<KFileItemModel::ItemData
*>::iterator
KFileItemModel::upperBound(QList
<ItemData
*>::iterator begin
,
1314 QList
<ItemData
*>::iterator end
,
1315 const ItemData
* value
)
1317 // The implementation is based on qUpperBound() from qalgorithms.h
1318 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1320 QList
<ItemData
*>::iterator middle
;
1321 int n
= end
- begin
;
1326 middle
= begin
+ half
;
1327 if (lessThan(value
, *middle
)) {
1337 void KFileItemModel::reverse(QList
<ItemData
*>::iterator begin
,
1338 QList
<ItemData
*>::iterator end
)
1340 // The implementation is based on qReverse() from qalgorithms.h
1341 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1344 while (begin
< end
) {
1345 qSwap(*begin
++, *end
--);
1349 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
) const
1351 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1352 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1353 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1354 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1356 if (m_caseSensitivity
== Qt::CaseInsensitive
) {
1357 const int result
= m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseInsensitive
)
1358 : QString::compare(a
, b
, Qt::CaseInsensitive
);
1360 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1361 // comparison, still a deterministic sort order is required. A case sensitive
1362 // comparison is done as fallback.
1367 return m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseSensitive
)
1368 : QString::compare(a
, b
, Qt::CaseSensitive
);
1371 int KFileItemModel::expansionLevelsCompare(const KFileItem
& a
, const KFileItem
& b
) const
1373 const KUrl urlA
= a
.url();
1374 const KUrl urlB
= b
.url();
1375 if (urlA
.directory() == urlB
.directory()) {
1376 // Both items have the same directory as parent
1380 // Check whether one item is the parent of the other item
1381 if (urlA
.isParentOf(urlB
)) {
1383 } else if (urlB
.isParentOf(urlA
)) {
1387 // Determine the maximum common path of both items and
1388 // remember the index in 'index'
1389 const QString pathA
= urlA
.path();
1390 const QString pathB
= urlB
.path();
1392 const int maxIndex
= qMin(pathA
.length(), pathB
.length()) - 1;
1394 while (index
<= maxIndex
&& pathA
.at(index
) == pathB
.at(index
)) {
1397 if (index
> maxIndex
) {
1400 while ((pathA
.at(index
) != QLatin1Char('/') || pathB
.at(index
) != QLatin1Char('/')) && index
> 0) {
1404 // Determine the first sub-path after the common path and
1405 // check whether it represents a directory or already a file
1407 const QString subPathA
= subPath(a
, pathA
, index
, &isDirA
);
1409 const QString subPathB
= subPath(b
, pathB
, index
, &isDirB
);
1411 if (isDirA
&& !isDirB
) {
1413 } else if (!isDirA
&& isDirB
) {
1417 return stringCompare(subPathA
, subPathB
);
1420 QString
KFileItemModel::subPath(const KFileItem
& item
,
1421 const QString
& itemPath
,
1426 const int pathIndex
= itemPath
.indexOf('/', start
+ 1);
1427 *isDir
= (pathIndex
> 0) || item
.isDir();
1428 return itemPath
.mid(start
, pathIndex
- start
);
1431 bool KFileItemModel::useMaximumUpdateInterval() const
1433 const KDirLister
* dirLister
= m_dirLister
.data();
1434 return dirLister
&& !dirLister
->url().isLocalFile();
1437 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1439 Q_ASSERT(!m_itemData
.isEmpty());
1441 const int maxIndex
= count() - 1;
1442 QList
<QPair
<int, QVariant
> > groups
;
1446 bool isLetter
= false;
1447 for (int i
= 0; i
<= maxIndex
; ++i
) {
1448 if (isChildItem(i
)) {
1452 const QString name
= m_itemData
.at(i
)->values
.value("name").toString();
1454 // Use the first character of the name as group indication
1455 QChar newFirstChar
= name
.at(0).toUpper();
1456 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1457 newFirstChar
= name
.at(1);
1460 if (firstChar
!= newFirstChar
) {
1461 QString newGroupValue
;
1462 if (newFirstChar
>= QLatin1Char('A') && newFirstChar
<= QLatin1Char('Z')) {
1463 // Apply group 'A' - 'Z'
1464 newGroupValue
= newFirstChar
;
1466 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
1467 // Apply group '0 - 9' for any name that starts with a digit
1468 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
1472 // If the current group is 'A' - 'Z' check whether a locale character
1473 // fits into the existing group.
1474 // TODO: This does not work in the case if e.g. the group 'O' starts with
1475 // an umlaut 'O' -> provide unit-test to document this known issue
1476 const QChar
prevChar(firstChar
.unicode() - ushort(1));
1477 const QChar
nextChar(firstChar
.unicode() + ushort(1));
1478 const QString
currChar(newFirstChar
);
1479 const bool partOfCurrentGroup
= currChar
.localeAwareCompare(prevChar
) > 0 &&
1480 currChar
.localeAwareCompare(nextChar
) < 0;
1481 if (partOfCurrentGroup
) {
1485 newGroupValue
= i18nc("@title:group", "Others");
1489 if (newGroupValue
!= groupValue
) {
1490 groupValue
= newGroupValue
;
1491 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1494 firstChar
= newFirstChar
;
1500 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
1502 Q_ASSERT(!m_itemData
.isEmpty());
1504 const int maxIndex
= count() - 1;
1505 QList
<QPair
<int, QVariant
> > groups
;
1508 for (int i
= 0; i
<= maxIndex
; ++i
) {
1509 if (isChildItem(i
)) {
1513 const KFileItem
& item
= m_itemData
.at(i
)->item
;
1514 const KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
1515 QString newGroupValue
;
1516 if (!item
.isNull() && item
.isDir()) {
1517 newGroupValue
= i18nc("@title:group Size", "Folders");
1518 } else if (fileSize
< 5 * 1024 * 1024) {
1519 newGroupValue
= i18nc("@title:group Size", "Small");
1520 } else if (fileSize
< 10 * 1024 * 1024) {
1521 newGroupValue
= i18nc("@title:group Size", "Medium");
1523 newGroupValue
= i18nc("@title:group Size", "Big");
1526 if (newGroupValue
!= groupValue
) {
1527 groupValue
= newGroupValue
;
1528 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1535 QList
<QPair
<int, QVariant
> > KFileItemModel::dateRoleGroups() const
1537 Q_ASSERT(!m_itemData
.isEmpty());
1539 const int maxIndex
= count() - 1;
1540 QList
<QPair
<int, QVariant
> > groups
;
1542 const QDate currentDate
= KDateTime::currentLocalDateTime().date();
1544 int yearForCurrentWeek
= 0;
1545 int currentWeek
= currentDate
.weekNumber(&yearForCurrentWeek
);
1546 if (yearForCurrentWeek
== currentDate
.year() + 1) {
1550 QDate previousModifiedDate
;
1552 for (int i
= 0; i
<= maxIndex
; ++i
) {
1553 if (isChildItem(i
)) {
1557 const KDateTime modifiedTime
= m_itemData
.at(i
)->item
.time(KFileItem::ModificationTime
);
1558 const QDate modifiedDate
= modifiedTime
.date();
1559 if (modifiedDate
== previousModifiedDate
) {
1560 // The current item is in the same group as the previous item
1563 previousModifiedDate
= modifiedDate
;
1565 const int daysDistance
= modifiedDate
.daysTo(currentDate
);
1567 int yearForModifiedWeek
= 0;
1568 int modifiedWeek
= modifiedDate
.weekNumber(&yearForModifiedWeek
);
1569 if (yearForModifiedWeek
== modifiedDate
.year() + 1) {
1573 QString newGroupValue
;
1574 if (currentDate
.year() == modifiedDate
.year() && currentDate
.month() == modifiedDate
.month()) {
1575 if (modifiedWeek
> currentWeek
) {
1576 // Usecase: modified date = 2010-01-01, current date = 2010-01-22
1577 // modified week = 53, current week = 3
1580 switch (currentWeek
- modifiedWeek
) {
1582 switch (daysDistance
) {
1583 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
1584 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
1585 default: newGroupValue
= modifiedTime
.toString(i18nc("@title:group The week day name: %A", "%A"));
1589 newGroupValue
= i18nc("@title:group Date", "Last Week");
1592 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
1595 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
1599 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
1605 const QDate lastMonthDate
= currentDate
.addMonths(-1);
1606 if (lastMonthDate
.year() == modifiedDate
.year() && lastMonthDate
.month() == modifiedDate
.month()) {
1607 if (daysDistance
== 1) {
1608 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Yesterday (%B, %Y)"));
1609 } else if (daysDistance
<= 7) {
1610 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)"));
1611 } else if (daysDistance
<= 7 * 2) {
1612 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)"));
1613 } else if (daysDistance
<= 7 * 3) {
1614 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)"));
1615 } else if (daysDistance
<= 7 * 4) {
1616 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)"));
1618 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"));
1621 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"));
1625 if (newGroupValue
!= groupValue
) {
1626 groupValue
= newGroupValue
;
1627 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1634 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
1636 Q_ASSERT(!m_itemData
.isEmpty());
1638 const int maxIndex
= count() - 1;
1639 QList
<QPair
<int, QVariant
> > groups
;
1641 QString permissionsString
;
1643 for (int i
= 0; i
<= maxIndex
; ++i
) {
1644 if (isChildItem(i
)) {
1648 const ItemData
* itemData
= m_itemData
.at(i
);
1649 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
1650 if (newPermissionsString
== permissionsString
) {
1653 permissionsString
= newPermissionsString
;
1655 const QFileInfo
info(itemData
->item
.url().pathOrUrl());
1659 if (info
.permission(QFile::ReadUser
)) {
1660 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1662 if (info
.permission(QFile::WriteUser
)) {
1663 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1665 if (info
.permission(QFile::ExeUser
)) {
1666 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1668 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
1672 if (info
.permission(QFile::ReadGroup
)) {
1673 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1675 if (info
.permission(QFile::WriteGroup
)) {
1676 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1678 if (info
.permission(QFile::ExeGroup
)) {
1679 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1681 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
1683 // Set others string
1685 if (info
.permission(QFile::ReadOther
)) {
1686 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1688 if (info
.permission(QFile::WriteOther
)) {
1689 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1691 if (info
.permission(QFile::ExeOther
)) {
1692 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1694 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
1696 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
1697 if (newGroupValue
!= groupValue
) {
1698 groupValue
= newGroupValue
;
1699 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1706 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
1708 Q_ASSERT(!m_itemData
.isEmpty());
1710 const int maxIndex
= count() - 1;
1711 QList
<QPair
<int, QVariant
> > groups
;
1714 for (int i
= 0; i
<= maxIndex
; ++i
) {
1715 if (isChildItem(i
)) {
1718 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating").toInt();
1719 if (newGroupValue
!= groupValue
) {
1720 groupValue
= newGroupValue
;
1721 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1728 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
1730 Q_ASSERT(!m_itemData
.isEmpty());
1732 const int maxIndex
= count() - 1;
1733 QList
<QPair
<int, QVariant
> > groups
;
1736 for (int i
= 0; i
<= maxIndex
; ++i
) {
1737 if (isChildItem(i
)) {
1740 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
1741 if (newGroupValue
!= groupValue
) {
1742 groupValue
= newGroupValue
;
1743 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1750 bool KFileItemModel::matchesNameFilter(const KFileItem
& item
) const
1752 // TODO #1: A performance improvement would be possible by caching m_nameFilter.toLower().
1753 // Before adding yet-another-member it should be checked whether it brings a noticable
1754 // improvement at all.
1756 // TODO #2: If the user entered a '*' use a regular expression
1757 const QString itemText
= item
.text().toLower();
1758 return itemText
.contains(m_nameFilter
.toLower());
1761 #include "kfileitemmodel.moc"