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(UninitializedRootExpansionLevel
),
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
[ExpansionLevelRole
];
362 const bool willSupportExpanding
= 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 (!isExpandable(index
) || isExpanded(index
) == expanded
) {
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
)->values
.value("isExpandable").toBool();
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
)
465 const KDirLister
* dirLister
= m_dirLister
.data();
470 const int pos
= dirLister
->url().url().length();
472 // Assure that each sub-path of the URLs that should be
473 // expanded is added to m_urlsToExpand too. KDirLister
474 // does not care whether the parent-URL has already been
476 QSetIterator
<KUrl
> it1(urls
);
477 while (it1
.hasNext()) {
478 const KUrl
& url
= it1
.next();
480 KUrl urlToExpand
= dirLister
->url();
481 const QStringList subDirs
= url
.url().mid(pos
).split(QDir::separator());
482 for (int i
= 0; i
< subDirs
.count(); ++i
) {
483 urlToExpand
.addPath(subDirs
.at(i
));
484 m_urlsToExpand
.insert(urlToExpand
);
488 // KDirLister::open() must called at least once to trigger an initial
489 // loading. The pending URLs that must be restored are handled
490 // in slotCompleted().
491 QSetIterator
<KUrl
> it2(m_urlsToExpand
);
492 while (it2
.hasNext()) {
493 const int idx
= index(it2
.next());
494 if (idx
>= 0 && !isExpanded(idx
)) {
495 setExpanded(idx
, true);
501 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
503 if (m_filter
.pattern() != nameFilter
) {
504 dispatchPendingItemsToInsert();
506 m_filter
.setPattern(nameFilter
);
508 // Check which shown items from m_itemData must get
509 // hidden and hence moved to m_filteredItems.
510 KFileItemList newFilteredItems
;
512 foreach (ItemData
* itemData
, m_itemData
) {
513 if (!m_filter
.matches(itemData
->item
)) {
514 // Only filter non-expanded items as child items may never
515 // exist without a parent item
516 if (!itemData
->values
.value("isExpanded").toBool()) {
517 newFilteredItems
.append(itemData
->item
);
518 m_filteredItems
.insert(itemData
->item
);
523 removeItems(newFilteredItems
);
525 // Check which hidden items from m_filteredItems should
526 // get visible again and hence removed from m_filteredItems.
527 KFileItemList newVisibleItems
;
529 QMutableSetIterator
<KFileItem
> it(m_filteredItems
);
530 while (it
.hasNext()) {
531 const KFileItem item
= it
.next();
532 if (m_filter
.matches(item
)) {
533 newVisibleItems
.append(item
);
534 m_filteredItems
.remove(item
);
538 insertItems(newVisibleItems
);
542 QString
KFileItemModel::nameFilter() const
544 return m_filter
.pattern();
547 void KFileItemModel::onGroupedSortingChanged(bool current
)
553 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
556 m_sortRole
= roleIndex(current
);
558 #ifdef KFILEITEMMODEL_DEBUG
559 if (!m_requestRole
[m_sortRole
]) {
560 kWarning() << "The sort-role has been changed to a role that has not been received yet";
567 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
574 void KFileItemModel::resortAllItems()
576 m_resortAllItemsTimer
->stop();
578 const int itemCount
= count();
579 if (itemCount
<= 0) {
583 #ifdef KFILEITEMMODEL_DEBUG
586 kDebug() << "===========================================================";
587 kDebug() << "Resorting" << itemCount
<< "items";
590 // Remember the order of the current URLs so
591 // that it can be determined which indexes have
592 // been moved because of the resorting.
594 oldUrls
.reserve(itemCount
);
595 foreach (const ItemData
* itemData
, m_itemData
) {
596 oldUrls
.append(itemData
->item
.url());
603 sort(m_itemData
.begin(), m_itemData
.end());
604 for (int i
= 0; i
< itemCount
; ++i
) {
605 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
608 // Determine the indexes that have been moved
609 bool emitItemsMoved
= false;
610 QList
<int> movedToIndexes
;
611 movedToIndexes
.reserve(itemCount
);
612 for (int i
= 0; i
< itemCount
; i
++) {
613 const int newIndex
= m_items
.value(oldUrls
.at(i
).url());
614 movedToIndexes
.append(newIndex
);
615 if (!emitItemsMoved
&& newIndex
!= i
) {
616 emitItemsMoved
= true;
620 if (emitItemsMoved
) {
621 emit
itemsMoved(KItemRange(0, itemCount
), movedToIndexes
);
624 #ifdef KFILEITEMMODEL_DEBUG
625 kDebug() << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
629 void KFileItemModel::slotCompleted()
631 if (m_urlsToExpand
.isEmpty() && m_minimumUpdateIntervalTimer
->isActive()) {
632 // dispatchPendingItems() will be called when the timer
634 m_pendingEmitLoadingCompleted
= true;
638 m_pendingEmitLoadingCompleted
= false;
639 dispatchPendingItemsToInsert();
641 if (!m_urlsToExpand
.isEmpty()) {
642 // Try to find a URL that can be expanded.
643 // Note that the parent folder must be expanded before any of its subfolders become visible.
644 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
645 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
646 foreach(const KUrl
& url
, m_urlsToExpand
) {
647 const int index
= m_items
.value(url
, -1);
649 m_urlsToExpand
.remove(url
);
650 if (setExpanded(index
, true)) {
651 // The dir lister has been triggered. This slot will be called
652 // again after the directory has been expanded.
658 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
659 // if these URLs have been deleted in the meantime.
660 m_urlsToExpand
.clear();
663 emit
loadingCompleted();
664 m_minimumUpdateIntervalTimer
->start();
667 void KFileItemModel::slotCanceled()
669 m_minimumUpdateIntervalTimer
->stop();
670 m_maximumUpdateIntervalTimer
->stop();
671 dispatchPendingItemsToInsert();
674 void KFileItemModel::slotNewItems(const KFileItemList
& items
)
676 Q_ASSERT(!items
.isEmpty());
678 if (m_requestRole
[ExpansionLevelRole
] && m_rootExpansionLevel
>= 0) {
679 // To be able to compare whether the new items may be inserted as children
680 // of a parent item the pending items must be added to the model first.
681 dispatchPendingItemsToInsert();
683 KFileItem item
= items
.first();
685 // If the expanding of items is enabled, the call
686 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
687 // might result in emitting the same items twice due to the Keep-parameter.
688 // This case happens if an item gets expanded, collapsed and expanded again
689 // before the items could be loaded for the first expansion.
690 const int index
= m_items
.value(item
.url(), -1);
692 // The items are already part of the model.
696 // KDirLister keeps the children of items that got expanded once even if
697 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
698 // checked whether the parent for new items is still expanded.
699 KUrl parentUrl
= item
.url().upUrl();
700 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
701 const int parentIndex
= m_items
.value(parentUrl
, -1);
702 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
703 // The parent is not expanded.
708 if (m_filter
.pattern().isEmpty()) {
709 m_pendingItemsToInsert
.append(items
);
711 // The name-filter is active. Hide filtered items
712 // before inserting them into the model and remember
713 // the filtered items in m_filteredItems.
714 KFileItemList filteredItems
;
715 foreach (const KFileItem
& item
, items
) {
716 if (m_filter
.matches(item
)) {
717 filteredItems
.append(item
);
719 m_filteredItems
.insert(item
);
723 m_pendingItemsToInsert
.append(filteredItems
);
726 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer
->isActive()) {
727 // Assure that items get dispatched if no completed() or canceled() signal is
728 // emitted during the maximum update interval.
729 m_maximumUpdateIntervalTimer
->start();
733 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
735 dispatchPendingItemsToInsert();
737 KFileItemList itemsToRemove
= items
;
738 if (m_requestRole
[ExpansionLevelRole
] && m_rootExpansionLevel
>= 0) {
739 // Assure that removing a parent item also results in removing all children
740 foreach (const KFileItem
& item
, items
) {
741 itemsToRemove
.append(childItems(item
));
745 if (!m_filteredItems
.isEmpty()) {
746 foreach (const KFileItem
& item
, itemsToRemove
) {
747 m_filteredItems
.remove(item
);
751 removeItems(itemsToRemove
);
754 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
756 Q_ASSERT(!items
.isEmpty());
757 #ifdef KFILEITEMMODEL_DEBUG
758 kDebug() << "Refreshing" << items
.count() << "items";
763 // Get the indexes of all items that have been refreshed
765 indexes
.reserve(items
.count());
767 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
768 while (it
.hasNext()) {
769 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
770 const KFileItem
& oldItem
= itemPair
.first
;
771 const KFileItem
& newItem
= itemPair
.second
;
772 const int index
= m_items
.value(oldItem
.url(), -1);
774 m_itemData
[index
]->item
= newItem
;
775 m_itemData
[index
]->values
= retrieveData(newItem
);
776 m_items
.remove(oldItem
.url());
777 m_items
.insert(newItem
.url(), index
);
778 indexes
.append(index
);
782 // If the changed items have been created recently, they might not be in m_items yet.
783 // In that case, the list 'indexes' might be empty.
784 if (indexes
.isEmpty()) {
788 // Extract the item-ranges out of the changed indexes
791 KItemRangeList itemRangeList
;
792 int previousIndex
= indexes
.at(0);
793 int rangeIndex
= previousIndex
;
796 const int maxIndex
= indexes
.count() - 1;
797 for (int i
= 1; i
<= maxIndex
; ++i
) {
798 const int currentIndex
= indexes
.at(i
);
799 if (currentIndex
== previousIndex
+ 1) {
802 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
804 rangeIndex
= currentIndex
;
807 previousIndex
= currentIndex
;
810 if (rangeCount
> 0) {
811 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
814 emit
itemsChanged(itemRangeList
, m_roles
);
819 void KFileItemModel::slotClear()
821 #ifdef KFILEITEMMODEL_DEBUG
822 kDebug() << "Clearing all items";
825 m_filteredItems
.clear();
828 m_minimumUpdateIntervalTimer
->stop();
829 m_maximumUpdateIntervalTimer
->stop();
830 m_resortAllItemsTimer
->stop();
831 m_pendingItemsToInsert
.clear();
833 m_rootExpansionLevel
= UninitializedRootExpansionLevel
;
835 const int removedCount
= m_itemData
.count();
836 if (removedCount
> 0) {
837 qDeleteAll(m_itemData
);
840 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
843 m_expandedUrls
.clear();
846 void KFileItemModel::slotClear(const KUrl
& url
)
851 void KFileItemModel::dispatchPendingItemsToInsert()
853 if (!m_pendingItemsToInsert
.isEmpty()) {
854 insertItems(m_pendingItemsToInsert
);
855 m_pendingItemsToInsert
.clear();
858 if (m_pendingEmitLoadingCompleted
) {
859 emit
loadingCompleted();
863 void KFileItemModel::insertItems(const KFileItemList
& items
)
865 if (items
.isEmpty()) {
869 #ifdef KFILEITEMMODEL_DEBUG
872 kDebug() << "===========================================================";
873 kDebug() << "Inserting" << items
.count() << "items";
878 QList
<ItemData
*> sortedItems
= createItemDataList(items
);
879 sort(sortedItems
.begin(), sortedItems
.end());
881 #ifdef KFILEITEMMODEL_DEBUG
882 kDebug() << "[TIME] Sorting:" << timer
.elapsed();
885 KItemRangeList itemRanges
;
888 int insertedAtIndex
= -1; // Index for the current item-range
889 int insertedCount
= 0; // Count for the current item-range
890 int previouslyInsertedCount
= 0; // Sum of previously inserted items for all ranges
891 while (sourceIndex
< sortedItems
.count()) {
892 // Find target index from m_items to insert the current item
894 const int previousTargetIndex
= targetIndex
;
895 while (targetIndex
< m_itemData
.count()) {
896 if (!lessThan(m_itemData
.at(targetIndex
), sortedItems
.at(sourceIndex
))) {
902 if (targetIndex
- previousTargetIndex
> 0 && insertedAtIndex
>= 0) {
903 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
904 previouslyInsertedCount
+= insertedCount
;
905 insertedAtIndex
= targetIndex
- previouslyInsertedCount
;
909 // Insert item at the position targetIndex by transfering
910 // the ownership of the item-data from sortedItems to m_itemData.
911 // m_items will be inserted after the loop (see comment below)
912 m_itemData
.insert(targetIndex
, sortedItems
.at(sourceIndex
));
915 if (insertedAtIndex
< 0) {
916 insertedAtIndex
= targetIndex
;
917 Q_ASSERT(previouslyInsertedCount
== 0);
923 // The indexes of all m_items must be adjusted, not only the index
925 const int itemDataCount
= m_itemData
.count();
926 for (int i
= 0; i
< itemDataCount
; ++i
) {
927 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
930 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
931 emit
itemsInserted(itemRanges
);
933 #ifdef KFILEITEMMODEL_DEBUG
934 kDebug() << "[TIME] Inserting of" << items
.count() << "items:" << timer
.elapsed();
938 void KFileItemModel::removeItems(const KFileItemList
& items
)
940 if (items
.isEmpty()) {
944 #ifdef KFILEITEMMODEL_DEBUG
945 kDebug() << "Removing " << items
.count() << "items";
950 QList
<ItemData
*> sortedItems
;
951 sortedItems
.reserve(items
.count());
952 foreach (const KFileItem
& item
, items
) {
953 const int index
= m_items
.value(item
.url(), -1);
955 sortedItems
.append(m_itemData
.at(index
));
958 sort(sortedItems
.begin(), sortedItems
.end());
960 QList
<int> indexesToRemove
;
961 indexesToRemove
.reserve(items
.count());
963 // Calculate the item ranges that will get deleted
964 KItemRangeList itemRanges
;
965 int removedAtIndex
= -1;
966 int removedCount
= 0;
968 foreach (const ItemData
* itemData
, sortedItems
) {
969 const KFileItem
& itemToRemove
= itemData
->item
;
971 const int previousTargetIndex
= targetIndex
;
972 while (targetIndex
< m_itemData
.count()) {
973 if (m_itemData
.at(targetIndex
)->item
.url() == itemToRemove
.url()) {
978 if (targetIndex
>= m_itemData
.count()) {
979 kWarning() << "Item that should be deleted has not been found!";
983 if (targetIndex
- previousTargetIndex
> 0 && removedAtIndex
>= 0) {
984 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
985 removedAtIndex
= targetIndex
;
989 indexesToRemove
.append(targetIndex
);
990 if (removedAtIndex
< 0) {
991 removedAtIndex
= targetIndex
;
998 for (int i
= indexesToRemove
.count() - 1; i
>= 0; --i
) {
999 const int indexToRemove
= indexesToRemove
.at(i
);
1000 ItemData
* data
= m_itemData
.at(indexToRemove
);
1002 m_items
.remove(data
->item
.url());
1005 m_itemData
.removeAt(indexToRemove
);
1008 // The indexes of all m_items must be adjusted, not only the index
1009 // of the removed items
1010 const int itemDataCount
= m_itemData
.count();
1011 for (int i
= 0; i
< itemDataCount
; ++i
) {
1012 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
1016 m_rootExpansionLevel
= UninitializedRootExpansionLevel
;
1019 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
1020 emit
itemsRemoved(itemRanges
);
1023 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const KFileItemList
& items
) const
1025 QList
<ItemData
*> itemDataList
;
1026 itemDataList
.reserve(items
.count());
1028 foreach (const KFileItem
& item
, items
) {
1029 ItemData
* itemData
= new ItemData();
1030 itemData
->item
= item
;
1031 itemData
->values
= retrieveData(item
);
1032 itemData
->parent
= 0;
1034 const bool determineParent
= m_requestRole
[ExpansionLevelRole
]
1035 && itemData
->values
["expansionLevel"].toInt() > 0;
1036 if (determineParent
) {
1037 KUrl parentUrl
= item
.url().upUrl();
1038 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
1039 const int parentIndex
= m_items
.value(parentUrl
, -1);
1040 if (parentIndex
>= 0) {
1041 itemData
->parent
= m_itemData
.at(parentIndex
);
1043 kWarning() << "Parent item not found for" << item
.url();
1047 itemDataList
.append(itemData
);
1050 return itemDataList
;
1053 void KFileItemModel::removeExpandedItems()
1055 KFileItemList expandedItems
;
1057 const int maxIndex
= m_itemData
.count() - 1;
1058 for (int i
= 0; i
<= maxIndex
; ++i
) {
1059 const ItemData
* itemData
= m_itemData
.at(i
);
1060 if (itemData
->values
.value("expansionLevel").toInt() > 0) {
1061 expandedItems
.append(itemData
->item
);
1065 // The m_rootExpansionLevel may not get reset before all items with
1066 // a bigger expansionLevel have been removed.
1067 Q_ASSERT(m_rootExpansionLevel
>= 0);
1068 removeItems(expandedItems
);
1070 m_rootExpansionLevel
= UninitializedRootExpansionLevel
;
1071 m_expandedUrls
.clear();
1074 void KFileItemModel::resetRoles()
1076 for (int i
= 0; i
< RolesCount
; ++i
) {
1077 m_requestRole
[i
] = false;
1081 KFileItemModel::Role
KFileItemModel::roleIndex(const QByteArray
& role
) const
1083 static QHash
<QByteArray
, Role
> rolesHash
;
1084 if (rolesHash
.isEmpty()) {
1085 rolesHash
.insert("name", NameRole
);
1086 rolesHash
.insert("size", SizeRole
);
1087 rolesHash
.insert("date", DateRole
);
1088 rolesHash
.insert("permissions", PermissionsRole
);
1089 rolesHash
.insert("owner", OwnerRole
);
1090 rolesHash
.insert("group", GroupRole
);
1091 rolesHash
.insert("type", TypeRole
);
1092 rolesHash
.insert("destination", DestinationRole
);
1093 rolesHash
.insert("path", PathRole
);
1094 rolesHash
.insert("comment", CommentRole
);
1095 rolesHash
.insert("tags", TagsRole
);
1096 rolesHash
.insert("rating", RatingRole
);
1097 rolesHash
.insert("isDir", IsDirRole
);
1098 rolesHash
.insert("isExpanded", IsExpandedRole
);
1099 rolesHash
.insert("isExpandable", IsExpandableRole
);
1100 rolesHash
.insert("expansionLevel", ExpansionLevelRole
);
1102 return rolesHash
.value(role
, NoRole
);
1105 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
) const
1107 // It is important to insert only roles that are fast to retrieve. E.g.
1108 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1109 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1110 QHash
<QByteArray
, QVariant
> data
;
1111 data
.insert("iconPixmap", QPixmap());
1112 data
.insert("url", item
.url());
1114 const bool isDir
= item
.isDir();
1115 if (m_requestRole
[IsDirRole
]) {
1116 data
.insert("isDir", isDir
);
1119 if (m_requestRole
[NameRole
]) {
1120 data
.insert("name", item
.text());
1123 if (m_requestRole
[SizeRole
]) {
1125 data
.insert("size", QVariant());
1127 data
.insert("size", item
.size());
1131 if (m_requestRole
[DateRole
]) {
1132 // Don't use KFileItem::timeString() as this is too expensive when
1133 // having several thousands of items. Instead the formatting of the
1134 // date-time will be done on-demand by the view when the date will be shown.
1135 const KDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
1136 data
.insert("date", dateTime
.dateTime());
1139 if (m_requestRole
[PermissionsRole
]) {
1140 data
.insert("permissions", item
.permissionsString());
1143 if (m_requestRole
[OwnerRole
]) {
1144 data
.insert("owner", item
.user());
1147 if (m_requestRole
[GroupRole
]) {
1148 data
.insert("group", item
.group());
1151 if (m_requestRole
[DestinationRole
]) {
1152 QString destination
= item
.linkDest();
1153 if (destination
.isEmpty()) {
1154 destination
= i18nc("@item:intable", "No destination");
1156 data
.insert("destination", destination
);
1159 if (m_requestRole
[PathRole
]) {
1160 if (item
.url().protocol() == QLatin1String("trash")) {
1161 const KIO::UDSEntry udsEntry
= item
.entry();
1162 data
.insert("path", udsEntry
.stringValue(KIO::UDSEntry::UDS_EXTRA
));
1164 data
.insert("path", item
.localPath());
1168 if (m_requestRole
[IsExpandedRole
]) {
1169 data
.insert("isExpanded", false);
1172 if (m_requestRole
[IsExpandableRole
]) {
1173 data
.insert("isExpandable", item
.isDir() && item
.url() == item
.targetUrl());
1176 if (m_requestRole
[ExpansionLevelRole
]) {
1177 if (m_rootExpansionLevel
== UninitializedRootExpansionLevel
&& m_dirLister
.data()) {
1178 const KUrl rootUrl
= m_dirLister
.data()->url();
1179 const QString protocol
= rootUrl
.protocol();
1180 const bool forceRootExpansionLevel
= (protocol
== QLatin1String("trash") ||
1181 protocol
== QLatin1String("nepomuk") ||
1182 protocol
== QLatin1String("remote") ||
1183 protocol
.contains(QLatin1String("search")));
1184 if (forceRootExpansionLevel
) {
1185 m_rootExpansionLevel
= ForceRootExpansionLevel
;
1187 const QString rootDir
= rootUrl
.directory(KUrl::AppendTrailingSlash
);
1188 m_rootExpansionLevel
= rootDir
.count('/');
1189 if (m_rootExpansionLevel
== 1) {
1190 // Special case: The root is already reached and no parent is available
1191 --m_rootExpansionLevel
;
1196 if (m_rootExpansionLevel
== ForceRootExpansionLevel
) {
1197 data
.insert("expansionLevel", -1);
1199 const QString dir
= item
.url().directory(KUrl::AppendTrailingSlash
);
1200 const int level
= dir
.count('/') - m_rootExpansionLevel
- 1;
1201 data
.insert("expansionLevel", level
);
1205 if (item
.isMimeTypeKnown()) {
1206 data
.insert("iconName", item
.iconName());
1208 if (m_requestRole
[TypeRole
]) {
1209 data
.insert("type", item
.mimeComment());
1216 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
) const
1220 if (m_rootExpansionLevel
>= 0) {
1221 result
= expansionLevelsCompare(a
, b
);
1223 // The items have parents with different expansion levels
1224 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1228 if (m_sortFoldersFirst
|| m_sortRole
== SizeRole
) {
1229 const bool isDirA
= a
->item
.isDir();
1230 const bool isDirB
= b
->item
.isDir();
1231 if (isDirA
&& !isDirB
) {
1233 } else if (!isDirA
&& isDirB
) {
1238 result
= sortRoleCompare(a
, b
);
1240 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1243 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
) const
1245 const KFileItem
& itemA
= a
->item
;
1246 const KFileItem
& itemB
= b
->item
;
1250 switch (m_sortRole
) {
1252 // The name role is handled as default fallback after the switch
1256 const KDateTime dateTimeA
= itemA
.time(KFileItem::ModificationTime
);
1257 const KDateTime dateTimeB
= itemB
.time(KFileItem::ModificationTime
);
1258 if (dateTimeA
< dateTimeB
) {
1260 } else if (dateTimeA
> dateTimeB
) {
1267 if (itemA
.isDir()) {
1268 Q_ASSERT(itemB
.isDir()); // see "if (m_sortFoldersFirst || m_sortRole == SizeRole)" above
1270 const QVariant valueA
= a
->values
.value("size");
1271 const QVariant valueB
= b
->values
.value("size");
1273 if (valueA
.isNull()) {
1275 } else if (valueB
.isNull()) {
1278 result
= valueA
.value
<KIO::filesize_t
>() - valueB
.value
<KIO::filesize_t
>();
1281 Q_ASSERT(!itemB
.isDir()); // see "if (m_sortFoldersFirst || m_sortRole == SizeRole)" above
1282 result
= itemA
.size() - itemB
.size();
1288 result
= QString::compare(a
->values
.value("type").toString(),
1289 b
->values
.value("type").toString());
1294 result
= QString::compare(a
->values
.value("comment").toString(),
1295 b
->values
.value("comment").toString());
1300 result
= QString::compare(a
->values
.value("tags").toString(),
1301 b
->values
.value("tags").toString());
1306 result
= a
->values
.value("rating").toInt() - b
->values
.value("rating").toInt();
1315 // The current sort role was sufficient to define an order
1319 // Fallback #1: Compare the text of the items
1320 result
= stringCompare(itemA
.text(), itemB
.text());
1325 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1326 result
= stringCompare(itemA
.name(m_caseSensitivity
== Qt::CaseInsensitive
),
1327 itemB
.name(m_caseSensitivity
== Qt::CaseInsensitive
));
1332 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1333 // equal. In this case a comparison of the URL is done which is unique in all cases
1334 // within KDirLister.
1335 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1338 void KFileItemModel::sort(QList
<ItemData
*>::iterator begin
,
1339 QList
<ItemData
*>::iterator end
)
1341 // The implementation is based on qStableSortHelper() from qalgorithms.h
1342 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1343 // In opposite to qStableSort() it allows to use a member-function for the comparison of elements.
1345 const int span
= end
- begin
;
1350 const QList
<ItemData
*>::iterator middle
= begin
+ span
/ 2;
1351 sort(begin
, middle
);
1353 merge(begin
, middle
, end
);
1356 void KFileItemModel::merge(QList
<ItemData
*>::iterator begin
,
1357 QList
<ItemData
*>::iterator pivot
,
1358 QList
<ItemData
*>::iterator end
)
1360 // The implementation is based on qMerge() from qalgorithms.h
1361 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1363 const int len1
= pivot
- begin
;
1364 const int len2
= end
- pivot
;
1366 if (len1
== 0 || len2
== 0) {
1370 if (len1
+ len2
== 2) {
1371 if (lessThan(*(begin
+ 1), *(begin
))) {
1372 qSwap(*begin
, *(begin
+ 1));
1377 QList
<ItemData
*>::iterator firstCut
;
1378 QList
<ItemData
*>::iterator secondCut
;
1381 const int len1Half
= len1
/ 2;
1382 firstCut
= begin
+ len1Half
;
1383 secondCut
= lowerBound(pivot
, end
, *firstCut
);
1384 len2Half
= secondCut
- pivot
;
1386 len2Half
= len2
/ 2;
1387 secondCut
= pivot
+ len2Half
;
1388 firstCut
= upperBound(begin
, pivot
, *secondCut
);
1391 reverse(firstCut
, pivot
);
1392 reverse(pivot
, secondCut
);
1393 reverse(firstCut
, secondCut
);
1395 const QList
<ItemData
*>::iterator newPivot
= firstCut
+ len2Half
;
1396 merge(begin
, firstCut
, newPivot
);
1397 merge(newPivot
, secondCut
, end
);
1400 QList
<KFileItemModel::ItemData
*>::iterator
KFileItemModel::lowerBound(QList
<ItemData
*>::iterator begin
,
1401 QList
<ItemData
*>::iterator end
,
1402 const ItemData
* value
)
1404 // The implementation is based on qLowerBound() from qalgorithms.h
1405 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1407 QList
<ItemData
*>::iterator middle
;
1408 int n
= int(end
- begin
);
1413 middle
= begin
+ half
;
1414 if (lessThan(*middle
, value
)) {
1424 QList
<KFileItemModel::ItemData
*>::iterator
KFileItemModel::upperBound(QList
<ItemData
*>::iterator begin
,
1425 QList
<ItemData
*>::iterator end
,
1426 const ItemData
* value
)
1428 // The implementation is based on qUpperBound() from qalgorithms.h
1429 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1431 QList
<ItemData
*>::iterator middle
;
1432 int n
= end
- begin
;
1437 middle
= begin
+ half
;
1438 if (lessThan(value
, *middle
)) {
1448 void KFileItemModel::reverse(QList
<ItemData
*>::iterator begin
,
1449 QList
<ItemData
*>::iterator end
)
1451 // The implementation is based on qReverse() from qalgorithms.h
1452 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1455 while (begin
< end
) {
1456 qSwap(*begin
++, *end
--);
1460 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
) const
1462 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1463 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1464 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1465 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1467 if (m_caseSensitivity
== Qt::CaseInsensitive
) {
1468 const int result
= m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseInsensitive
)
1469 : QString::compare(a
, b
, Qt::CaseInsensitive
);
1471 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1472 // comparison, still a deterministic sort order is required. A case sensitive
1473 // comparison is done as fallback.
1478 return m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseSensitive
)
1479 : QString::compare(a
, b
, Qt::CaseSensitive
);
1482 int KFileItemModel::expansionLevelsCompare(const ItemData
* a
, const ItemData
* b
) const
1484 const KUrl urlA
= a
->item
.url();
1485 const KUrl urlB
= b
->item
.url();
1486 if (urlA
.directory() == urlB
.directory()) {
1487 // Both items have the same directory as parent
1491 // Check whether one item is the parent of the other item
1492 if (urlA
.isParentOf(urlB
)) {
1493 return (sortOrder() == Qt::AscendingOrder
) ? -1 : +1;
1494 } else if (urlB
.isParentOf(urlA
)) {
1495 return (sortOrder() == Qt::AscendingOrder
) ? +1 : -1;
1498 // Determine the maximum common path of both items and
1499 // remember the index in 'index'
1500 const QString pathA
= urlA
.path();
1501 const QString pathB
= urlB
.path();
1503 const int maxIndex
= qMin(pathA
.length(), pathB
.length()) - 1;
1505 while (index
<= maxIndex
&& pathA
.at(index
) == pathB
.at(index
)) {
1508 if (index
> maxIndex
) {
1511 while ((pathA
.at(index
) != QLatin1Char('/') || pathB
.at(index
) != QLatin1Char('/')) && index
> 0) {
1515 // Determine the first sub-path after the common path and
1516 // check whether it represents a directory or already a file
1518 const QString subPathA
= subPath(a
->item
, pathA
, index
, &isDirA
);
1520 const QString subPathB
= subPath(b
->item
, pathB
, index
, &isDirB
);
1522 if (isDirA
&& !isDirB
) {
1523 return (sortOrder() == Qt::AscendingOrder
) ? -1 : +1;
1524 } else if (!isDirA
&& isDirB
) {
1525 return (sortOrder() == Qt::AscendingOrder
) ? +1 : -1;
1528 // Compare the items of the parents that represent the first
1529 // different path after the common path.
1530 const KUrl
parentUrlA(pathA
.left(index
) + subPathA
);
1531 const KUrl
parentUrlB(pathB
.left(index
) + subPathB
);
1533 const ItemData
* parentA
= a
;
1534 while (parentA
&& parentA
->item
.url() != parentUrlA
) {
1535 parentA
= parentA
->parent
;
1538 const ItemData
* parentB
= b
;
1539 while (parentB
&& parentB
->item
.url() != parentUrlB
) {
1540 parentB
= parentB
->parent
;
1543 if (parentA
&& parentB
) {
1544 return sortRoleCompare(parentA
, parentB
);
1547 kWarning() << "Child items without parent detected:" << a
->item
.url() << b
->item
.url();
1548 return QString::compare(urlA
.url(), urlB
.url(), Qt::CaseSensitive
);
1551 QString
KFileItemModel::subPath(const KFileItem
& item
,
1552 const QString
& itemPath
,
1557 const int pathIndex
= itemPath
.indexOf('/', start
+ 1);
1558 *isDir
= (pathIndex
> 0) || item
.isDir();
1559 return itemPath
.mid(start
, pathIndex
- start
);
1562 bool KFileItemModel::useMaximumUpdateInterval() const
1564 const KDirLister
* dirLister
= m_dirLister
.data();
1565 return dirLister
&& !dirLister
->url().isLocalFile();
1568 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1570 Q_ASSERT(!m_itemData
.isEmpty());
1572 const int maxIndex
= count() - 1;
1573 QList
<QPair
<int, QVariant
> > groups
;
1577 bool isLetter
= false;
1578 for (int i
= 0; i
<= maxIndex
; ++i
) {
1579 if (isChildItem(i
)) {
1583 const QString name
= m_itemData
.at(i
)->values
.value("name").toString();
1585 // Use the first character of the name as group indication
1586 QChar newFirstChar
= name
.at(0).toUpper();
1587 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1588 newFirstChar
= name
.at(1).toUpper();
1591 if (firstChar
!= newFirstChar
) {
1592 QString newGroupValue
;
1593 if (newFirstChar
>= QLatin1Char('A') && newFirstChar
<= QLatin1Char('Z')) {
1594 // Apply group 'A' - 'Z'
1595 newGroupValue
= newFirstChar
;
1597 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
1598 // Apply group '0 - 9' for any name that starts with a digit
1599 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
1603 // If the current group is 'A' - 'Z' check whether a locale character
1604 // fits into the existing group.
1605 // TODO: This does not work in the case if e.g. the group 'O' starts with
1606 // an umlaut 'O' -> provide unit-test to document this known issue
1607 const QChar
prevChar(firstChar
.unicode() - ushort(1));
1608 const QChar
nextChar(firstChar
.unicode() + ushort(1));
1609 const QString
currChar(newFirstChar
);
1610 const bool partOfCurrentGroup
= currChar
.localeAwareCompare(prevChar
) > 0 &&
1611 currChar
.localeAwareCompare(nextChar
) < 0;
1612 if (partOfCurrentGroup
) {
1616 newGroupValue
= i18nc("@title:group", "Others");
1620 if (newGroupValue
!= groupValue
) {
1621 groupValue
= newGroupValue
;
1622 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1625 firstChar
= newFirstChar
;
1631 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
1633 Q_ASSERT(!m_itemData
.isEmpty());
1635 const int maxIndex
= count() - 1;
1636 QList
<QPair
<int, QVariant
> > groups
;
1639 for (int i
= 0; i
<= maxIndex
; ++i
) {
1640 if (isChildItem(i
)) {
1644 const KFileItem
& item
= m_itemData
.at(i
)->item
;
1645 const KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
1646 QString newGroupValue
;
1647 if (!item
.isNull() && item
.isDir()) {
1648 newGroupValue
= i18nc("@title:group Size", "Folders");
1649 } else if (fileSize
< 5 * 1024 * 1024) {
1650 newGroupValue
= i18nc("@title:group Size", "Small");
1651 } else if (fileSize
< 10 * 1024 * 1024) {
1652 newGroupValue
= i18nc("@title:group Size", "Medium");
1654 newGroupValue
= i18nc("@title:group Size", "Big");
1657 if (newGroupValue
!= groupValue
) {
1658 groupValue
= newGroupValue
;
1659 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1666 QList
<QPair
<int, QVariant
> > KFileItemModel::dateRoleGroups() const
1668 Q_ASSERT(!m_itemData
.isEmpty());
1670 const int maxIndex
= count() - 1;
1671 QList
<QPair
<int, QVariant
> > groups
;
1673 const QDate currentDate
= KDateTime::currentLocalDateTime().date();
1675 int yearForCurrentWeek
= 0;
1676 int currentWeek
= currentDate
.weekNumber(&yearForCurrentWeek
);
1677 if (yearForCurrentWeek
== currentDate
.year() + 1) {
1681 QDate previousModifiedDate
;
1683 for (int i
= 0; i
<= maxIndex
; ++i
) {
1684 if (isChildItem(i
)) {
1688 const KDateTime modifiedTime
= m_itemData
.at(i
)->item
.time(KFileItem::ModificationTime
);
1689 const QDate modifiedDate
= modifiedTime
.date();
1690 if (modifiedDate
== previousModifiedDate
) {
1691 // The current item is in the same group as the previous item
1694 previousModifiedDate
= modifiedDate
;
1696 const int daysDistance
= modifiedDate
.daysTo(currentDate
);
1698 int yearForModifiedWeek
= 0;
1699 int modifiedWeek
= modifiedDate
.weekNumber(&yearForModifiedWeek
);
1700 if (yearForModifiedWeek
== modifiedDate
.year() + 1) {
1704 QString newGroupValue
;
1705 if (currentDate
.year() == modifiedDate
.year() && currentDate
.month() == modifiedDate
.month()) {
1706 if (modifiedWeek
> currentWeek
) {
1707 // Usecase: modified date = 2010-01-01, current date = 2010-01-22
1708 // modified week = 53, current week = 3
1711 switch (currentWeek
- modifiedWeek
) {
1713 switch (daysDistance
) {
1714 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
1715 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
1716 default: newGroupValue
= modifiedTime
.toString(i18nc("@title:group The week day name: %A", "%A"));
1720 newGroupValue
= i18nc("@title:group Date", "Last Week");
1723 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
1726 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
1730 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
1736 const QDate lastMonthDate
= currentDate
.addMonths(-1);
1737 if (lastMonthDate
.year() == modifiedDate
.year() && lastMonthDate
.month() == modifiedDate
.month()) {
1738 if (daysDistance
== 1) {
1739 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Yesterday (%B, %Y)"));
1740 } else if (daysDistance
<= 7) {
1741 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)"));
1742 } else if (daysDistance
<= 7 * 2) {
1743 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)"));
1744 } else if (daysDistance
<= 7 * 3) {
1745 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)"));
1746 } else if (daysDistance
<= 7 * 4) {
1747 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)"));
1749 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"));
1752 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"));
1756 if (newGroupValue
!= groupValue
) {
1757 groupValue
= newGroupValue
;
1758 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1765 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
1767 Q_ASSERT(!m_itemData
.isEmpty());
1769 const int maxIndex
= count() - 1;
1770 QList
<QPair
<int, QVariant
> > groups
;
1772 QString permissionsString
;
1774 for (int i
= 0; i
<= maxIndex
; ++i
) {
1775 if (isChildItem(i
)) {
1779 const ItemData
* itemData
= m_itemData
.at(i
);
1780 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
1781 if (newPermissionsString
== permissionsString
) {
1784 permissionsString
= newPermissionsString
;
1786 const QFileInfo
info(itemData
->item
.url().pathOrUrl());
1790 if (info
.permission(QFile::ReadUser
)) {
1791 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1793 if (info
.permission(QFile::WriteUser
)) {
1794 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1796 if (info
.permission(QFile::ExeUser
)) {
1797 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1799 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
1803 if (info
.permission(QFile::ReadGroup
)) {
1804 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1806 if (info
.permission(QFile::WriteGroup
)) {
1807 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1809 if (info
.permission(QFile::ExeGroup
)) {
1810 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1812 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
1814 // Set others string
1816 if (info
.permission(QFile::ReadOther
)) {
1817 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1819 if (info
.permission(QFile::WriteOther
)) {
1820 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1822 if (info
.permission(QFile::ExeOther
)) {
1823 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1825 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
1827 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
1828 if (newGroupValue
!= groupValue
) {
1829 groupValue
= newGroupValue
;
1830 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1837 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
1839 Q_ASSERT(!m_itemData
.isEmpty());
1841 const int maxIndex
= count() - 1;
1842 QList
<QPair
<int, QVariant
> > groups
;
1845 for (int i
= 0; i
<= maxIndex
; ++i
) {
1846 if (isChildItem(i
)) {
1849 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating").toInt();
1850 if (newGroupValue
!= groupValue
) {
1851 groupValue
= newGroupValue
;
1852 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1859 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
1861 Q_ASSERT(!m_itemData
.isEmpty());
1863 const int maxIndex
= count() - 1;
1864 QList
<QPair
<int, QVariant
> > groups
;
1867 for (int i
= 0; i
<= maxIndex
; ++i
) {
1868 if (isChildItem(i
)) {
1871 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
1872 if (newGroupValue
!= groupValue
) {
1873 groupValue
= newGroupValue
;
1874 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1881 KFileItemList
KFileItemModel::childItems(const KFileItem
& item
) const
1883 KFileItemList items
;
1885 int index
= m_items
.value(item
.url(), -1);
1887 const int parentLevel
= m_itemData
.at(index
)->values
.value("expansionLevel").toInt();
1889 while (index
< m_itemData
.count() && m_itemData
.at(index
)->values
.value("expansionLevel").toInt() > parentLevel
) {
1890 items
.append(m_itemData
.at(index
)->item
);
1898 #include "kfileitemmodel.moc"