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 KDirLister
* dirLister
= m_dirLister
.data();
408 const KUrl url
= m_itemData
.at(index
)->item
.url();
410 m_expandedUrls
.insert(url
);
413 dirLister
->openUrl(url
, KDirLister::Keep
);
417 m_expandedUrls
.remove(url
);
420 dirLister
->stop(url
);
423 KFileItemList itemsToRemove
;
424 const int expansionLevel
= data(index
)["expansionLevel"].toInt();
426 while (index
< count() && data(index
)["expansionLevel"].toInt() > expansionLevel
) {
427 itemsToRemove
.append(m_itemData
.at(index
)->item
);
430 removeItems(itemsToRemove
);
437 bool KFileItemModel::isExpanded(int index
) const
439 if (index
>= 0 && index
< count()) {
440 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
445 bool KFileItemModel::isExpandable(int index
) const
447 if (index
>= 0 && index
< count()) {
448 return m_itemData
.at(index
)->item
.isDir();
453 QSet
<KUrl
> KFileItemModel::expandedUrls() const
455 return m_expandedUrls
;
458 void KFileItemModel::restoreExpandedUrls(const QSet
<KUrl
>& urls
)
460 m_urlsToExpand
= urls
;
463 void KFileItemModel::setExpanded(const QSet
<KUrl
>& urls
)
466 const KDirLister
* dirLister
= m_dirLister
.data();
471 const int pos
= dirLister
->url().url().length();
473 // Assure that each sub-path of the URLs that should be
474 // expanded is added to m_urlsToExpand too. KDirLister
475 // does not care whether the parent-URL has already been
477 QSetIterator
<KUrl
> it1(urls
);
478 while (it1
.hasNext()) {
479 const KUrl
& url
= it1
.next();
481 KUrl urlToExpand
= dirLister
->url();
482 const QStringList subDirs
= url
.url().mid(pos
).split(QDir::separator());
483 for (int i
= 0; i
< subDirs
.count(); ++i
) {
484 urlToExpand
.addPath(subDirs
.at(i
));
485 m_urlsToExpand
.insert(urlToExpand
);
489 // KDirLister::open() must called at least once to trigger an initial
490 // loading. The pending URLs that must be restored are handled
491 // in slotCompleted().
492 QSetIterator
<KUrl
> it2(m_urlsToExpand
);
493 while (it2
.hasNext()) {
494 const int idx
= index(it2
.next());
495 if (idx
>= 0 && !isExpanded(idx
)) {
496 setExpanded(idx
, true);
502 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
504 if (m_nameFilter
!= nameFilter
) {
505 dispatchPendingItemsToInsert();
507 m_nameFilter
= nameFilter
;
509 // Check which shown items from m_itemData must get
510 // hidden and hence moved to m_filteredItems.
511 KFileItemList newFilteredItems
;
513 foreach (ItemData
* itemData
, m_itemData
) {
514 if (!matchesNameFilter(itemData
->item
)) {
515 newFilteredItems
.append(itemData
->item
);
516 m_filteredItems
.insert(itemData
->item
);
520 removeItems(newFilteredItems
);
522 // Check which hidden items from m_filteredItems should
523 // get visible again and hence removed from m_filteredItems.
524 KFileItemList newVisibleItems
;
526 QMutableSetIterator
<KFileItem
> it(m_filteredItems
);
527 while (it
.hasNext()) {
528 const KFileItem item
= it
.next();
529 if (matchesNameFilter(item
)) {
530 newVisibleItems
.append(item
);
531 m_filteredItems
.remove(item
);
535 insertItems(newVisibleItems
);
539 QString
KFileItemModel::nameFilter() const
544 void KFileItemModel::onGroupedSortingChanged(bool current
)
550 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
553 m_sortRole
= roleIndex(current
);
555 #ifdef KFILEITEMMODEL_DEBUG
556 if (!m_requestRole
[m_sortRole
]) {
557 kWarning() << "The sort-role has been changed to a role that has not been received yet";
564 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
571 void KFileItemModel::resortAllItems()
573 m_resortAllItemsTimer
->stop();
575 const int itemCount
= count();
576 if (itemCount
<= 0) {
580 #ifdef KFILEITEMMODEL_DEBUG
583 kDebug() << "===========================================================";
584 kDebug() << "Resorting" << itemCount
<< "items";
587 // Remember the order of the current URLs so
588 // that it can be determined which indexes have
589 // been moved because of the resorting.
591 oldUrls
.reserve(itemCount
);
592 foreach (const ItemData
* itemData
, m_itemData
) {
593 oldUrls
.append(itemData
->item
.url());
600 sort(m_itemData
.begin(), m_itemData
.end());
601 for (int i
= 0; i
< itemCount
; ++i
) {
602 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
605 // Determine the indexes that have been moved
606 bool emitItemsMoved
= false;
607 QList
<int> movedToIndexes
;
608 movedToIndexes
.reserve(itemCount
);
609 for (int i
= 0; i
< itemCount
; i
++) {
610 const int newIndex
= m_items
.value(oldUrls
.at(i
).url());
611 movedToIndexes
.append(newIndex
);
612 if (!emitItemsMoved
&& newIndex
!= i
) {
613 emitItemsMoved
= true;
617 if (emitItemsMoved
) {
618 emit
itemsMoved(KItemRange(0, itemCount
), movedToIndexes
);
621 #ifdef KFILEITEMMODEL_DEBUG
622 kDebug() << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
626 void KFileItemModel::slotCompleted()
628 if (m_urlsToExpand
.isEmpty() && m_minimumUpdateIntervalTimer
->isActive()) {
629 // dispatchPendingItems() will be called when the timer
631 m_pendingEmitLoadingCompleted
= true;
635 m_pendingEmitLoadingCompleted
= false;
636 dispatchPendingItemsToInsert();
638 if (!m_urlsToExpand
.isEmpty()) {
639 // Try to find a URL that can be expanded.
640 // Note that the parent folder must be expanded before any of its subfolders become visible.
641 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
642 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
643 foreach(const KUrl
& url
, m_urlsToExpand
) {
644 const int index
= m_items
.value(url
, -1);
646 m_urlsToExpand
.remove(url
);
647 if (setExpanded(index
, true)) {
648 // The dir lister has been triggered. This slot will be called
649 // again after the directory has been expanded.
655 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
656 // if these URLs have been deleted in the meantime.
657 m_urlsToExpand
.clear();
660 emit
loadingCompleted();
661 m_minimumUpdateIntervalTimer
->start();
664 void KFileItemModel::slotCanceled()
666 m_minimumUpdateIntervalTimer
->stop();
667 m_maximumUpdateIntervalTimer
->stop();
668 dispatchPendingItemsToInsert();
671 void KFileItemModel::slotNewItems(const KFileItemList
& items
)
673 if (m_requestRole
[ExpansionLevelRole
] && m_rootExpansionLevel
>= 0) {
674 // If the expanding of items is enabled in the model, it might be
675 // possible that the call dirLister->openUrl(url, KDirLister::Keep) in
676 // KFileItemModel::setExpanded() results in emitting of the same items
677 // twice due to the Keep-parameter. This case happens if an item gets
678 // expanded, collapsed and expanded again before the items could be loaded
679 // for the first expansion.
680 foreach (const KFileItem
& item
, items
) {
681 const int index
= m_items
.value(item
.url(), -1);
683 // The items are already part of the model.
689 if (m_nameFilter
.isEmpty()) {
690 m_pendingItemsToInsert
.append(items
);
692 // The name-filter is active. Hide filtered items
693 // before inserting them into the model and remember
694 // the filtered items in m_filteredItems.
695 KFileItemList filteredItems
;
696 foreach (const KFileItem
& item
, items
) {
697 if (matchesNameFilter(item
)) {
698 filteredItems
.append(item
);
700 m_filteredItems
.insert(item
);
704 m_pendingItemsToInsert
.append(filteredItems
);
707 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer
->isActive()) {
708 // Assure that items get dispatched if no completed() or canceled() signal is
709 // emitted during the maximum update interval.
710 m_maximumUpdateIntervalTimer
->start();
714 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
716 dispatchPendingItemsToInsert();
718 if (!m_filteredItems
.isEmpty()) {
719 foreach (const KFileItem
& item
, items
) {
720 m_filteredItems
.remove(item
);
727 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
729 Q_ASSERT(!items
.isEmpty());
730 #ifdef KFILEITEMMODEL_DEBUG
731 kDebug() << "Refreshing" << items
.count() << "items";
736 // Get the indexes of all items that have been refreshed
738 indexes
.reserve(items
.count());
740 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
741 while (it
.hasNext()) {
742 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
743 const KFileItem
& oldItem
= itemPair
.first
;
744 const KFileItem
& newItem
= itemPair
.second
;
745 const int index
= m_items
.value(oldItem
.url(), -1);
747 m_itemData
[index
]->item
= newItem
;
748 m_itemData
[index
]->values
= retrieveData(newItem
);
749 m_items
.remove(oldItem
.url());
750 m_items
.insert(newItem
.url(), index
);
751 indexes
.append(index
);
755 // If the changed items have been created recently, they might not be in m_items yet.
756 // In that case, the list 'indexes' might be empty.
757 if (indexes
.isEmpty()) {
761 // Extract the item-ranges out of the changed indexes
764 KItemRangeList itemRangeList
;
765 int previousIndex
= indexes
.at(0);
766 int rangeIndex
= previousIndex
;
769 const int maxIndex
= indexes
.count() - 1;
770 for (int i
= 1; i
<= maxIndex
; ++i
) {
771 const int currentIndex
= indexes
.at(i
);
772 if (currentIndex
== previousIndex
+ 1) {
775 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
777 rangeIndex
= currentIndex
;
780 previousIndex
= currentIndex
;
783 if (rangeCount
> 0) {
784 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
787 emit
itemsChanged(itemRangeList
, m_roles
);
790 void KFileItemModel::slotClear()
792 #ifdef KFILEITEMMODEL_DEBUG
793 kDebug() << "Clearing all items";
796 m_filteredItems
.clear();
799 m_minimumUpdateIntervalTimer
->stop();
800 m_maximumUpdateIntervalTimer
->stop();
801 m_resortAllItemsTimer
->stop();
802 m_pendingItemsToInsert
.clear();
804 m_rootExpansionLevel
= -1;
806 const int removedCount
= m_itemData
.count();
807 if (removedCount
> 0) {
808 qDeleteAll(m_itemData
);
811 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
814 m_expandedUrls
.clear();
817 void KFileItemModel::slotClear(const KUrl
& url
)
822 void KFileItemModel::dispatchPendingItemsToInsert()
824 if (!m_pendingItemsToInsert
.isEmpty()) {
825 insertItems(m_pendingItemsToInsert
);
826 m_pendingItemsToInsert
.clear();
829 if (m_pendingEmitLoadingCompleted
) {
830 emit
loadingCompleted();
834 void KFileItemModel::insertItems(const KFileItemList
& items
)
836 if (items
.isEmpty()) {
840 #ifdef KFILEITEMMODEL_DEBUG
843 kDebug() << "===========================================================";
844 kDebug() << "Inserting" << items
.count() << "items";
849 QList
<ItemData
*> sortedItems
= createItemDataList(items
);
850 sort(sortedItems
.begin(), sortedItems
.end());
852 #ifdef KFILEITEMMODEL_DEBUG
853 kDebug() << "[TIME] Sorting:" << timer
.elapsed();
856 KItemRangeList itemRanges
;
859 int insertedAtIndex
= -1; // Index for the current item-range
860 int insertedCount
= 0; // Count for the current item-range
861 int previouslyInsertedCount
= 0; // Sum of previously inserted items for all ranges
862 while (sourceIndex
< sortedItems
.count()) {
863 // Find target index from m_items to insert the current item
865 const int previousTargetIndex
= targetIndex
;
866 while (targetIndex
< m_itemData
.count()) {
867 if (!lessThan(m_itemData
.at(targetIndex
), sortedItems
.at(sourceIndex
))) {
873 if (targetIndex
- previousTargetIndex
> 0 && insertedAtIndex
>= 0) {
874 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
875 previouslyInsertedCount
+= insertedCount
;
876 insertedAtIndex
= targetIndex
- previouslyInsertedCount
;
880 // Insert item at the position targetIndex by transfering
881 // the ownership of the item-data from sortedItems to m_itemData.
882 // m_items will be inserted after the loop (see comment below)
883 m_itemData
.insert(targetIndex
, sortedItems
.at(sourceIndex
));
886 if (insertedAtIndex
< 0) {
887 insertedAtIndex
= targetIndex
;
888 Q_ASSERT(previouslyInsertedCount
== 0);
894 // The indexes of all m_items must be adjusted, not only the index
896 const int itemDataCount
= m_itemData
.count();
897 for (int i
= 0; i
< itemDataCount
; ++i
) {
898 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
901 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
902 emit
itemsInserted(itemRanges
);
904 #ifdef KFILEITEMMODEL_DEBUG
905 kDebug() << "[TIME] Inserting of" << items
.count() << "items:" << timer
.elapsed();
909 void KFileItemModel::removeItems(const KFileItemList
& items
)
911 if (items
.isEmpty()) {
915 #ifdef KFILEITEMMODEL_DEBUG
916 kDebug() << "Removing " << items
.count() << "items";
921 QList
<ItemData
*> sortedItems
= createItemDataList(items
);
922 sort(sortedItems
.begin(), sortedItems
.end());
924 QList
<int> indexesToRemove
;
925 indexesToRemove
.reserve(items
.count());
927 // Calculate the item ranges that will get deleted
928 KItemRangeList itemRanges
;
929 int removedAtIndex
= -1;
930 int removedCount
= 0;
932 foreach (const ItemData
* itemData
, sortedItems
) {
933 const KFileItem
& itemToRemove
= itemData
->item
;
935 const int previousTargetIndex
= targetIndex
;
936 while (targetIndex
< m_itemData
.count()) {
937 if (m_itemData
.at(targetIndex
)->item
.url() == itemToRemove
.url()) {
942 if (targetIndex
>= m_itemData
.count()) {
943 kWarning() << "Item that should be deleted has not been found!";
947 if (targetIndex
- previousTargetIndex
> 0 && removedAtIndex
>= 0) {
948 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
949 removedAtIndex
= targetIndex
;
953 indexesToRemove
.append(targetIndex
);
954 if (removedAtIndex
< 0) {
955 removedAtIndex
= targetIndex
;
960 qDeleteAll(sortedItems
);
964 for (int i
= indexesToRemove
.count() - 1; i
>= 0; --i
) {
965 const int indexToRemove
= indexesToRemove
.at(i
);
966 ItemData
* data
= m_itemData
.at(indexToRemove
);
968 m_items
.remove(data
->item
.url());
971 m_itemData
.removeAt(indexToRemove
);
974 // The indexes of all m_items must be adjusted, not only the index
975 // of the removed items
976 const int itemDataCount
= m_itemData
.count();
977 for (int i
= 0; i
< itemDataCount
; ++i
) {
978 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
982 m_rootExpansionLevel
= -1;
985 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
986 emit
itemsRemoved(itemRanges
);
989 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const KFileItemList
& items
) const
991 QList
<ItemData
*> itemDataList
;
992 itemDataList
.reserve(items
.count());
994 foreach (const KFileItem
& item
, items
) {
995 ItemData
* itemData
= new ItemData();
996 itemData
->item
= item
;
997 itemData
->values
= retrieveData(item
);
998 itemDataList
.append(itemData
);
1001 return itemDataList
;
1004 void KFileItemModel::removeExpandedItems()
1006 KFileItemList expandedItems
;
1008 const int maxIndex
= m_itemData
.count() - 1;
1009 for (int i
= 0; i
<= maxIndex
; ++i
) {
1010 const ItemData
* itemData
= m_itemData
.at(i
);
1011 if (itemData
->values
.value("expansionLevel").toInt() > 0) {
1012 expandedItems
.append(itemData
->item
);
1016 // The m_rootExpansionLevel may not get reset before all items with
1017 // a bigger expansionLevel have been removed.
1018 Q_ASSERT(m_rootExpansionLevel
>= 0);
1019 removeItems(expandedItems
);
1021 m_rootExpansionLevel
= -1;
1022 m_expandedUrls
.clear();
1025 void KFileItemModel::resetRoles()
1027 for (int i
= 0; i
< RolesCount
; ++i
) {
1028 m_requestRole
[i
] = false;
1032 KFileItemModel::Role
KFileItemModel::roleIndex(const QByteArray
& role
) const
1034 static QHash
<QByteArray
, Role
> rolesHash
;
1035 if (rolesHash
.isEmpty()) {
1036 rolesHash
.insert("name", NameRole
);
1037 rolesHash
.insert("size", SizeRole
);
1038 rolesHash
.insert("date", DateRole
);
1039 rolesHash
.insert("permissions", PermissionsRole
);
1040 rolesHash
.insert("owner", OwnerRole
);
1041 rolesHash
.insert("group", GroupRole
);
1042 rolesHash
.insert("type", TypeRole
);
1043 rolesHash
.insert("destination", DestinationRole
);
1044 rolesHash
.insert("path", PathRole
);
1045 rolesHash
.insert("comment", CommentRole
);
1046 rolesHash
.insert("tags", TagsRole
);
1047 rolesHash
.insert("rating", RatingRole
);
1048 rolesHash
.insert("isDir", IsDirRole
);
1049 rolesHash
.insert("isExpanded", IsExpandedRole
);
1050 rolesHash
.insert("expansionLevel", ExpansionLevelRole
);
1052 return rolesHash
.value(role
, NoRole
);
1055 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
) const
1057 // It is important to insert only roles that are fast to retrieve. E.g.
1058 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1059 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1060 QHash
<QByteArray
, QVariant
> data
;
1061 data
.insert("iconPixmap", QPixmap());
1062 data
.insert("url", item
.url());
1064 const bool isDir
= item
.isDir();
1065 if (m_requestRole
[IsDirRole
]) {
1066 data
.insert("isDir", isDir
);
1069 if (m_requestRole
[NameRole
]) {
1070 data
.insert("name", item
.text());
1073 if (m_requestRole
[SizeRole
]) {
1075 data
.insert("size", QVariant());
1077 data
.insert("size", item
.size());
1081 if (m_requestRole
[DateRole
]) {
1082 // Don't use KFileItem::timeString() as this is too expensive when
1083 // having several thousands of items. Instead the formatting of the
1084 // date-time will be done on-demand by the view when the date will be shown.
1085 const KDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
1086 data
.insert("date", dateTime
.dateTime());
1089 if (m_requestRole
[PermissionsRole
]) {
1090 data
.insert("permissions", item
.permissionsString());
1093 if (m_requestRole
[OwnerRole
]) {
1094 data
.insert("owner", item
.user());
1097 if (m_requestRole
[GroupRole
]) {
1098 data
.insert("group", item
.group());
1101 if (m_requestRole
[DestinationRole
]) {
1102 QString destination
= item
.linkDest();
1103 if (destination
.isEmpty()) {
1104 destination
= i18nc("@item:intable", "No destination");
1106 data
.insert("destination", destination
);
1109 if (m_requestRole
[PathRole
]) {
1110 data
.insert("path", item
.localPath());
1113 if (m_requestRole
[IsExpandedRole
]) {
1114 data
.insert("isExpanded", false);
1117 if (m_requestRole
[ExpansionLevelRole
]) {
1118 if (m_rootExpansionLevel
< 0 && m_dirLister
.data()) {
1119 const QString rootDir
= m_dirLister
.data()->url().directory(KUrl::AppendTrailingSlash
);
1120 m_rootExpansionLevel
= rootDir
.count('/');
1121 if (m_rootExpansionLevel
== 1) {
1122 // Special case: The root is already reached and no parent is available
1123 --m_rootExpansionLevel
;
1126 const QString dir
= item
.url().directory(KUrl::AppendTrailingSlash
);
1127 const int level
= dir
.count('/') - m_rootExpansionLevel
- 1;
1128 data
.insert("expansionLevel", level
);
1131 if (item
.isMimeTypeKnown()) {
1132 data
.insert("iconName", item
.iconName());
1134 if (m_requestRole
[TypeRole
]) {
1135 data
.insert("type", item
.mimeComment());
1142 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
) const
1144 const KFileItem
& itemA
= a
->item
;
1145 const KFileItem
& itemB
= b
->item
;
1149 if (m_rootExpansionLevel
>= 0) {
1150 result
= expansionLevelsCompare(itemA
, itemB
);
1152 // The items have parents with different expansion levels
1153 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1157 if (m_sortFoldersFirst
|| m_sortRole
== SizeRole
) {
1158 const bool isDirA
= itemA
.isDir();
1159 const bool isDirB
= itemB
.isDir();
1160 if (isDirA
&& !isDirB
) {
1162 } else if (!isDirA
&& isDirB
) {
1167 switch (m_sortRole
) {
1169 result
= stringCompare(itemA
.text(), itemB
.text());
1171 // KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1172 result
= stringCompare(itemA
.name(m_caseSensitivity
== Qt::CaseInsensitive
),
1173 itemB
.name(m_caseSensitivity
== Qt::CaseInsensitive
));
1179 const KDateTime dateTimeA
= itemA
.time(KFileItem::ModificationTime
);
1180 const KDateTime dateTimeB
= itemB
.time(KFileItem::ModificationTime
);
1181 if (dateTimeA
< dateTimeB
) {
1183 } else if (dateTimeA
> dateTimeB
) {
1190 if (itemA
.isDir()) {
1191 Q_ASSERT(itemB
.isDir()); // see "if (m_sortFoldersFirst || m_sortRole == SizeRole)" above
1193 const QVariant valueA
= a
->values
.value("size");
1194 const QVariant valueB
= b
->values
.value("size");
1196 if (valueA
.isNull()) {
1198 } else if (valueB
.isNull()) {
1201 result
= valueA
.value
<KIO::filesize_t
>() - valueB
.value
<KIO::filesize_t
>();
1204 Q_ASSERT(!itemB
.isDir()); // see "if (m_sortFoldersFirst || m_sortRole == SizeRole)" above
1205 result
= itemA
.size() - itemB
.size();
1211 result
= QString::compare(a
->values
.value("type").toString(),
1212 b
->values
.value("type").toString());
1217 result
= QString::compare(a
->values
.value("comment").toString(),
1218 b
->values
.value("comment").toString());
1223 result
= QString::compare(a
->values
.value("tags").toString(),
1224 b
->values
.value("tags").toString());
1229 result
= a
->values
.value("rating").toInt() - b
->values
.value("rating").toInt();
1238 // It must be assured that the sort order is always unique even if two values have been
1239 // equal. In this case a comparison of the URL is done which is unique in all cases
1240 // within KDirLister.
1241 result
= QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1244 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1247 void KFileItemModel::sort(QList
<ItemData
*>::iterator begin
,
1248 QList
<ItemData
*>::iterator end
)
1250 // The implementation is based on qStableSortHelper() from qalgorithms.h
1251 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1252 // In opposite to qStableSort() it allows to use a member-function for the comparison of elements.
1254 const int span
= end
- begin
;
1259 const QList
<ItemData
*>::iterator middle
= begin
+ span
/ 2;
1260 sort(begin
, middle
);
1262 merge(begin
, middle
, end
);
1265 void KFileItemModel::merge(QList
<ItemData
*>::iterator begin
,
1266 QList
<ItemData
*>::iterator pivot
,
1267 QList
<ItemData
*>::iterator end
)
1269 // The implementation is based on qMerge() from qalgorithms.h
1270 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1272 const int len1
= pivot
- begin
;
1273 const int len2
= end
- pivot
;
1275 if (len1
== 0 || len2
== 0) {
1279 if (len1
+ len2
== 2) {
1280 if (lessThan(*(begin
+ 1), *(begin
))) {
1281 qSwap(*begin
, *(begin
+ 1));
1286 QList
<ItemData
*>::iterator firstCut
;
1287 QList
<ItemData
*>::iterator secondCut
;
1290 const int len1Half
= len1
/ 2;
1291 firstCut
= begin
+ len1Half
;
1292 secondCut
= lowerBound(pivot
, end
, *firstCut
);
1293 len2Half
= secondCut
- pivot
;
1295 len2Half
= len2
/ 2;
1296 secondCut
= pivot
+ len2Half
;
1297 firstCut
= upperBound(begin
, pivot
, *secondCut
);
1300 reverse(firstCut
, pivot
);
1301 reverse(pivot
, secondCut
);
1302 reverse(firstCut
, secondCut
);
1304 const QList
<ItemData
*>::iterator newPivot
= firstCut
+ len2Half
;
1305 merge(begin
, firstCut
, newPivot
);
1306 merge(newPivot
, secondCut
, end
);
1309 QList
<KFileItemModel::ItemData
*>::iterator
KFileItemModel::lowerBound(QList
<ItemData
*>::iterator begin
,
1310 QList
<ItemData
*>::iterator end
,
1311 const ItemData
* value
)
1313 // The implementation is based on qLowerBound() from qalgorithms.h
1314 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1316 QList
<ItemData
*>::iterator middle
;
1317 int n
= int(end
- begin
);
1322 middle
= begin
+ half
;
1323 if (lessThan(*middle
, value
)) {
1333 QList
<KFileItemModel::ItemData
*>::iterator
KFileItemModel::upperBound(QList
<ItemData
*>::iterator begin
,
1334 QList
<ItemData
*>::iterator end
,
1335 const ItemData
* value
)
1337 // The implementation is based on qUpperBound() from qalgorithms.h
1338 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1340 QList
<ItemData
*>::iterator middle
;
1341 int n
= end
- begin
;
1346 middle
= begin
+ half
;
1347 if (lessThan(value
, *middle
)) {
1357 void KFileItemModel::reverse(QList
<ItemData
*>::iterator begin
,
1358 QList
<ItemData
*>::iterator end
)
1360 // The implementation is based on qReverse() from qalgorithms.h
1361 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1364 while (begin
< end
) {
1365 qSwap(*begin
++, *end
--);
1369 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
) const
1371 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1372 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1373 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1374 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1376 if (m_caseSensitivity
== Qt::CaseInsensitive
) {
1377 const int result
= m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseInsensitive
)
1378 : QString::compare(a
, b
, Qt::CaseInsensitive
);
1380 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1381 // comparison, still a deterministic sort order is required. A case sensitive
1382 // comparison is done as fallback.
1387 return m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseSensitive
)
1388 : QString::compare(a
, b
, Qt::CaseSensitive
);
1391 int KFileItemModel::expansionLevelsCompare(const KFileItem
& a
, const KFileItem
& b
) const
1393 const KUrl urlA
= a
.url();
1394 const KUrl urlB
= b
.url();
1395 if (urlA
.directory() == urlB
.directory()) {
1396 // Both items have the same directory as parent
1400 // Check whether one item is the parent of the other item
1401 if (urlA
.isParentOf(urlB
)) {
1403 } else if (urlB
.isParentOf(urlA
)) {
1407 // Determine the maximum common path of both items and
1408 // remember the index in 'index'
1409 const QString pathA
= urlA
.path();
1410 const QString pathB
= urlB
.path();
1412 const int maxIndex
= qMin(pathA
.length(), pathB
.length()) - 1;
1414 while (index
<= maxIndex
&& pathA
.at(index
) == pathB
.at(index
)) {
1417 if (index
> maxIndex
) {
1420 while ((pathA
.at(index
) != QLatin1Char('/') || pathB
.at(index
) != QLatin1Char('/')) && index
> 0) {
1424 // Determine the first sub-path after the common path and
1425 // check whether it represents a directory or already a file
1427 const QString subPathA
= subPath(a
, pathA
, index
, &isDirA
);
1429 const QString subPathB
= subPath(b
, pathB
, index
, &isDirB
);
1431 if (isDirA
&& !isDirB
) {
1433 } else if (!isDirA
&& isDirB
) {
1437 return stringCompare(subPathA
, subPathB
);
1440 QString
KFileItemModel::subPath(const KFileItem
& item
,
1441 const QString
& itemPath
,
1446 const int pathIndex
= itemPath
.indexOf('/', start
+ 1);
1447 *isDir
= (pathIndex
> 0) || item
.isDir();
1448 return itemPath
.mid(start
, pathIndex
- start
);
1451 bool KFileItemModel::useMaximumUpdateInterval() const
1453 const KDirLister
* dirLister
= m_dirLister
.data();
1454 return dirLister
&& !dirLister
->url().isLocalFile();
1457 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1459 Q_ASSERT(!m_itemData
.isEmpty());
1461 const int maxIndex
= count() - 1;
1462 QList
<QPair
<int, QVariant
> > groups
;
1466 bool isLetter
= false;
1467 for (int i
= 0; i
<= maxIndex
; ++i
) {
1468 if (isChildItem(i
)) {
1472 const QString name
= m_itemData
.at(i
)->values
.value("name").toString();
1474 // Use the first character of the name as group indication
1475 QChar newFirstChar
= name
.at(0).toUpper();
1476 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1477 newFirstChar
= name
.at(1);
1480 if (firstChar
!= newFirstChar
) {
1481 QString newGroupValue
;
1482 if (newFirstChar
>= QLatin1Char('A') && newFirstChar
<= QLatin1Char('Z')) {
1483 // Apply group 'A' - 'Z'
1484 newGroupValue
= newFirstChar
;
1486 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
1487 // Apply group '0 - 9' for any name that starts with a digit
1488 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
1492 // If the current group is 'A' - 'Z' check whether a locale character
1493 // fits into the existing group.
1494 // TODO: This does not work in the case if e.g. the group 'O' starts with
1495 // an umlaut 'O' -> provide unit-test to document this known issue
1496 const QChar
prevChar(firstChar
.unicode() - ushort(1));
1497 const QChar
nextChar(firstChar
.unicode() + ushort(1));
1498 const QString
currChar(newFirstChar
);
1499 const bool partOfCurrentGroup
= currChar
.localeAwareCompare(prevChar
) > 0 &&
1500 currChar
.localeAwareCompare(nextChar
) < 0;
1501 if (partOfCurrentGroup
) {
1505 newGroupValue
= i18nc("@title:group", "Others");
1509 if (newGroupValue
!= groupValue
) {
1510 groupValue
= newGroupValue
;
1511 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1514 firstChar
= newFirstChar
;
1520 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
1522 Q_ASSERT(!m_itemData
.isEmpty());
1524 const int maxIndex
= count() - 1;
1525 QList
<QPair
<int, QVariant
> > groups
;
1528 for (int i
= 0; i
<= maxIndex
; ++i
) {
1529 if (isChildItem(i
)) {
1533 const KFileItem
& item
= m_itemData
.at(i
)->item
;
1534 const KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
1535 QString newGroupValue
;
1536 if (!item
.isNull() && item
.isDir()) {
1537 newGroupValue
= i18nc("@title:group Size", "Folders");
1538 } else if (fileSize
< 5 * 1024 * 1024) {
1539 newGroupValue
= i18nc("@title:group Size", "Small");
1540 } else if (fileSize
< 10 * 1024 * 1024) {
1541 newGroupValue
= i18nc("@title:group Size", "Medium");
1543 newGroupValue
= i18nc("@title:group Size", "Big");
1546 if (newGroupValue
!= groupValue
) {
1547 groupValue
= newGroupValue
;
1548 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1555 QList
<QPair
<int, QVariant
> > KFileItemModel::dateRoleGroups() const
1557 Q_ASSERT(!m_itemData
.isEmpty());
1559 const int maxIndex
= count() - 1;
1560 QList
<QPair
<int, QVariant
> > groups
;
1562 const QDate currentDate
= KDateTime::currentLocalDateTime().date();
1564 int yearForCurrentWeek
= 0;
1565 int currentWeek
= currentDate
.weekNumber(&yearForCurrentWeek
);
1566 if (yearForCurrentWeek
== currentDate
.year() + 1) {
1570 QDate previousModifiedDate
;
1572 for (int i
= 0; i
<= maxIndex
; ++i
) {
1573 if (isChildItem(i
)) {
1577 const KDateTime modifiedTime
= m_itemData
.at(i
)->item
.time(KFileItem::ModificationTime
);
1578 const QDate modifiedDate
= modifiedTime
.date();
1579 if (modifiedDate
== previousModifiedDate
) {
1580 // The current item is in the same group as the previous item
1583 previousModifiedDate
= modifiedDate
;
1585 const int daysDistance
= modifiedDate
.daysTo(currentDate
);
1587 int yearForModifiedWeek
= 0;
1588 int modifiedWeek
= modifiedDate
.weekNumber(&yearForModifiedWeek
);
1589 if (yearForModifiedWeek
== modifiedDate
.year() + 1) {
1593 QString newGroupValue
;
1594 if (currentDate
.year() == modifiedDate
.year() && currentDate
.month() == modifiedDate
.month()) {
1595 if (modifiedWeek
> currentWeek
) {
1596 // Usecase: modified date = 2010-01-01, current date = 2010-01-22
1597 // modified week = 53, current week = 3
1600 switch (currentWeek
- modifiedWeek
) {
1602 switch (daysDistance
) {
1603 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
1604 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
1605 default: newGroupValue
= modifiedTime
.toString(i18nc("@title:group The week day name: %A", "%A"));
1609 newGroupValue
= i18nc("@title:group Date", "Last Week");
1612 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
1615 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
1619 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
1625 const QDate lastMonthDate
= currentDate
.addMonths(-1);
1626 if (lastMonthDate
.year() == modifiedDate
.year() && lastMonthDate
.month() == modifiedDate
.month()) {
1627 if (daysDistance
== 1) {
1628 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Yesterday (%B, %Y)"));
1629 } else if (daysDistance
<= 7) {
1630 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)"));
1631 } else if (daysDistance
<= 7 * 2) {
1632 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)"));
1633 } else if (daysDistance
<= 7 * 3) {
1634 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)"));
1635 } else if (daysDistance
<= 7 * 4) {
1636 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)"));
1638 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"));
1641 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"));
1645 if (newGroupValue
!= groupValue
) {
1646 groupValue
= newGroupValue
;
1647 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1654 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
1656 Q_ASSERT(!m_itemData
.isEmpty());
1658 const int maxIndex
= count() - 1;
1659 QList
<QPair
<int, QVariant
> > groups
;
1661 QString permissionsString
;
1663 for (int i
= 0; i
<= maxIndex
; ++i
) {
1664 if (isChildItem(i
)) {
1668 const ItemData
* itemData
= m_itemData
.at(i
);
1669 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
1670 if (newPermissionsString
== permissionsString
) {
1673 permissionsString
= newPermissionsString
;
1675 const QFileInfo
info(itemData
->item
.url().pathOrUrl());
1679 if (info
.permission(QFile::ReadUser
)) {
1680 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1682 if (info
.permission(QFile::WriteUser
)) {
1683 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1685 if (info
.permission(QFile::ExeUser
)) {
1686 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1688 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
1692 if (info
.permission(QFile::ReadGroup
)) {
1693 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1695 if (info
.permission(QFile::WriteGroup
)) {
1696 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1698 if (info
.permission(QFile::ExeGroup
)) {
1699 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1701 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
1703 // Set others string
1705 if (info
.permission(QFile::ReadOther
)) {
1706 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1708 if (info
.permission(QFile::WriteOther
)) {
1709 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1711 if (info
.permission(QFile::ExeOther
)) {
1712 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1714 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
1716 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
1717 if (newGroupValue
!= groupValue
) {
1718 groupValue
= newGroupValue
;
1719 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1726 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
1728 Q_ASSERT(!m_itemData
.isEmpty());
1730 const int maxIndex
= count() - 1;
1731 QList
<QPair
<int, QVariant
> > groups
;
1734 for (int i
= 0; i
<= maxIndex
; ++i
) {
1735 if (isChildItem(i
)) {
1738 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating").toInt();
1739 if (newGroupValue
!= groupValue
) {
1740 groupValue
= newGroupValue
;
1741 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1748 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
1750 Q_ASSERT(!m_itemData
.isEmpty());
1752 const int maxIndex
= count() - 1;
1753 QList
<QPair
<int, QVariant
> > groups
;
1756 for (int i
= 0; i
<= maxIndex
; ++i
) {
1757 if (isChildItem(i
)) {
1760 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
1761 if (newGroupValue
!= groupValue
) {
1762 groupValue
= newGroupValue
;
1763 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1770 bool KFileItemModel::matchesNameFilter(const KFileItem
& item
) const
1772 // TODO #1: A performance improvement would be possible by caching m_nameFilter.toLower().
1773 // Before adding yet-another-member it should be checked whether it brings a noticable
1774 // improvement at all.
1776 // TODO #2: If the user entered a '*' use a regular expression
1777 const QString itemText
= item
.text().toLower();
1778 return itemText
.contains(m_nameFilter
.toLower());
1781 #include "kfileitemmodel.moc"