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(KUrl
)), 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 void KFileItemModel::setShowFoldersOnly(bool enabled
)
188 KDirLister
* dirLister
= m_dirLister
.data();
190 dirLister
->setDirOnlyMode(enabled
);
194 bool KFileItemModel::showFoldersOnly() const
196 KDirLister
* dirLister
= m_dirLister
.data();
197 return dirLister
? dirLister
->dirOnlyMode() : false;
200 QMimeData
* KFileItemModel::createMimeData(const QSet
<int>& indexes
) const
202 QMimeData
* data
= new QMimeData();
204 // The following code has been taken from KDirModel::mimeData()
205 // (kdelibs/kio/kio/kdirmodel.cpp)
206 // Copyright (C) 2006 David Faure <faure@kde.org>
208 KUrl::List mostLocalUrls
;
209 bool canUseMostLocalUrls
= true;
211 QSetIterator
<int> it(indexes
);
212 while (it
.hasNext()) {
213 const int index
= it
.next();
214 const KFileItem item
= fileItem(index
);
215 if (!item
.isNull()) {
219 mostLocalUrls
<< item
.mostLocalUrl(isLocal
);
221 canUseMostLocalUrls
= false;
226 const bool different
= canUseMostLocalUrls
&& mostLocalUrls
!= urls
;
227 urls
= KDirModel::simplifiedUrlList(urls
); // TODO: Check if we still need KDirModel for this in KDE 5.0
229 mostLocalUrls
= KDirModel::simplifiedUrlList(mostLocalUrls
);
230 urls
.populateMimeData(mostLocalUrls
, data
);
232 urls
.populateMimeData(data
);
238 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
240 startFromIndex
= qMax(0, startFromIndex
);
241 for (int i
= startFromIndex
; i
< count(); ++i
) {
242 if (data(i
)["name"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
246 for (int i
= 0; i
< startFromIndex
; ++i
) {
247 if (data(i
)["name"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
254 bool KFileItemModel::supportsDropping(int index
) const
256 const KFileItem item
= fileItem(index
);
257 return item
.isNull() ? false : item
.isDir();
260 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
264 switch (roleIndex(role
)) {
265 case NameRole
: descr
= i18nc("@item:intable", "Name"); break;
266 case SizeRole
: descr
= i18nc("@item:intable", "Size"); break;
267 case DateRole
: descr
= i18nc("@item:intable", "Date"); break;
268 case PermissionsRole
: descr
= i18nc("@item:intable", "Permissions"); break;
269 case OwnerRole
: descr
= i18nc("@item:intable", "Owner"); break;
270 case GroupRole
: descr
= i18nc("@item:intable", "Group"); break;
271 case TypeRole
: descr
= i18nc("@item:intable", "Type"); break;
272 case DestinationRole
: descr
= i18nc("@item:intable", "Destination"); break;
273 case PathRole
: descr
= i18nc("@item:intable", "Path"); break;
274 case CommentRole
: descr
= i18nc("@item:intable", "Comment"); break;
275 case TagsRole
: descr
= i18nc("@item:intable", "Tags"); break;
276 case RatingRole
: descr
= i18nc("@item:intable", "Rating"); break;
278 case IsDirRole
: break;
279 case IsExpandedRole
: break;
280 case ExpansionLevelRole
: break;
281 default: Q_ASSERT(false); break;
287 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
289 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
290 #ifdef KFILEITEMMODEL_DEBUG
294 switch (roleIndex(sortRole())) {
295 case NameRole
: m_groups
= nameRoleGroups(); break;
296 case SizeRole
: m_groups
= sizeRoleGroups(); break;
297 case DateRole
: m_groups
= dateRoleGroups(); break;
298 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
299 case OwnerRole
: m_groups
= genericStringRoleGroups("owner"); break;
300 case GroupRole
: m_groups
= genericStringRoleGroups("group"); break;
301 case TypeRole
: m_groups
= genericStringRoleGroups("type"); break;
302 case DestinationRole
: m_groups
= genericStringRoleGroups("destination"); break;
303 case PathRole
: m_groups
= genericStringRoleGroups("path"); break;
304 case CommentRole
: m_groups
= genericStringRoleGroups("comment"); break;
305 case TagsRole
: m_groups
= genericStringRoleGroups("tags"); break;
306 case RatingRole
: m_groups
= ratingRoleGroups(); break;
308 case IsDirRole
: break;
309 case IsExpandedRole
: break;
310 case ExpansionLevelRole
: break;
311 default: Q_ASSERT(false); break;
314 #ifdef KFILEITEMMODEL_DEBUG
315 kDebug() << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
322 KFileItem
KFileItemModel::fileItem(int index
) const
324 if (index
>= 0 && index
< count()) {
325 return m_itemData
.at(index
)->item
;
331 KFileItem
KFileItemModel::fileItem(const KUrl
& url
) const
333 const int index
= m_items
.value(url
, -1);
335 return m_itemData
.at(index
)->item
;
340 int KFileItemModel::index(const KFileItem
& item
) const
346 return m_items
.value(item
.url(), -1);
349 int KFileItemModel::index(const KUrl
& url
) const
351 KUrl urlToFind
= url
;
352 urlToFind
.adjustPath(KUrl::RemoveTrailingSlash
);
353 return m_items
.value(urlToFind
, -1);
356 KFileItem
KFileItemModel::rootItem() const
358 const KDirLister
* dirLister
= m_dirLister
.data();
360 return dirLister
->rootItem();
365 void KFileItemModel::clear()
370 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
375 const bool supportedExpanding
= m_requestRole
[ExpansionLevelRole
];
376 const bool willSupportExpanding
= roles
.contains("expansionLevel");
377 if (supportedExpanding
&& !willSupportExpanding
) {
378 // No expanding is supported anymore. Take care to delete all items that have an expansion level
379 // that is not 0 (and hence are part of an expanded item).
380 removeExpandedItems();
387 QSetIterator
<QByteArray
> it(roles
);
388 while (it
.hasNext()) {
389 const QByteArray
& role
= it
.next();
390 m_requestRole
[roleIndex(role
)] = true;
394 // Update m_data with the changed requested roles
395 const int maxIndex
= count() - 1;
396 for (int i
= 0; i
<= maxIndex
; ++i
) {
397 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
);
400 kWarning() << "TODO: Emitting itemsChanged() with no information what has changed!";
401 emit
itemsChanged(KItemRangeList() << KItemRange(0, count()), QSet
<QByteArray
>());
405 QSet
<QByteArray
> KFileItemModel::roles() const
410 bool KFileItemModel::setExpanded(int index
, bool expanded
)
412 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
416 QHash
<QByteArray
, QVariant
> values
;
417 values
.insert("isExpanded", expanded
);
418 if (!setData(index
, values
)) {
422 KDirLister
* dirLister
= m_dirLister
.data();
423 const KUrl url
= m_itemData
.at(index
)->item
.url();
425 m_expandedUrls
.insert(url
);
428 dirLister
->openUrl(url
, KDirLister::Keep
);
432 m_expandedUrls
.remove(url
);
435 dirLister
->stop(url
);
438 KFileItemList itemsToRemove
;
439 const int expansionLevel
= data(index
)["expansionLevel"].toInt();
441 while (index
< count() && data(index
)["expansionLevel"].toInt() > expansionLevel
) {
442 itemsToRemove
.append(m_itemData
.at(index
)->item
);
445 removeItems(itemsToRemove
);
452 bool KFileItemModel::isExpanded(int index
) const
454 if (index
>= 0 && index
< count()) {
455 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
460 bool KFileItemModel::isExpandable(int index
) const
462 if (index
>= 0 && index
< count()) {
463 return m_itemData
.at(index
)->values
.value("isExpandable").toBool();
468 QSet
<KUrl
> KFileItemModel::expandedUrls() const
470 return m_expandedUrls
;
473 void KFileItemModel::restoreExpandedUrls(const QSet
<KUrl
>& urls
)
475 m_urlsToExpand
= urls
;
478 void KFileItemModel::setExpanded(const QSet
<KUrl
>& urls
)
480 const KDirLister
* dirLister
= m_dirLister
.data();
485 const int pos
= dirLister
->url().url().length();
487 // Assure that each sub-path of the URLs that should be
488 // expanded is added to m_urlsToExpand too. KDirLister
489 // does not care whether the parent-URL has already been
491 QSetIterator
<KUrl
> it1(urls
);
492 while (it1
.hasNext()) {
493 const KUrl
& url
= it1
.next();
495 KUrl urlToExpand
= dirLister
->url();
496 const QStringList subDirs
= url
.url().mid(pos
).split(QDir::separator());
497 for (int i
= 0; i
< subDirs
.count(); ++i
) {
498 urlToExpand
.addPath(subDirs
.at(i
));
499 m_urlsToExpand
.insert(urlToExpand
);
503 // KDirLister::open() must called at least once to trigger an initial
504 // loading. The pending URLs that must be restored are handled
505 // in slotCompleted().
506 QSetIterator
<KUrl
> it2(m_urlsToExpand
);
507 while (it2
.hasNext()) {
508 const int idx
= index(it2
.next());
509 if (idx
>= 0 && !isExpanded(idx
)) {
510 setExpanded(idx
, true);
516 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
518 if (m_filter
.pattern() != nameFilter
) {
519 dispatchPendingItemsToInsert();
521 m_filter
.setPattern(nameFilter
);
523 // Check which shown items from m_itemData must get
524 // hidden and hence moved to m_filteredItems.
525 KFileItemList newFilteredItems
;
527 foreach (ItemData
* itemData
, m_itemData
) {
528 if (!m_filter
.matches(itemData
->item
)) {
529 // Only filter non-expanded items as child items may never
530 // exist without a parent item
531 if (!itemData
->values
.value("isExpanded").toBool()) {
532 newFilteredItems
.append(itemData
->item
);
533 m_filteredItems
.insert(itemData
->item
);
538 removeItems(newFilteredItems
);
540 // Check which hidden items from m_filteredItems should
541 // get visible again and hence removed from m_filteredItems.
542 KFileItemList newVisibleItems
;
544 QMutableSetIterator
<KFileItem
> it(m_filteredItems
);
545 while (it
.hasNext()) {
546 const KFileItem item
= it
.next();
547 if (m_filter
.matches(item
)) {
548 newVisibleItems
.append(item
);
549 m_filteredItems
.remove(item
);
553 insertItems(newVisibleItems
);
557 QString
KFileItemModel::nameFilter() const
559 return m_filter
.pattern();
562 void KFileItemModel::onGroupedSortingChanged(bool current
)
568 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
571 m_sortRole
= roleIndex(current
);
573 #ifdef KFILEITEMMODEL_DEBUG
574 if (!m_requestRole
[m_sortRole
]) {
575 kWarning() << "The sort-role has been changed to a role that has not been received yet";
582 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
589 void KFileItemModel::resortAllItems()
591 m_resortAllItemsTimer
->stop();
593 const int itemCount
= count();
594 if (itemCount
<= 0) {
598 #ifdef KFILEITEMMODEL_DEBUG
601 kDebug() << "===========================================================";
602 kDebug() << "Resorting" << itemCount
<< "items";
605 // Remember the order of the current URLs so
606 // that it can be determined which indexes have
607 // been moved because of the resorting.
609 oldUrls
.reserve(itemCount
);
610 foreach (const ItemData
* itemData
, m_itemData
) {
611 oldUrls
.append(itemData
->item
.url());
618 sort(m_itemData
.begin(), m_itemData
.end());
619 for (int i
= 0; i
< itemCount
; ++i
) {
620 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
623 // Determine the indexes that have been moved
624 QList
<int> movedToIndexes
;
625 movedToIndexes
.reserve(itemCount
);
626 for (int i
= 0; i
< itemCount
; i
++) {
627 const int newIndex
= m_items
.value(oldUrls
.at(i
).url());
628 movedToIndexes
.append(newIndex
);
631 // Don't check whether items have really been moved and always emit a
632 // itemsMoved() signal after resorting: In case of grouped items
633 // the groups might change even if the items themselves don't change their
634 // position. Let the receiver of the signal decide whether a check for moved
635 // items makes sense.
636 emit
itemsMoved(KItemRange(0, itemCount
), movedToIndexes
);
638 #ifdef KFILEITEMMODEL_DEBUG
639 kDebug() << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
643 void KFileItemModel::slotCompleted()
645 if (m_urlsToExpand
.isEmpty() && m_minimumUpdateIntervalTimer
->isActive()) {
646 // dispatchPendingItems() will be called when the timer
648 m_pendingEmitLoadingCompleted
= true;
652 m_pendingEmitLoadingCompleted
= false;
653 dispatchPendingItemsToInsert();
655 if (!m_urlsToExpand
.isEmpty()) {
656 // Try to find a URL that can be expanded.
657 // Note that the parent folder must be expanded before any of its subfolders become visible.
658 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
659 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
660 foreach(const KUrl
& url
, m_urlsToExpand
) {
661 const int index
= m_items
.value(url
, -1);
663 m_urlsToExpand
.remove(url
);
664 if (setExpanded(index
, true)) {
665 // The dir lister has been triggered. This slot will be called
666 // again after the directory has been expanded.
672 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
673 // if these URLs have been deleted in the meantime.
674 m_urlsToExpand
.clear();
677 emit
loadingCompleted();
678 m_minimumUpdateIntervalTimer
->start();
681 void KFileItemModel::slotCanceled()
683 m_minimumUpdateIntervalTimer
->stop();
684 m_maximumUpdateIntervalTimer
->stop();
685 dispatchPendingItemsToInsert();
688 void KFileItemModel::slotNewItems(const KFileItemList
& items
)
690 Q_ASSERT(!items
.isEmpty());
692 if (m_requestRole
[ExpansionLevelRole
] && m_rootExpansionLevel
>= 0) {
693 // To be able to compare whether the new items may be inserted as children
694 // of a parent item the pending items must be added to the model first.
695 dispatchPendingItemsToInsert();
697 KFileItem item
= items
.first();
699 // If the expanding of items is enabled, the call
700 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
701 // might result in emitting the same items twice due to the Keep-parameter.
702 // This case happens if an item gets expanded, collapsed and expanded again
703 // before the items could be loaded for the first expansion.
704 const int index
= m_items
.value(item
.url(), -1);
706 // The items are already part of the model.
710 // KDirLister keeps the children of items that got expanded once even if
711 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
712 // checked whether the parent for new items is still expanded.
713 KUrl parentUrl
= item
.url().upUrl();
714 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
715 const int parentIndex
= m_items
.value(parentUrl
, -1);
716 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
717 // The parent is not expanded.
722 if (m_filter
.pattern().isEmpty()) {
723 m_pendingItemsToInsert
.append(items
);
725 // The name-filter is active. Hide filtered items
726 // before inserting them into the model and remember
727 // the filtered items in m_filteredItems.
728 KFileItemList filteredItems
;
729 foreach (const KFileItem
& item
, items
) {
730 if (m_filter
.matches(item
)) {
731 filteredItems
.append(item
);
733 m_filteredItems
.insert(item
);
737 m_pendingItemsToInsert
.append(filteredItems
);
740 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer
->isActive()) {
741 // Assure that items get dispatched if no completed() or canceled() signal is
742 // emitted during the maximum update interval.
743 m_maximumUpdateIntervalTimer
->start();
747 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
749 dispatchPendingItemsToInsert();
751 KFileItemList itemsToRemove
= items
;
752 if (m_requestRole
[ExpansionLevelRole
] && m_rootExpansionLevel
>= 0) {
753 // Assure that removing a parent item also results in removing all children
754 foreach (const KFileItem
& item
, items
) {
755 itemsToRemove
.append(childItems(item
));
759 if (!m_filteredItems
.isEmpty()) {
760 foreach (const KFileItem
& item
, itemsToRemove
) {
761 m_filteredItems
.remove(item
);
765 removeItems(itemsToRemove
);
768 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
770 Q_ASSERT(!items
.isEmpty());
771 #ifdef KFILEITEMMODEL_DEBUG
772 kDebug() << "Refreshing" << items
.count() << "items";
777 // Get the indexes of all items that have been refreshed
779 indexes
.reserve(items
.count());
781 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
782 while (it
.hasNext()) {
783 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
784 const KFileItem
& oldItem
= itemPair
.first
;
785 const KFileItem
& newItem
= itemPair
.second
;
786 const int index
= m_items
.value(oldItem
.url(), -1);
788 m_itemData
[index
]->item
= newItem
;
789 m_itemData
[index
]->values
= retrieveData(newItem
);
790 m_items
.remove(oldItem
.url());
791 m_items
.insert(newItem
.url(), index
);
792 indexes
.append(index
);
796 // If the changed items have been created recently, they might not be in m_items yet.
797 // In that case, the list 'indexes' might be empty.
798 if (indexes
.isEmpty()) {
802 // Extract the item-ranges out of the changed indexes
805 KItemRangeList itemRangeList
;
806 int previousIndex
= indexes
.at(0);
807 int rangeIndex
= previousIndex
;
810 const int maxIndex
= indexes
.count() - 1;
811 for (int i
= 1; i
<= maxIndex
; ++i
) {
812 const int currentIndex
= indexes
.at(i
);
813 if (currentIndex
== previousIndex
+ 1) {
816 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
818 rangeIndex
= currentIndex
;
821 previousIndex
= currentIndex
;
824 if (rangeCount
> 0) {
825 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
828 emit
itemsChanged(itemRangeList
, m_roles
);
833 void KFileItemModel::slotClear()
835 #ifdef KFILEITEMMODEL_DEBUG
836 kDebug() << "Clearing all items";
839 m_filteredItems
.clear();
842 m_minimumUpdateIntervalTimer
->stop();
843 m_maximumUpdateIntervalTimer
->stop();
844 m_resortAllItemsTimer
->stop();
845 m_pendingItemsToInsert
.clear();
847 m_rootExpansionLevel
= UninitializedRootExpansionLevel
;
849 const int removedCount
= m_itemData
.count();
850 if (removedCount
> 0) {
851 qDeleteAll(m_itemData
);
854 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
857 m_expandedUrls
.clear();
860 void KFileItemModel::slotClear(const KUrl
& url
)
865 void KFileItemModel::dispatchPendingItemsToInsert()
867 if (!m_pendingItemsToInsert
.isEmpty()) {
868 insertItems(m_pendingItemsToInsert
);
869 m_pendingItemsToInsert
.clear();
872 if (m_pendingEmitLoadingCompleted
) {
873 emit
loadingCompleted();
877 void KFileItemModel::insertItems(const KFileItemList
& items
)
879 if (items
.isEmpty()) {
883 #ifdef KFILEITEMMODEL_DEBUG
886 kDebug() << "===========================================================";
887 kDebug() << "Inserting" << items
.count() << "items";
892 QList
<ItemData
*> sortedItems
= createItemDataList(items
);
893 sort(sortedItems
.begin(), sortedItems
.end());
895 #ifdef KFILEITEMMODEL_DEBUG
896 kDebug() << "[TIME] Sorting:" << timer
.elapsed();
899 KItemRangeList itemRanges
;
902 int insertedAtIndex
= -1; // Index for the current item-range
903 int insertedCount
= 0; // Count for the current item-range
904 int previouslyInsertedCount
= 0; // Sum of previously inserted items for all ranges
905 while (sourceIndex
< sortedItems
.count()) {
906 // Find target index from m_items to insert the current item
908 const int previousTargetIndex
= targetIndex
;
909 while (targetIndex
< m_itemData
.count()) {
910 if (!lessThan(m_itemData
.at(targetIndex
), sortedItems
.at(sourceIndex
))) {
916 if (targetIndex
- previousTargetIndex
> 0 && insertedAtIndex
>= 0) {
917 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
918 previouslyInsertedCount
+= insertedCount
;
919 insertedAtIndex
= targetIndex
- previouslyInsertedCount
;
923 // Insert item at the position targetIndex by transfering
924 // the ownership of the item-data from sortedItems to m_itemData.
925 // m_items will be inserted after the loop (see comment below)
926 m_itemData
.insert(targetIndex
, sortedItems
.at(sourceIndex
));
929 if (insertedAtIndex
< 0) {
930 insertedAtIndex
= targetIndex
;
931 Q_ASSERT(previouslyInsertedCount
== 0);
937 // The indexes of all m_items must be adjusted, not only the index
939 const int itemDataCount
= m_itemData
.count();
940 for (int i
= 0; i
< itemDataCount
; ++i
) {
941 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
944 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
945 emit
itemsInserted(itemRanges
);
947 #ifdef KFILEITEMMODEL_DEBUG
948 kDebug() << "[TIME] Inserting of" << items
.count() << "items:" << timer
.elapsed();
952 void KFileItemModel::removeItems(const KFileItemList
& items
)
954 if (items
.isEmpty()) {
958 #ifdef KFILEITEMMODEL_DEBUG
959 kDebug() << "Removing " << items
.count() << "items";
964 QList
<ItemData
*> sortedItems
;
965 sortedItems
.reserve(items
.count());
966 foreach (const KFileItem
& item
, items
) {
967 const int index
= m_items
.value(item
.url(), -1);
969 sortedItems
.append(m_itemData
.at(index
));
972 sort(sortedItems
.begin(), sortedItems
.end());
974 QList
<int> indexesToRemove
;
975 indexesToRemove
.reserve(items
.count());
977 // Calculate the item ranges that will get deleted
978 KItemRangeList itemRanges
;
979 int removedAtIndex
= -1;
980 int removedCount
= 0;
982 foreach (const ItemData
* itemData
, sortedItems
) {
983 const KFileItem
& itemToRemove
= itemData
->item
;
985 const int previousTargetIndex
= targetIndex
;
986 while (targetIndex
< m_itemData
.count()) {
987 if (m_itemData
.at(targetIndex
)->item
.url() == itemToRemove
.url()) {
992 if (targetIndex
>= m_itemData
.count()) {
993 kWarning() << "Item that should be deleted has not been found!";
997 if (targetIndex
- previousTargetIndex
> 0 && removedAtIndex
>= 0) {
998 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
999 removedAtIndex
= targetIndex
;
1003 indexesToRemove
.append(targetIndex
);
1004 if (removedAtIndex
< 0) {
1005 removedAtIndex
= targetIndex
;
1012 for (int i
= indexesToRemove
.count() - 1; i
>= 0; --i
) {
1013 const int indexToRemove
= indexesToRemove
.at(i
);
1014 ItemData
* data
= m_itemData
.at(indexToRemove
);
1016 m_items
.remove(data
->item
.url());
1019 m_itemData
.removeAt(indexToRemove
);
1022 // The indexes of all m_items must be adjusted, not only the index
1023 // of the removed items
1024 const int itemDataCount
= m_itemData
.count();
1025 for (int i
= 0; i
< itemDataCount
; ++i
) {
1026 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
1030 m_rootExpansionLevel
= UninitializedRootExpansionLevel
;
1033 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
1034 emit
itemsRemoved(itemRanges
);
1037 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const KFileItemList
& items
) const
1039 QList
<ItemData
*> itemDataList
;
1040 itemDataList
.reserve(items
.count());
1042 foreach (const KFileItem
& item
, items
) {
1043 ItemData
* itemData
= new ItemData();
1044 itemData
->item
= item
;
1045 itemData
->values
= retrieveData(item
);
1046 itemData
->parent
= 0;
1048 const bool determineParent
= m_requestRole
[ExpansionLevelRole
]
1049 && itemData
->values
["expansionLevel"].toInt() > 0;
1050 if (determineParent
) {
1051 KUrl parentUrl
= item
.url().upUrl();
1052 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
1053 const int parentIndex
= m_items
.value(parentUrl
, -1);
1054 if (parentIndex
>= 0) {
1055 itemData
->parent
= m_itemData
.at(parentIndex
);
1057 kWarning() << "Parent item not found for" << item
.url();
1061 itemDataList
.append(itemData
);
1064 return itemDataList
;
1067 void KFileItemModel::removeExpandedItems()
1069 KFileItemList expandedItems
;
1071 const int maxIndex
= m_itemData
.count() - 1;
1072 for (int i
= 0; i
<= maxIndex
; ++i
) {
1073 const ItemData
* itemData
= m_itemData
.at(i
);
1074 if (itemData
->values
.value("expansionLevel").toInt() > 0) {
1075 expandedItems
.append(itemData
->item
);
1079 // The m_rootExpansionLevel may not get reset before all items with
1080 // a bigger expansionLevel have been removed.
1081 Q_ASSERT(m_rootExpansionLevel
>= 0);
1082 removeItems(expandedItems
);
1084 m_rootExpansionLevel
= UninitializedRootExpansionLevel
;
1085 m_expandedUrls
.clear();
1088 void KFileItemModel::resetRoles()
1090 for (int i
= 0; i
< RolesCount
; ++i
) {
1091 m_requestRole
[i
] = false;
1095 KFileItemModel::Role
KFileItemModel::roleIndex(const QByteArray
& role
) const
1097 static QHash
<QByteArray
, Role
> rolesHash
;
1098 if (rolesHash
.isEmpty()) {
1099 rolesHash
.insert("name", NameRole
);
1100 rolesHash
.insert("size", SizeRole
);
1101 rolesHash
.insert("date", DateRole
);
1102 rolesHash
.insert("permissions", PermissionsRole
);
1103 rolesHash
.insert("owner", OwnerRole
);
1104 rolesHash
.insert("group", GroupRole
);
1105 rolesHash
.insert("type", TypeRole
);
1106 rolesHash
.insert("destination", DestinationRole
);
1107 rolesHash
.insert("path", PathRole
);
1108 rolesHash
.insert("comment", CommentRole
);
1109 rolesHash
.insert("tags", TagsRole
);
1110 rolesHash
.insert("rating", RatingRole
);
1111 rolesHash
.insert("isDir", IsDirRole
);
1112 rolesHash
.insert("isExpanded", IsExpandedRole
);
1113 rolesHash
.insert("isExpandable", IsExpandableRole
);
1114 rolesHash
.insert("expansionLevel", ExpansionLevelRole
);
1116 return rolesHash
.value(role
, NoRole
);
1119 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
) const
1121 // It is important to insert only roles that are fast to retrieve. E.g.
1122 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1123 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1124 QHash
<QByteArray
, QVariant
> data
;
1125 data
.insert("iconPixmap", QPixmap());
1126 data
.insert("url", item
.url());
1128 const bool isDir
= item
.isDir();
1129 if (m_requestRole
[IsDirRole
]) {
1130 data
.insert("isDir", isDir
);
1133 if (m_requestRole
[NameRole
]) {
1134 data
.insert("name", item
.text());
1137 if (m_requestRole
[SizeRole
]) {
1139 data
.insert("size", QVariant());
1141 data
.insert("size", item
.size());
1145 if (m_requestRole
[DateRole
]) {
1146 // Don't use KFileItem::timeString() as this is too expensive when
1147 // having several thousands of items. Instead the formatting of the
1148 // date-time will be done on-demand by the view when the date will be shown.
1149 const KDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
1150 data
.insert("date", dateTime
.dateTime());
1153 if (m_requestRole
[PermissionsRole
]) {
1154 data
.insert("permissions", item
.permissionsString());
1157 if (m_requestRole
[OwnerRole
]) {
1158 data
.insert("owner", item
.user());
1161 if (m_requestRole
[GroupRole
]) {
1162 data
.insert("group", item
.group());
1165 if (m_requestRole
[DestinationRole
]) {
1166 QString destination
= item
.linkDest();
1167 if (destination
.isEmpty()) {
1168 destination
= i18nc("@item:intable", "No destination");
1170 data
.insert("destination", destination
);
1173 if (m_requestRole
[PathRole
]) {
1175 if (item
.url().protocol() == QLatin1String("trash")) {
1176 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1178 path
= item
.localPath();
1181 const int index
= path
.lastIndexOf(item
.text());
1182 path
= path
.mid(0, index
- 1);
1183 data
.insert("path", path
);
1186 if (m_requestRole
[IsExpandedRole
]) {
1187 data
.insert("isExpanded", false);
1190 if (m_requestRole
[IsExpandableRole
]) {
1191 data
.insert("isExpandable", item
.isDir() && item
.url() == item
.targetUrl());
1194 if (m_requestRole
[ExpansionLevelRole
]) {
1195 if (m_rootExpansionLevel
== UninitializedRootExpansionLevel
&& m_dirLister
.data()) {
1196 const KUrl rootUrl
= m_dirLister
.data()->url();
1197 const QString protocol
= rootUrl
.protocol();
1198 const bool forceRootExpansionLevel
= (protocol
== QLatin1String("trash") ||
1199 protocol
== QLatin1String("nepomuk") ||
1200 protocol
== QLatin1String("remote") ||
1201 protocol
.contains(QLatin1String("search")));
1202 if (forceRootExpansionLevel
) {
1203 m_rootExpansionLevel
= ForceRootExpansionLevel
;
1205 const QString rootDir
= rootUrl
.path(KUrl::AddTrailingSlash
);
1206 m_rootExpansionLevel
= rootDir
.count('/');
1210 if (m_rootExpansionLevel
== ForceRootExpansionLevel
) {
1211 data
.insert("expansionLevel", -1);
1213 const QString dir
= item
.url().directory(KUrl::AppendTrailingSlash
);
1214 const int level
= dir
.count('/') - m_rootExpansionLevel
;
1215 data
.insert("expansionLevel", level
);
1219 if (item
.isMimeTypeKnown()) {
1220 data
.insert("iconName", item
.iconName());
1222 if (m_requestRole
[TypeRole
]) {
1223 data
.insert("type", item
.mimeComment());
1230 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
) const
1234 if (m_rootExpansionLevel
>= 0) {
1235 result
= expansionLevelsCompare(a
, b
);
1237 // The items have parents with different expansion levels
1238 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1242 if (m_sortFoldersFirst
|| m_sortRole
== SizeRole
) {
1243 const bool isDirA
= a
->item
.isDir();
1244 const bool isDirB
= b
->item
.isDir();
1245 if (isDirA
&& !isDirB
) {
1247 } else if (!isDirA
&& isDirB
) {
1252 result
= sortRoleCompare(a
, b
);
1254 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1257 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
) const
1259 const KFileItem
& itemA
= a
->item
;
1260 const KFileItem
& itemB
= b
->item
;
1264 switch (m_sortRole
) {
1266 // The name role is handled as default fallback after the switch
1270 const KDateTime dateTimeA
= itemA
.time(KFileItem::ModificationTime
);
1271 const KDateTime dateTimeB
= itemB
.time(KFileItem::ModificationTime
);
1272 if (dateTimeA
< dateTimeB
) {
1274 } else if (dateTimeA
> dateTimeB
) {
1281 if (itemA
.isDir()) {
1282 Q_ASSERT(itemB
.isDir()); // see "if (m_sortFoldersFirst || m_sortRole == SizeRole)" above
1284 const QVariant valueA
= a
->values
.value("size");
1285 const QVariant valueB
= b
->values
.value("size");
1287 if (valueA
.isNull()) {
1289 } else if (valueB
.isNull()) {
1292 result
= valueA
.value
<KIO::filesize_t
>() - valueB
.value
<KIO::filesize_t
>();
1295 Q_ASSERT(!itemB
.isDir()); // see "if (m_sortFoldersFirst || m_sortRole == SizeRole)" above
1296 result
= itemA
.size() - itemB
.size();
1302 result
= QString::compare(a
->values
.value("type").toString(),
1303 b
->values
.value("type").toString());
1308 result
= QString::compare(a
->values
.value("comment").toString(),
1309 b
->values
.value("comment").toString());
1314 result
= QString::compare(a
->values
.value("tags").toString(),
1315 b
->values
.value("tags").toString());
1320 result
= a
->values
.value("rating").toInt() - b
->values
.value("rating").toInt();
1329 // The current sort role was sufficient to define an order
1333 // Fallback #1: Compare the text of the items
1334 result
= stringCompare(itemA
.text(), itemB
.text());
1339 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1340 result
= stringCompare(itemA
.name(m_caseSensitivity
== Qt::CaseInsensitive
),
1341 itemB
.name(m_caseSensitivity
== Qt::CaseInsensitive
));
1346 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1347 // equal. In this case a comparison of the URL is done which is unique in all cases
1348 // within KDirLister.
1349 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1352 void KFileItemModel::sort(QList
<ItemData
*>::iterator begin
,
1353 QList
<ItemData
*>::iterator end
)
1355 // The implementation is based on qStableSortHelper() from qalgorithms.h
1356 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1357 // In opposite to qStableSort() it allows to use a member-function for the comparison of elements.
1359 const int span
= end
- begin
;
1364 const QList
<ItemData
*>::iterator middle
= begin
+ span
/ 2;
1365 sort(begin
, middle
);
1367 merge(begin
, middle
, end
);
1370 void KFileItemModel::merge(QList
<ItemData
*>::iterator begin
,
1371 QList
<ItemData
*>::iterator pivot
,
1372 QList
<ItemData
*>::iterator end
)
1374 // The implementation is based on qMerge() from qalgorithms.h
1375 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1377 const int len1
= pivot
- begin
;
1378 const int len2
= end
- pivot
;
1380 if (len1
== 0 || len2
== 0) {
1384 if (len1
+ len2
== 2) {
1385 if (lessThan(*(begin
+ 1), *(begin
))) {
1386 qSwap(*begin
, *(begin
+ 1));
1391 QList
<ItemData
*>::iterator firstCut
;
1392 QList
<ItemData
*>::iterator secondCut
;
1395 const int len1Half
= len1
/ 2;
1396 firstCut
= begin
+ len1Half
;
1397 secondCut
= lowerBound(pivot
, end
, *firstCut
);
1398 len2Half
= secondCut
- pivot
;
1400 len2Half
= len2
/ 2;
1401 secondCut
= pivot
+ len2Half
;
1402 firstCut
= upperBound(begin
, pivot
, *secondCut
);
1405 reverse(firstCut
, pivot
);
1406 reverse(pivot
, secondCut
);
1407 reverse(firstCut
, secondCut
);
1409 const QList
<ItemData
*>::iterator newPivot
= firstCut
+ len2Half
;
1410 merge(begin
, firstCut
, newPivot
);
1411 merge(newPivot
, secondCut
, end
);
1414 QList
<KFileItemModel::ItemData
*>::iterator
KFileItemModel::lowerBound(QList
<ItemData
*>::iterator begin
,
1415 QList
<ItemData
*>::iterator end
,
1416 const ItemData
* value
)
1418 // The implementation is based on qLowerBound() from qalgorithms.h
1419 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1421 QList
<ItemData
*>::iterator middle
;
1422 int n
= int(end
- begin
);
1427 middle
= begin
+ half
;
1428 if (lessThan(*middle
, value
)) {
1438 QList
<KFileItemModel::ItemData
*>::iterator
KFileItemModel::upperBound(QList
<ItemData
*>::iterator begin
,
1439 QList
<ItemData
*>::iterator end
,
1440 const ItemData
* value
)
1442 // The implementation is based on qUpperBound() from qalgorithms.h
1443 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1445 QList
<ItemData
*>::iterator middle
;
1446 int n
= end
- begin
;
1451 middle
= begin
+ half
;
1452 if (lessThan(value
, *middle
)) {
1462 void KFileItemModel::reverse(QList
<ItemData
*>::iterator begin
,
1463 QList
<ItemData
*>::iterator end
)
1465 // The implementation is based on qReverse() from qalgorithms.h
1466 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1469 while (begin
< end
) {
1470 qSwap(*begin
++, *end
--);
1474 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
) const
1476 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1477 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1478 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1479 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1481 if (m_caseSensitivity
== Qt::CaseInsensitive
) {
1482 const int result
= m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseInsensitive
)
1483 : QString::compare(a
, b
, Qt::CaseInsensitive
);
1485 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1486 // comparison, still a deterministic sort order is required. A case sensitive
1487 // comparison is done as fallback.
1492 return m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseSensitive
)
1493 : QString::compare(a
, b
, Qt::CaseSensitive
);
1496 int KFileItemModel::expansionLevelsCompare(const ItemData
* a
, const ItemData
* b
) const
1498 const KUrl urlA
= a
->item
.url();
1499 const KUrl urlB
= b
->item
.url();
1500 if (urlA
.directory() == urlB
.directory()) {
1501 // Both items have the same directory as parent
1505 // Check whether one item is the parent of the other item
1506 if (urlA
.isParentOf(urlB
)) {
1507 return (sortOrder() == Qt::AscendingOrder
) ? -1 : +1;
1508 } else if (urlB
.isParentOf(urlA
)) {
1509 return (sortOrder() == Qt::AscendingOrder
) ? +1 : -1;
1512 // Determine the maximum common path of both items and
1513 // remember the index in 'index'
1514 const QString pathA
= urlA
.path();
1515 const QString pathB
= urlB
.path();
1517 const int maxIndex
= qMin(pathA
.length(), pathB
.length()) - 1;
1519 while (index
<= maxIndex
&& pathA
.at(index
) == pathB
.at(index
)) {
1522 if (index
> maxIndex
) {
1525 while ((pathA
.at(index
) != QLatin1Char('/') || pathB
.at(index
) != QLatin1Char('/')) && index
> 0) {
1529 // Determine the first sub-path after the common path and
1530 // check whether it represents a directory or already a file
1532 const QString subPathA
= subPath(a
->item
, pathA
, index
, &isDirA
);
1534 const QString subPathB
= subPath(b
->item
, pathB
, index
, &isDirB
);
1536 if (isDirA
&& !isDirB
) {
1537 return (sortOrder() == Qt::AscendingOrder
) ? -1 : +1;
1538 } else if (!isDirA
&& isDirB
) {
1539 return (sortOrder() == Qt::AscendingOrder
) ? +1 : -1;
1542 // Compare the items of the parents that represent the first
1543 // different path after the common path.
1544 const QString parentPathA
= pathA
.left(index
) + subPathA
;
1545 const QString parentPathB
= pathB
.left(index
) + subPathB
;
1547 const ItemData
* parentA
= a
;
1548 while (parentA
&& parentA
->item
.url().path() != parentPathA
) {
1549 parentA
= parentA
->parent
;
1552 const ItemData
* parentB
= b
;
1553 while (parentB
&& parentB
->item
.url().path() != parentPathB
) {
1554 parentB
= parentB
->parent
;
1557 if (parentA
&& parentB
) {
1558 return sortRoleCompare(parentA
, parentB
);
1561 kWarning() << "Child items without parent detected:" << a
->item
.url() << b
->item
.url();
1562 return QString::compare(urlA
.url(), urlB
.url(), Qt::CaseSensitive
);
1565 QString
KFileItemModel::subPath(const KFileItem
& item
,
1566 const QString
& itemPath
,
1571 const int pathIndex
= itemPath
.indexOf('/', start
+ 1);
1572 *isDir
= (pathIndex
> 0) || item
.isDir();
1573 return itemPath
.mid(start
, pathIndex
- start
);
1576 bool KFileItemModel::useMaximumUpdateInterval() const
1578 const KDirLister
* dirLister
= m_dirLister
.data();
1579 return dirLister
&& !dirLister
->url().isLocalFile();
1582 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1584 Q_ASSERT(!m_itemData
.isEmpty());
1586 const int maxIndex
= count() - 1;
1587 QList
<QPair
<int, QVariant
> > groups
;
1591 bool isLetter
= false;
1592 for (int i
= 0; i
<= maxIndex
; ++i
) {
1593 if (isChildItem(i
)) {
1597 const QString name
= m_itemData
.at(i
)->values
.value("name").toString();
1599 // Use the first character of the name as group indication
1600 QChar newFirstChar
= name
.at(0).toUpper();
1601 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1602 newFirstChar
= name
.at(1).toUpper();
1605 if (firstChar
!= newFirstChar
) {
1606 QString newGroupValue
;
1607 if (newFirstChar
>= QLatin1Char('A') && newFirstChar
<= QLatin1Char('Z')) {
1608 // Apply group 'A' - 'Z'
1609 newGroupValue
= newFirstChar
;
1611 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
1612 // Apply group '0 - 9' for any name that starts with a digit
1613 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
1617 // If the current group is 'A' - 'Z' check whether a locale character
1618 // fits into the existing group.
1619 // TODO: This does not work in the case if e.g. the group 'O' starts with
1620 // an umlaut 'O' -> provide unit-test to document this known issue
1621 const QChar
prevChar(firstChar
.unicode() - ushort(1));
1622 const QChar
nextChar(firstChar
.unicode() + ushort(1));
1623 const QString
currChar(newFirstChar
);
1624 const bool partOfCurrentGroup
= currChar
.localeAwareCompare(prevChar
) > 0 &&
1625 currChar
.localeAwareCompare(nextChar
) < 0;
1626 if (partOfCurrentGroup
) {
1630 newGroupValue
= i18nc("@title:group", "Others");
1634 if (newGroupValue
!= groupValue
) {
1635 groupValue
= newGroupValue
;
1636 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1639 firstChar
= newFirstChar
;
1645 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
1647 Q_ASSERT(!m_itemData
.isEmpty());
1649 const int maxIndex
= count() - 1;
1650 QList
<QPair
<int, QVariant
> > groups
;
1653 for (int i
= 0; i
<= maxIndex
; ++i
) {
1654 if (isChildItem(i
)) {
1658 const KFileItem
& item
= m_itemData
.at(i
)->item
;
1659 const KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
1660 QString newGroupValue
;
1661 if (!item
.isNull() && item
.isDir()) {
1662 newGroupValue
= i18nc("@title:group Size", "Folders");
1663 } else if (fileSize
< 5 * 1024 * 1024) {
1664 newGroupValue
= i18nc("@title:group Size", "Small");
1665 } else if (fileSize
< 10 * 1024 * 1024) {
1666 newGroupValue
= i18nc("@title:group Size", "Medium");
1668 newGroupValue
= i18nc("@title:group Size", "Big");
1671 if (newGroupValue
!= groupValue
) {
1672 groupValue
= newGroupValue
;
1673 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1680 QList
<QPair
<int, QVariant
> > KFileItemModel::dateRoleGroups() const
1682 Q_ASSERT(!m_itemData
.isEmpty());
1684 const int maxIndex
= count() - 1;
1685 QList
<QPair
<int, QVariant
> > groups
;
1687 const QDate currentDate
= KDateTime::currentLocalDateTime().date();
1689 int yearForCurrentWeek
= 0;
1690 int currentWeek
= currentDate
.weekNumber(&yearForCurrentWeek
);
1691 if (yearForCurrentWeek
== currentDate
.year() + 1) {
1695 QDate previousModifiedDate
;
1697 for (int i
= 0; i
<= maxIndex
; ++i
) {
1698 if (isChildItem(i
)) {
1702 const KDateTime modifiedTime
= m_itemData
.at(i
)->item
.time(KFileItem::ModificationTime
);
1703 const QDate modifiedDate
= modifiedTime
.date();
1704 if (modifiedDate
== previousModifiedDate
) {
1705 // The current item is in the same group as the previous item
1708 previousModifiedDate
= modifiedDate
;
1710 const int daysDistance
= modifiedDate
.daysTo(currentDate
);
1712 int yearForModifiedWeek
= 0;
1713 int modifiedWeek
= modifiedDate
.weekNumber(&yearForModifiedWeek
);
1714 if (yearForModifiedWeek
== modifiedDate
.year() + 1) {
1718 QString newGroupValue
;
1719 if (currentDate
.year() == modifiedDate
.year() && currentDate
.month() == modifiedDate
.month()) {
1720 if (modifiedWeek
> currentWeek
) {
1721 // Usecase: modified date = 2010-01-01, current date = 2010-01-22
1722 // modified week = 53, current week = 3
1725 switch (currentWeek
- modifiedWeek
) {
1727 switch (daysDistance
) {
1728 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
1729 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
1730 default: newGroupValue
= modifiedTime
.toString(i18nc("@title:group The week day name: %A", "%A"));
1734 newGroupValue
= i18nc("@title:group Date", "Last Week");
1737 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
1740 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
1744 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
1750 const QDate lastMonthDate
= currentDate
.addMonths(-1);
1751 if (lastMonthDate
.year() == modifiedDate
.year() && lastMonthDate
.month() == modifiedDate
.month()) {
1752 if (daysDistance
== 1) {
1753 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Yesterday (%B, %Y)"));
1754 } else if (daysDistance
<= 7) {
1755 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)"));
1756 } else if (daysDistance
<= 7 * 2) {
1757 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)"));
1758 } else if (daysDistance
<= 7 * 3) {
1759 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)"));
1760 } else if (daysDistance
<= 7 * 4) {
1761 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)"));
1763 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"));
1766 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"));
1770 if (newGroupValue
!= groupValue
) {
1771 groupValue
= newGroupValue
;
1772 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1779 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
1781 Q_ASSERT(!m_itemData
.isEmpty());
1783 const int maxIndex
= count() - 1;
1784 QList
<QPair
<int, QVariant
> > groups
;
1786 QString permissionsString
;
1788 for (int i
= 0; i
<= maxIndex
; ++i
) {
1789 if (isChildItem(i
)) {
1793 const ItemData
* itemData
= m_itemData
.at(i
);
1794 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
1795 if (newPermissionsString
== permissionsString
) {
1798 permissionsString
= newPermissionsString
;
1800 const QFileInfo
info(itemData
->item
.url().pathOrUrl());
1804 if (info
.permission(QFile::ReadUser
)) {
1805 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1807 if (info
.permission(QFile::WriteUser
)) {
1808 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1810 if (info
.permission(QFile::ExeUser
)) {
1811 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1813 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
1817 if (info
.permission(QFile::ReadGroup
)) {
1818 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1820 if (info
.permission(QFile::WriteGroup
)) {
1821 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1823 if (info
.permission(QFile::ExeGroup
)) {
1824 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1826 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
1828 // Set others string
1830 if (info
.permission(QFile::ReadOther
)) {
1831 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1833 if (info
.permission(QFile::WriteOther
)) {
1834 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1836 if (info
.permission(QFile::ExeOther
)) {
1837 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1839 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
1841 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
1842 if (newGroupValue
!= groupValue
) {
1843 groupValue
= newGroupValue
;
1844 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1851 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
1853 Q_ASSERT(!m_itemData
.isEmpty());
1855 const int maxIndex
= count() - 1;
1856 QList
<QPair
<int, QVariant
> > groups
;
1858 int groupValue
= -1;
1859 for (int i
= 0; i
<= maxIndex
; ++i
) {
1860 if (isChildItem(i
)) {
1863 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
1864 if (newGroupValue
!= groupValue
) {
1865 groupValue
= newGroupValue
;
1866 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1873 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
1875 Q_ASSERT(!m_itemData
.isEmpty());
1877 const int maxIndex
= count() - 1;
1878 QList
<QPair
<int, QVariant
> > groups
;
1880 bool isFirstGroupValue
= true;
1882 for (int i
= 0; i
<= maxIndex
; ++i
) {
1883 if (isChildItem(i
)) {
1886 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
1887 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
1888 groupValue
= newGroupValue
;
1889 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1890 isFirstGroupValue
= false;
1897 KFileItemList
KFileItemModel::childItems(const KFileItem
& item
) const
1899 KFileItemList items
;
1901 int index
= m_items
.value(item
.url(), -1);
1903 const int parentLevel
= m_itemData
.at(index
)->values
.value("expansionLevel").toInt();
1905 while (index
< m_itemData
.count() && m_itemData
.at(index
)->values
.value("expansionLevel").toInt() > parentLevel
) {
1906 items
.append(m_itemData
.at(index
)->item
);
1914 #include "kfileitemmodel.moc"