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"
24 #include <KGlobalSettings>
26 #include <KStringHandler>
32 // #define KFILEITEMMODEL_DEBUG
34 KFileItemModel::KFileItemModel(KDirLister
* dirLister
, QObject
* parent
) :
35 KItemModelBase("name", parent
),
36 m_dirLister(dirLister
),
37 m_naturalSorting(KGlobalSettings::naturalSorting()),
38 m_sortFoldersFirst(true),
41 m_caseSensitivity(Qt::CaseInsensitive
),
47 m_minimumUpdateIntervalTimer(0),
48 m_maximumUpdateIntervalTimer(0),
49 m_resortAllItemsTimer(0),
50 m_pendingItemsToInsert(),
51 m_pendingEmitLoadingCompleted(false),
53 m_expandedParentsCountRoot(UninitializedExpandedParentsCountRoot
),
57 // Apply default roles that should be determined
59 m_requestRole
[NameRole
] = true;
60 m_requestRole
[IsDirRole
] = true;
61 m_roles
.insert("name");
62 m_roles
.insert("isDir");
66 connect(dirLister
, SIGNAL(canceled()), this, SLOT(slotCanceled()));
67 connect(dirLister
, SIGNAL(completed(KUrl
)), this, SLOT(slotCompleted()));
68 connect(dirLister
, SIGNAL(newItems(KFileItemList
)), this, SLOT(slotNewItems(KFileItemList
)));
69 connect(dirLister
, SIGNAL(itemsDeleted(KFileItemList
)), this, SLOT(slotItemsDeleted(KFileItemList
)));
70 connect(dirLister
, SIGNAL(refreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)), this, SLOT(slotRefreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)));
71 connect(dirLister
, SIGNAL(clear()), this, SLOT(slotClear()));
72 connect(dirLister
, SIGNAL(clear(KUrl
)), this, SLOT(slotClear(KUrl
)));
74 // Although the layout engine of KItemListView is fast it is very inefficient to e.g.
75 // emit 50 itemsInserted()-signals each 100 ms. m_minimumUpdateIntervalTimer assures that updates
76 // are done in 1 second intervals for equal operations.
77 m_minimumUpdateIntervalTimer
= new QTimer(this);
78 m_minimumUpdateIntervalTimer
->setInterval(1000);
79 m_minimumUpdateIntervalTimer
->setSingleShot(true);
80 connect(m_minimumUpdateIntervalTimer
, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
82 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
83 // before the completed() or canceled() signal has been emitted.
84 m_maximumUpdateIntervalTimer
= new QTimer(this);
85 m_maximumUpdateIntervalTimer
->setInterval(2000);
86 m_maximumUpdateIntervalTimer
->setSingleShot(true);
87 connect(m_maximumUpdateIntervalTimer
, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
89 // When changing the value of an item which represents the sort-role a resorting must be
90 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
91 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
92 // resorting is postponed until the timer has been exceeded.
93 m_resortAllItemsTimer
= new QTimer(this);
94 m_resortAllItemsTimer
->setInterval(500);
95 m_resortAllItemsTimer
->setSingleShot(true);
96 connect(m_resortAllItemsTimer
, SIGNAL(timeout()), this, SLOT(resortAllItems()));
98 Q_ASSERT(m_minimumUpdateIntervalTimer
->interval() <= m_maximumUpdateIntervalTimer
->interval());
100 connect(KGlobalSettings::self(), SIGNAL(naturalSortingChanged()), this, SLOT(slotNaturalSortingChanged()));
103 KFileItemModel::~KFileItemModel()
105 qDeleteAll(m_itemData
);
109 int KFileItemModel::count() const
111 return m_itemData
.count();
114 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
116 if (index
>= 0 && index
< count()) {
117 return m_itemData
.at(index
)->values
;
119 return QHash
<QByteArray
, QVariant
>();
122 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
124 if (index
< 0 || index
>= count()) {
128 QHash
<QByteArray
, QVariant
> currentValues
= m_itemData
.at(index
)->values
;
130 // Determine which roles have been changed
131 QSet
<QByteArray
> changedRoles
;
132 QHashIterator
<QByteArray
, QVariant
> it(values
);
133 while (it
.hasNext()) {
135 const QByteArray role
= it
.key();
136 const QVariant value
= it
.value();
138 if (currentValues
[role
] != value
) {
139 currentValues
[role
] = value
;
140 changedRoles
.insert(role
);
144 if (changedRoles
.isEmpty()) {
148 m_itemData
[index
]->values
= currentValues
;
149 emit
itemsChanged(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
151 if (changedRoles
.contains(sortRole())) {
152 m_resortAllItemsTimer
->start();
158 void KFileItemModel::setSortFoldersFirst(bool foldersFirst
)
160 if (foldersFirst
!= m_sortFoldersFirst
) {
161 m_sortFoldersFirst
= foldersFirst
;
166 bool KFileItemModel::sortFoldersFirst() const
168 return m_sortFoldersFirst
;
171 void KFileItemModel::setShowHiddenFiles(bool show
)
173 KDirLister
* dirLister
= m_dirLister
.data();
175 dirLister
->setShowingDotFiles(show
);
176 dirLister
->emitChanges();
183 bool KFileItemModel::showHiddenFiles() const
185 const KDirLister
* dirLister
= m_dirLister
.data();
186 return dirLister
? dirLister
->showingDotFiles() : false;
189 void KFileItemModel::setShowFoldersOnly(bool enabled
)
191 KDirLister
* dirLister
= m_dirLister
.data();
193 dirLister
->setDirOnlyMode(enabled
);
197 bool KFileItemModel::showFoldersOnly() const
199 KDirLister
* dirLister
= m_dirLister
.data();
200 return dirLister
? dirLister
->dirOnlyMode() : false;
203 QMimeData
* KFileItemModel::createMimeData(const QSet
<int>& indexes
) const
205 QMimeData
* data
= new QMimeData();
207 // The following code has been taken from KDirModel::mimeData()
208 // (kdelibs/kio/kio/kdirmodel.cpp)
209 // Copyright (C) 2006 David Faure <faure@kde.org>
211 KUrl::List mostLocalUrls
;
212 bool canUseMostLocalUrls
= true;
214 QSetIterator
<int> it(indexes
);
215 while (it
.hasNext()) {
216 const int index
= it
.next();
217 const KFileItem item
= fileItem(index
);
218 if (!item
.isNull()) {
222 mostLocalUrls
<< item
.mostLocalUrl(isLocal
);
224 canUseMostLocalUrls
= false;
229 const bool different
= canUseMostLocalUrls
&& mostLocalUrls
!= urls
;
230 urls
= KDirModel::simplifiedUrlList(urls
); // TODO: Check if we still need KDirModel for this in KDE 5.0
232 mostLocalUrls
= KDirModel::simplifiedUrlList(mostLocalUrls
);
233 urls
.populateMimeData(mostLocalUrls
, data
);
235 urls
.populateMimeData(data
);
241 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
243 startFromIndex
= qMax(0, startFromIndex
);
244 for (int i
= startFromIndex
; i
< count(); ++i
) {
245 if (data(i
)["name"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
249 for (int i
= 0; i
< startFromIndex
; ++i
) {
250 if (data(i
)["name"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
257 bool KFileItemModel::supportsDropping(int index
) const
259 const KFileItem item
= fileItem(index
);
260 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
263 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
265 static QHash
<QByteArray
, QString
> description
;
266 if (description
.isEmpty()) {
268 const RoleInfoMap
* map
= rolesInfoMap(count
);
269 for (int i
= 0; i
< count
; ++i
) {
270 description
.insert(map
[i
].role
, map
[i
].roleTranslation
);
274 return description
.value(role
);
277 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
279 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
280 #ifdef KFILEITEMMODEL_DEBUG
284 switch (typeForRole(sortRole())) {
285 case NameRole
: m_groups
= nameRoleGroups(); break;
286 case SizeRole
: m_groups
= sizeRoleGroups(); break;
287 case DateRole
: m_groups
= dateRoleGroups(); break;
288 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
289 case OwnerRole
: m_groups
= genericStringRoleGroups("owner"); break;
290 case GroupRole
: m_groups
= genericStringRoleGroups("group"); break;
291 case TypeRole
: m_groups
= genericStringRoleGroups("type"); break;
292 case DestinationRole
: m_groups
= genericStringRoleGroups("destination"); break;
293 case PathRole
: m_groups
= genericStringRoleGroups("path"); break;
294 case CommentRole
: m_groups
= genericStringRoleGroups("comment"); break;
295 case TagsRole
: m_groups
= genericStringRoleGroups("tags"); break;
296 case RatingRole
: m_groups
= ratingRoleGroups(); break;
298 case IsDirRole
: break;
299 case IsExpandedRole
: break;
300 case ExpandedParentsCountRole
: break;
301 default: Q_ASSERT(false); break;
304 #ifdef KFILEITEMMODEL_DEBUG
305 kDebug() << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
312 KFileItem
KFileItemModel::fileItem(int index
) const
314 if (index
>= 0 && index
< count()) {
315 return m_itemData
.at(index
)->item
;
321 KFileItem
KFileItemModel::fileItem(const KUrl
& url
) const
323 const int index
= m_items
.value(url
, -1);
325 return m_itemData
.at(index
)->item
;
330 int KFileItemModel::index(const KFileItem
& item
) const
336 return m_items
.value(item
.url(), -1);
339 int KFileItemModel::index(const KUrl
& url
) const
341 KUrl urlToFind
= url
;
342 urlToFind
.adjustPath(KUrl::RemoveTrailingSlash
);
343 return m_items
.value(urlToFind
, -1);
346 KFileItem
KFileItemModel::rootItem() const
348 const KDirLister
* dirLister
= m_dirLister
.data();
350 return dirLister
->rootItem();
355 void KFileItemModel::clear()
360 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
362 if (m_roles
== roles
) {
368 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
369 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
370 if (supportedExpanding
&& !willSupportExpanding
) {
371 // No expanding is supported anymore. Take care to delete all items that have an expansion level
372 // that is not 0 (and hence are part of an expanded item).
373 removeExpandedItems();
380 QSetIterator
<QByteArray
> it(roles
);
381 while (it
.hasNext()) {
382 const QByteArray
& role
= it
.next();
383 m_requestRole
[typeForRole(role
)] = true;
387 // Update m_data with the changed requested roles
388 const int maxIndex
= count() - 1;
389 for (int i
= 0; i
<= maxIndex
; ++i
) {
390 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
);
393 kWarning() << "TODO: Emitting itemsChanged() with no information what has changed!";
394 emit
itemsChanged(KItemRangeList() << KItemRange(0, count()), QSet
<QByteArray
>());
398 QSet
<QByteArray
> KFileItemModel::roles() const
403 bool KFileItemModel::setExpanded(int index
, bool expanded
)
405 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
409 QHash
<QByteArray
, QVariant
> values
;
410 values
.insert("isExpanded", expanded
);
411 if (!setData(index
, values
)) {
415 KDirLister
* dirLister
= m_dirLister
.data();
416 const KUrl url
= m_itemData
.at(index
)->item
.url();
418 m_expandedUrls
.insert(url
);
421 dirLister
->openUrl(url
, KDirLister::Keep
);
425 m_expandedUrls
.remove(url
);
428 dirLister
->stop(url
);
431 KFileItemList itemsToRemove
;
432 const int expandedParentsCount
= data(index
)["expandedParentsCount"].toInt();
434 while (index
< count() && data(index
)["expandedParentsCount"].toInt() > expandedParentsCount
) {
435 itemsToRemove
.append(m_itemData
.at(index
)->item
);
438 removeItems(itemsToRemove
);
445 bool KFileItemModel::isExpanded(int index
) const
447 if (index
>= 0 && index
< count()) {
448 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
453 bool KFileItemModel::isExpandable(int index
) const
455 if (index
>= 0 && index
< count()) {
456 return m_itemData
.at(index
)->values
.value("isExpandable").toBool();
461 int KFileItemModel::expandedParentsCount(int index
) const
463 if (index
>= 0 && index
< count()) {
464 const int parentsCount
= m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt();
465 if (parentsCount
> 0) {
472 QSet
<KUrl
> KFileItemModel::expandedUrls() const
474 return m_expandedUrls
;
477 void KFileItemModel::restoreExpandedUrls(const QSet
<KUrl
>& urls
)
479 m_urlsToExpand
= urls
;
482 void KFileItemModel::expandParentItems(const KUrl
& url
)
484 const KDirLister
* dirLister
= m_dirLister
.data();
489 const int pos
= dirLister
->url().path().length();
491 // Assure that each sub-path of the URL that should be
492 // expanded is added to m_urlsToExpand. KDirLister
493 // does not care whether the parent-URL has already been
495 KUrl urlToExpand
= dirLister
->url();
496 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator());
497 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
498 urlToExpand
.addPath(subDirs
.at(i
));
499 m_urlsToExpand
.insert(urlToExpand
);
502 // KDirLister::open() must called at least once to trigger an initial
503 // loading. The pending URLs that must be restored are handled
504 // in slotCompleted().
505 QSetIterator
<KUrl
> it2(m_urlsToExpand
);
506 while (it2
.hasNext()) {
507 const int idx
= index(it2
.next());
508 if (idx
>= 0 && !isExpanded(idx
)) {
509 setExpanded(idx
, true);
515 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
517 if (m_filter
.pattern() != nameFilter
) {
518 dispatchPendingItemsToInsert();
520 m_filter
.setPattern(nameFilter
);
522 // Check which shown items from m_itemData must get
523 // hidden and hence moved to m_filteredItems.
524 KFileItemList newFilteredItems
;
526 foreach (ItemData
* itemData
, m_itemData
) {
527 if (!m_filter
.matches(itemData
->item
)) {
528 // Only filter non-expanded items as child items may never
529 // exist without a parent item
530 if (!itemData
->values
.value("isExpanded").toBool()) {
531 newFilteredItems
.append(itemData
->item
);
532 m_filteredItems
.insert(itemData
->item
);
537 removeItems(newFilteredItems
);
539 // Check which hidden items from m_filteredItems should
540 // get visible again and hence removed from m_filteredItems.
541 KFileItemList newVisibleItems
;
543 QMutableSetIterator
<KFileItem
> it(m_filteredItems
);
544 while (it
.hasNext()) {
545 const KFileItem item
= it
.next();
546 if (m_filter
.matches(item
)) {
547 newVisibleItems
.append(item
);
548 m_filteredItems
.remove(item
);
552 insertItems(newVisibleItems
);
556 QString
KFileItemModel::nameFilter() const
558 return m_filter
.pattern();
561 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
563 static QList
<RoleInfo
> rolesInfo
;
564 if (rolesInfo
.isEmpty()) {
566 const RoleInfoMap
* map
= rolesInfoMap(count
);
567 for (int i
= 0; i
< count
; ++i
) {
568 if (map
[i
].roleType
!= NoRole
) {
570 info
.role
= map
[i
].role
;
571 info
.translation
= map
[i
].roleTranslation
;
572 info
.group
= map
[i
].groupTranslation
;
573 rolesInfo
.append(info
);
581 void KFileItemModel::onGroupedSortingChanged(bool current
)
587 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
590 m_sortRole
= typeForRole(current
);
592 #ifdef KFILEITEMMODEL_DEBUG
593 if (!m_requestRole
[m_sortRole
]) {
594 kWarning() << "The sort-role has been changed to a role that has not been received yet";
601 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
608 void KFileItemModel::resortAllItems()
610 m_resortAllItemsTimer
->stop();
612 const int itemCount
= count();
613 if (itemCount
<= 0) {
617 #ifdef KFILEITEMMODEL_DEBUG
620 kDebug() << "===========================================================";
621 kDebug() << "Resorting" << itemCount
<< "items";
624 // Remember the order of the current URLs so
625 // that it can be determined which indexes have
626 // been moved because of the resorting.
628 oldUrls
.reserve(itemCount
);
629 foreach (const ItemData
* itemData
, m_itemData
) {
630 oldUrls
.append(itemData
->item
.url());
637 sort(m_itemData
.begin(), m_itemData
.end());
638 for (int i
= 0; i
< itemCount
; ++i
) {
639 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
642 // Determine the indexes that have been moved
643 QList
<int> movedToIndexes
;
644 movedToIndexes
.reserve(itemCount
);
645 for (int i
= 0; i
< itemCount
; i
++) {
646 const int newIndex
= m_items
.value(oldUrls
.at(i
).url());
647 movedToIndexes
.append(newIndex
);
650 // Don't check whether items have really been moved and always emit a
651 // itemsMoved() signal after resorting: In case of grouped items
652 // the groups might change even if the items themselves don't change their
653 // position. Let the receiver of the signal decide whether a check for moved
654 // items makes sense.
655 emit
itemsMoved(KItemRange(0, itemCount
), movedToIndexes
);
657 #ifdef KFILEITEMMODEL_DEBUG
658 kDebug() << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
662 void KFileItemModel::slotCompleted()
664 if (m_urlsToExpand
.isEmpty() && m_minimumUpdateIntervalTimer
->isActive()) {
665 // dispatchPendingItems() will be called when the timer
667 m_pendingEmitLoadingCompleted
= true;
671 m_pendingEmitLoadingCompleted
= false;
672 dispatchPendingItemsToInsert();
674 if (!m_urlsToExpand
.isEmpty()) {
675 // Try to find a URL that can be expanded.
676 // Note that the parent folder must be expanded before any of its subfolders become visible.
677 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
678 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
679 foreach(const KUrl
& url
, m_urlsToExpand
) {
680 const int index
= m_items
.value(url
, -1);
682 m_urlsToExpand
.remove(url
);
683 if (setExpanded(index
, true)) {
684 // The dir lister has been triggered. This slot will be called
685 // again after the directory has been expanded.
691 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
692 // if these URLs have been deleted in the meantime.
693 m_urlsToExpand
.clear();
696 emit
loadingCompleted();
697 m_minimumUpdateIntervalTimer
->start();
700 void KFileItemModel::slotCanceled()
702 m_minimumUpdateIntervalTimer
->stop();
703 m_maximumUpdateIntervalTimer
->stop();
704 dispatchPendingItemsToInsert();
707 void KFileItemModel::slotNewItems(const KFileItemList
& items
)
709 Q_ASSERT(!items
.isEmpty());
711 if (m_requestRole
[ExpandedParentsCountRole
] && m_expandedParentsCountRoot
>= 0) {
712 // To be able to compare whether the new items may be inserted as children
713 // of a parent item the pending items must be added to the model first.
714 dispatchPendingItemsToInsert();
716 KFileItem item
= items
.first();
718 // If the expanding of items is enabled, the call
719 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
720 // might result in emitting the same items twice due to the Keep-parameter.
721 // This case happens if an item gets expanded, collapsed and expanded again
722 // before the items could be loaded for the first expansion.
723 const int index
= m_items
.value(item
.url(), -1);
725 // The items are already part of the model.
729 // KDirLister keeps the children of items that got expanded once even if
730 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
731 // checked whether the parent for new items is still expanded.
732 KUrl parentUrl
= item
.url().upUrl();
733 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
734 const int parentIndex
= m_items
.value(parentUrl
, -1);
735 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
736 // The parent is not expanded.
741 if (m_filter
.pattern().isEmpty()) {
742 m_pendingItemsToInsert
.append(items
);
744 // The name-filter is active. Hide filtered items
745 // before inserting them into the model and remember
746 // the filtered items in m_filteredItems.
747 KFileItemList filteredItems
;
748 foreach (const KFileItem
& item
, items
) {
749 if (m_filter
.matches(item
)) {
750 filteredItems
.append(item
);
752 m_filteredItems
.insert(item
);
756 m_pendingItemsToInsert
.append(filteredItems
);
759 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer
->isActive()) {
760 // Assure that items get dispatched if no completed() or canceled() signal is
761 // emitted during the maximum update interval.
762 m_maximumUpdateIntervalTimer
->start();
766 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
768 dispatchPendingItemsToInsert();
770 KFileItemList itemsToRemove
= items
;
771 if (m_requestRole
[ExpandedParentsCountRole
] && m_expandedParentsCountRoot
>= 0) {
772 // Assure that removing a parent item also results in removing all children
773 foreach (const KFileItem
& item
, items
) {
774 itemsToRemove
.append(childItems(item
));
778 if (!m_filteredItems
.isEmpty()) {
779 foreach (const KFileItem
& item
, itemsToRemove
) {
780 m_filteredItems
.remove(item
);
784 removeItems(itemsToRemove
);
787 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
789 Q_ASSERT(!items
.isEmpty());
790 #ifdef KFILEITEMMODEL_DEBUG
791 kDebug() << "Refreshing" << items
.count() << "items";
796 // Get the indexes of all items that have been refreshed
798 indexes
.reserve(items
.count());
800 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
801 while (it
.hasNext()) {
802 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
803 const KFileItem
& oldItem
= itemPair
.first
;
804 const KFileItem
& newItem
= itemPair
.second
;
805 const int index
= m_items
.value(oldItem
.url(), -1);
807 m_itemData
[index
]->item
= newItem
;
808 m_itemData
[index
]->values
= retrieveData(newItem
);
809 m_items
.remove(oldItem
.url());
810 m_items
.insert(newItem
.url(), index
);
811 indexes
.append(index
);
815 // If the changed items have been created recently, they might not be in m_items yet.
816 // In that case, the list 'indexes' might be empty.
817 if (indexes
.isEmpty()) {
821 // Extract the item-ranges out of the changed indexes
824 KItemRangeList itemRangeList
;
825 int previousIndex
= indexes
.at(0);
826 int rangeIndex
= previousIndex
;
829 const int maxIndex
= indexes
.count() - 1;
830 for (int i
= 1; i
<= maxIndex
; ++i
) {
831 const int currentIndex
= indexes
.at(i
);
832 if (currentIndex
== previousIndex
+ 1) {
835 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
837 rangeIndex
= currentIndex
;
840 previousIndex
= currentIndex
;
843 if (rangeCount
> 0) {
844 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
847 emit
itemsChanged(itemRangeList
, m_roles
);
852 void KFileItemModel::slotClear()
854 #ifdef KFILEITEMMODEL_DEBUG
855 kDebug() << "Clearing all items";
858 m_filteredItems
.clear();
861 m_minimumUpdateIntervalTimer
->stop();
862 m_maximumUpdateIntervalTimer
->stop();
863 m_resortAllItemsTimer
->stop();
864 m_pendingItemsToInsert
.clear();
866 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
868 const int removedCount
= m_itemData
.count();
869 if (removedCount
> 0) {
870 qDeleteAll(m_itemData
);
873 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
876 m_expandedUrls
.clear();
879 void KFileItemModel::slotClear(const KUrl
& url
)
884 void KFileItemModel::slotNaturalSortingChanged()
886 m_naturalSorting
= KGlobalSettings::naturalSorting();
890 void KFileItemModel::dispatchPendingItemsToInsert()
892 if (!m_pendingItemsToInsert
.isEmpty()) {
893 insertItems(m_pendingItemsToInsert
);
894 m_pendingItemsToInsert
.clear();
897 if (m_pendingEmitLoadingCompleted
) {
898 emit
loadingCompleted();
902 void KFileItemModel::insertItems(const KFileItemList
& items
)
904 if (items
.isEmpty()) {
908 #ifdef KFILEITEMMODEL_DEBUG
911 kDebug() << "===========================================================";
912 kDebug() << "Inserting" << items
.count() << "items";
917 QList
<ItemData
*> sortedItems
= createItemDataList(items
);
918 sort(sortedItems
.begin(), sortedItems
.end());
920 #ifdef KFILEITEMMODEL_DEBUG
921 kDebug() << "[TIME] Sorting:" << timer
.elapsed();
924 KItemRangeList itemRanges
;
927 int insertedAtIndex
= -1; // Index for the current item-range
928 int insertedCount
= 0; // Count for the current item-range
929 int previouslyInsertedCount
= 0; // Sum of previously inserted items for all ranges
930 while (sourceIndex
< sortedItems
.count()) {
931 // Find target index from m_items to insert the current item
933 const int previousTargetIndex
= targetIndex
;
934 while (targetIndex
< m_itemData
.count()) {
935 if (!lessThan(m_itemData
.at(targetIndex
), sortedItems
.at(sourceIndex
))) {
941 if (targetIndex
- previousTargetIndex
> 0 && insertedAtIndex
>= 0) {
942 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
943 previouslyInsertedCount
+= insertedCount
;
944 insertedAtIndex
= targetIndex
- previouslyInsertedCount
;
948 // Insert item at the position targetIndex by transfering
949 // the ownership of the item-data from sortedItems to m_itemData.
950 // m_items will be inserted after the loop (see comment below)
951 m_itemData
.insert(targetIndex
, sortedItems
.at(sourceIndex
));
954 if (insertedAtIndex
< 0) {
955 insertedAtIndex
= targetIndex
;
956 Q_ASSERT(previouslyInsertedCount
== 0);
962 // The indexes of all m_items must be adjusted, not only the index
964 const int itemDataCount
= m_itemData
.count();
965 for (int i
= 0; i
< itemDataCount
; ++i
) {
966 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
969 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
970 emit
itemsInserted(itemRanges
);
972 #ifdef KFILEITEMMODEL_DEBUG
973 kDebug() << "[TIME] Inserting of" << items
.count() << "items:" << timer
.elapsed();
977 void KFileItemModel::removeItems(const KFileItemList
& items
)
979 if (items
.isEmpty()) {
983 #ifdef KFILEITEMMODEL_DEBUG
984 kDebug() << "Removing " << items
.count() << "items";
989 QList
<ItemData
*> sortedItems
;
990 sortedItems
.reserve(items
.count());
991 foreach (const KFileItem
& item
, items
) {
992 const int index
= m_items
.value(item
.url(), -1);
994 sortedItems
.append(m_itemData
.at(index
));
997 sort(sortedItems
.begin(), sortedItems
.end());
999 QList
<int> indexesToRemove
;
1000 indexesToRemove
.reserve(items
.count());
1002 // Calculate the item ranges that will get deleted
1003 KItemRangeList itemRanges
;
1004 int removedAtIndex
= -1;
1005 int removedCount
= 0;
1006 int targetIndex
= 0;
1007 foreach (const ItemData
* itemData
, sortedItems
) {
1008 const KFileItem
& itemToRemove
= itemData
->item
;
1010 const int previousTargetIndex
= targetIndex
;
1011 while (targetIndex
< m_itemData
.count()) {
1012 if (m_itemData
.at(targetIndex
)->item
.url() == itemToRemove
.url()) {
1017 if (targetIndex
>= m_itemData
.count()) {
1018 kWarning() << "Item that should be deleted has not been found!";
1022 if (targetIndex
- previousTargetIndex
> 0 && removedAtIndex
>= 0) {
1023 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
1024 removedAtIndex
= targetIndex
;
1028 indexesToRemove
.append(targetIndex
);
1029 if (removedAtIndex
< 0) {
1030 removedAtIndex
= targetIndex
;
1037 for (int i
= indexesToRemove
.count() - 1; i
>= 0; --i
) {
1038 const int indexToRemove
= indexesToRemove
.at(i
);
1039 ItemData
* data
= m_itemData
.at(indexToRemove
);
1041 m_items
.remove(data
->item
.url());
1044 m_itemData
.removeAt(indexToRemove
);
1047 // The indexes of all m_items must be adjusted, not only the index
1048 // of the removed items
1049 const int itemDataCount
= m_itemData
.count();
1050 for (int i
= 0; i
< itemDataCount
; ++i
) {
1051 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
1055 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
1058 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
1059 emit
itemsRemoved(itemRanges
);
1062 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const KFileItemList
& items
) const
1064 QList
<ItemData
*> itemDataList
;
1065 itemDataList
.reserve(items
.count());
1067 foreach (const KFileItem
& item
, items
) {
1068 ItemData
* itemData
= new ItemData();
1069 itemData
->item
= item
;
1070 itemData
->values
= retrieveData(item
);
1071 itemData
->parent
= 0;
1073 const bool determineParent
= m_requestRole
[ExpandedParentsCountRole
]
1074 && itemData
->values
["expandedParentsCount"].toInt() > 0;
1075 if (determineParent
) {
1076 KUrl parentUrl
= item
.url().upUrl();
1077 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
1078 const int parentIndex
= m_items
.value(parentUrl
, -1);
1079 if (parentIndex
>= 0) {
1080 itemData
->parent
= m_itemData
.at(parentIndex
);
1082 kWarning() << "Parent item not found for" << item
.url();
1086 itemDataList
.append(itemData
);
1089 return itemDataList
;
1092 void KFileItemModel::removeExpandedItems()
1094 KFileItemList expandedItems
;
1096 const int maxIndex
= m_itemData
.count() - 1;
1097 for (int i
= 0; i
<= maxIndex
; ++i
) {
1098 const ItemData
* itemData
= m_itemData
.at(i
);
1099 if (itemData
->values
.value("expandedParentsCount").toInt() > 0) {
1100 expandedItems
.append(itemData
->item
);
1104 // The m_expandedParentsCountRoot may not get reset before all items with
1105 // a bigger count have been removed.
1106 Q_ASSERT(m_expandedParentsCountRoot
>= 0);
1107 removeItems(expandedItems
);
1109 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
1110 m_expandedUrls
.clear();
1113 void KFileItemModel::resetRoles()
1115 for (int i
= 0; i
< RolesCount
; ++i
) {
1116 m_requestRole
[i
] = false;
1120 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1122 static QHash
<QByteArray
, RoleType
> roles
;
1123 if (roles
.isEmpty()) {
1124 // Insert user visible roles that can be accessed with
1125 // KFileItemModel::roleInformation()
1127 const RoleInfoMap
* map
= rolesInfoMap(count
);
1128 for (int i
= 0; i
< count
; ++i
) {
1129 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1132 // Insert internal roles (take care to synchronize the implementation
1133 // with KFileItemModel::roleForType() in case if a change is done).
1134 roles
.insert("isDir", IsDirRole
);
1135 roles
.insert("isExpanded", IsExpandedRole
);
1136 roles
.insert("isExpandable", IsExpandableRole
);
1137 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1139 Q_ASSERT(roles
.count() == RolesCount
);
1142 return roles
.value(role
, NoRole
);
1145 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1147 static QHash
<RoleType
, QByteArray
> roles
;
1148 if (roles
.isEmpty()) {
1149 // Insert user visible roles that can be accessed with
1150 // KFileItemModel::roleInformation()
1152 const RoleInfoMap
* map
= rolesInfoMap(count
);
1153 for (int i
= 0; i
< count
; ++i
) {
1154 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1157 // Insert internal roles (take care to synchronize the implementation
1158 // with KFileItemModel::typeForRole() in case if a change is done).
1159 roles
.insert(IsDirRole
, "isDir");
1160 roles
.insert(IsExpandedRole
, "isExpanded");
1161 roles
.insert(IsExpandableRole
, "isExpandable");
1162 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1164 Q_ASSERT(roles
.count() == RolesCount
);
1167 return roles
.value(roleType
);
1170 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
) const
1172 // It is important to insert only roles that are fast to retrieve. E.g.
1173 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1174 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1175 QHash
<QByteArray
, QVariant
> data
;
1176 data
.insert("iconPixmap", QPixmap());
1177 data
.insert("url", item
.url());
1179 const bool isDir
= item
.isDir();
1180 if (m_requestRole
[IsDirRole
]) {
1181 data
.insert("isDir", isDir
);
1184 if (m_requestRole
[NameRole
]) {
1185 data
.insert("name", item
.text());
1188 if (m_requestRole
[SizeRole
]) {
1190 data
.insert("size", QVariant());
1192 data
.insert("size", item
.size());
1196 if (m_requestRole
[DateRole
]) {
1197 // Don't use KFileItem::timeString() as this is too expensive when
1198 // having several thousands of items. Instead the formatting of the
1199 // date-time will be done on-demand by the view when the date will be shown.
1200 const KDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
1201 data
.insert("date", dateTime
.dateTime());
1204 if (m_requestRole
[PermissionsRole
]) {
1205 data
.insert("permissions", item
.permissionsString());
1208 if (m_requestRole
[OwnerRole
]) {
1209 data
.insert("owner", item
.user());
1212 if (m_requestRole
[GroupRole
]) {
1213 data
.insert("group", item
.group());
1216 if (m_requestRole
[DestinationRole
]) {
1217 QString destination
= item
.linkDest();
1218 if (destination
.isEmpty()) {
1219 destination
= i18nc("@item:intable", "No destination");
1221 data
.insert("destination", destination
);
1224 if (m_requestRole
[PathRole
]) {
1226 if (item
.url().protocol() == QLatin1String("trash")) {
1227 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1229 path
= item
.localPath();
1232 const int index
= path
.lastIndexOf(item
.text());
1233 path
= path
.mid(0, index
- 1);
1234 data
.insert("path", path
);
1237 if (m_requestRole
[IsExpandedRole
]) {
1238 data
.insert("isExpanded", false);
1241 if (m_requestRole
[IsExpandableRole
]) {
1242 data
.insert("isExpandable", item
.isDir() && item
.url() == item
.targetUrl());
1245 if (m_requestRole
[ExpandedParentsCountRole
]) {
1246 if (m_expandedParentsCountRoot
== UninitializedExpandedParentsCountRoot
&& m_dirLister
.data()) {
1247 const KUrl rootUrl
= m_dirLister
.data()->url();
1248 const QString protocol
= rootUrl
.protocol();
1249 const bool forceExpandedParentsCountRoot
= (protocol
== QLatin1String("trash") ||
1250 protocol
== QLatin1String("nepomuk") ||
1251 protocol
== QLatin1String("remote") ||
1252 protocol
.contains(QLatin1String("search")));
1253 if (forceExpandedParentsCountRoot
) {
1254 m_expandedParentsCountRoot
= ForceExpandedParentsCountRoot
;
1256 const QString rootDir
= rootUrl
.path(KUrl::AddTrailingSlash
);
1257 m_expandedParentsCountRoot
= rootDir
.count('/');
1261 if (m_expandedParentsCountRoot
== ForceExpandedParentsCountRoot
) {
1262 data
.insert("expandedParentsCount", -1);
1264 const QString dir
= item
.url().directory(KUrl::AppendTrailingSlash
);
1265 const int level
= dir
.count('/') - m_expandedParentsCountRoot
;
1266 data
.insert("expandedParentsCount", level
);
1270 if (item
.isMimeTypeKnown()) {
1271 data
.insert("iconName", item
.iconName());
1273 if (m_requestRole
[TypeRole
]) {
1274 data
.insert("type", item
.mimeComment());
1281 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
) const
1285 if (m_expandedParentsCountRoot
>= 0) {
1286 result
= expandedParentsCountCompare(a
, b
);
1288 // The items have parents with different expansion levels
1289 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1293 if (m_sortFoldersFirst
|| m_sortRole
== SizeRole
) {
1294 const bool isDirA
= a
->item
.isDir();
1295 const bool isDirB
= b
->item
.isDir();
1296 if (isDirA
&& !isDirB
) {
1298 } else if (!isDirA
&& isDirB
) {
1303 result
= sortRoleCompare(a
, b
);
1305 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1308 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
) const
1310 const KFileItem
& itemA
= a
->item
;
1311 const KFileItem
& itemB
= b
->item
;
1315 switch (m_sortRole
) {
1317 // The name role is handled as default fallback after the switch
1321 if (itemA
.isDir()) {
1322 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1323 Q_ASSERT(itemB
.isDir());
1325 const QVariant valueA
= a
->values
.value("size");
1326 const QVariant valueB
= b
->values
.value("size");
1327 if (valueA
.isNull() && valueB
.isNull()) {
1329 } else if (valueA
.isNull()) {
1331 } else if (valueB
.isNull()) {
1334 result
= valueA
.toInt() - valueB
.toInt();
1337 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1338 Q_ASSERT(!itemB
.isDir());
1339 const KIO::filesize_t sizeA
= itemA
.size();
1340 const KIO::filesize_t sizeB
= itemB
.size();
1341 if (sizeA
> sizeB
) {
1343 } else if (sizeA
< sizeB
) {
1353 const KDateTime dateTimeA
= itemA
.time(KFileItem::ModificationTime
);
1354 const KDateTime dateTimeB
= itemB
.time(KFileItem::ModificationTime
);
1355 if (dateTimeA
< dateTimeB
) {
1357 } else if (dateTimeA
> dateTimeB
) {
1364 result
= a
->values
.value("rating").toInt() - b
->values
.value("rating").toInt();
1368 case PermissionsRole
:
1372 case DestinationRole
:
1376 const QByteArray role
= roleForType(m_sortRole
);
1377 result
= QString::compare(a
->values
.value(role
).toString(),
1378 b
->values
.value(role
).toString());
1387 // The current sort role was sufficient to define an order
1391 // Fallback #1: Compare the text of the items
1392 result
= stringCompare(itemA
.text(), itemB
.text());
1397 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1398 result
= stringCompare(itemA
.name(m_caseSensitivity
== Qt::CaseInsensitive
),
1399 itemB
.name(m_caseSensitivity
== Qt::CaseInsensitive
));
1404 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1405 // equal. In this case a comparison of the URL is done which is unique in all cases
1406 // within KDirLister.
1407 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1410 void KFileItemModel::sort(QList
<ItemData
*>::iterator begin
,
1411 QList
<ItemData
*>::iterator end
)
1413 // The implementation is based on qStableSortHelper() from qalgorithms.h
1414 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1415 // In opposite to qStableSort() it allows to use a member-function for the comparison of elements.
1417 const int span
= end
- begin
;
1422 const QList
<ItemData
*>::iterator middle
= begin
+ span
/ 2;
1423 sort(begin
, middle
);
1425 merge(begin
, middle
, end
);
1428 void KFileItemModel::merge(QList
<ItemData
*>::iterator begin
,
1429 QList
<ItemData
*>::iterator pivot
,
1430 QList
<ItemData
*>::iterator end
)
1432 // The implementation is based on qMerge() from qalgorithms.h
1433 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1435 const int len1
= pivot
- begin
;
1436 const int len2
= end
- pivot
;
1438 if (len1
== 0 || len2
== 0) {
1442 if (len1
+ len2
== 2) {
1443 if (lessThan(*(begin
+ 1), *(begin
))) {
1444 qSwap(*begin
, *(begin
+ 1));
1449 QList
<ItemData
*>::iterator firstCut
;
1450 QList
<ItemData
*>::iterator secondCut
;
1453 const int len1Half
= len1
/ 2;
1454 firstCut
= begin
+ len1Half
;
1455 secondCut
= lowerBound(pivot
, end
, *firstCut
);
1456 len2Half
= secondCut
- pivot
;
1458 len2Half
= len2
/ 2;
1459 secondCut
= pivot
+ len2Half
;
1460 firstCut
= upperBound(begin
, pivot
, *secondCut
);
1463 reverse(firstCut
, pivot
);
1464 reverse(pivot
, secondCut
);
1465 reverse(firstCut
, secondCut
);
1467 const QList
<ItemData
*>::iterator newPivot
= firstCut
+ len2Half
;
1468 merge(begin
, firstCut
, newPivot
);
1469 merge(newPivot
, secondCut
, end
);
1472 QList
<KFileItemModel::ItemData
*>::iterator
KFileItemModel::lowerBound(QList
<ItemData
*>::iterator begin
,
1473 QList
<ItemData
*>::iterator end
,
1474 const ItemData
* value
)
1476 // The implementation is based on qLowerBound() from qalgorithms.h
1477 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1479 QList
<ItemData
*>::iterator middle
;
1480 int n
= int(end
- begin
);
1485 middle
= begin
+ half
;
1486 if (lessThan(*middle
, value
)) {
1496 QList
<KFileItemModel::ItemData
*>::iterator
KFileItemModel::upperBound(QList
<ItemData
*>::iterator begin
,
1497 QList
<ItemData
*>::iterator end
,
1498 const ItemData
* value
)
1500 // The implementation is based on qUpperBound() from qalgorithms.h
1501 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1503 QList
<ItemData
*>::iterator middle
;
1504 int n
= end
- begin
;
1509 middle
= begin
+ half
;
1510 if (lessThan(value
, *middle
)) {
1520 void KFileItemModel::reverse(QList
<ItemData
*>::iterator begin
,
1521 QList
<ItemData
*>::iterator end
)
1523 // The implementation is based on qReverse() from qalgorithms.h
1524 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1527 while (begin
< end
) {
1528 qSwap(*begin
++, *end
--);
1532 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
) const
1534 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1535 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1536 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1537 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1539 if (m_caseSensitivity
== Qt::CaseInsensitive
) {
1540 const int result
= m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseInsensitive
)
1541 : QString::compare(a
, b
, Qt::CaseInsensitive
);
1543 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1544 // comparison, still a deterministic sort order is required. A case sensitive
1545 // comparison is done as fallback.
1550 return m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseSensitive
)
1551 : QString::compare(a
, b
, Qt::CaseSensitive
);
1554 int KFileItemModel::expandedParentsCountCompare(const ItemData
* a
, const ItemData
* b
) const
1556 const KUrl urlA
= a
->item
.url();
1557 const KUrl urlB
= b
->item
.url();
1558 if (urlA
.directory() == urlB
.directory()) {
1559 // Both items have the same directory as parent
1563 // Check whether one item is the parent of the other item
1564 if (urlA
.isParentOf(urlB
)) {
1565 return (sortOrder() == Qt::AscendingOrder
) ? -1 : +1;
1566 } else if (urlB
.isParentOf(urlA
)) {
1567 return (sortOrder() == Qt::AscendingOrder
) ? +1 : -1;
1570 // Determine the maximum common path of both items and
1571 // remember the index in 'index'
1572 const QString pathA
= urlA
.path();
1573 const QString pathB
= urlB
.path();
1575 const int maxIndex
= qMin(pathA
.length(), pathB
.length()) - 1;
1577 while (index
<= maxIndex
&& pathA
.at(index
) == pathB
.at(index
)) {
1580 if (index
> maxIndex
) {
1583 while ((pathA
.at(index
) != QLatin1Char('/') || pathB
.at(index
) != QLatin1Char('/')) && index
> 0) {
1587 // Determine the first sub-path after the common path and
1588 // check whether it represents a directory or already a file
1590 const QString subPathA
= subPath(a
->item
, pathA
, index
, &isDirA
);
1592 const QString subPathB
= subPath(b
->item
, pathB
, index
, &isDirB
);
1594 if (isDirA
&& !isDirB
) {
1595 return (sortOrder() == Qt::AscendingOrder
) ? -1 : +1;
1596 } else if (!isDirA
&& isDirB
) {
1597 return (sortOrder() == Qt::AscendingOrder
) ? +1 : -1;
1600 // Compare the items of the parents that represent the first
1601 // different path after the common path.
1602 const QString parentPathA
= pathA
.left(index
) + subPathA
;
1603 const QString parentPathB
= pathB
.left(index
) + subPathB
;
1605 const ItemData
* parentA
= a
;
1606 while (parentA
&& parentA
->item
.url().path() != parentPathA
) {
1607 parentA
= parentA
->parent
;
1610 const ItemData
* parentB
= b
;
1611 while (parentB
&& parentB
->item
.url().path() != parentPathB
) {
1612 parentB
= parentB
->parent
;
1615 if (parentA
&& parentB
) {
1616 return sortRoleCompare(parentA
, parentB
);
1619 kWarning() << "Child items without parent detected:" << a
->item
.url() << b
->item
.url();
1620 return QString::compare(urlA
.url(), urlB
.url(), Qt::CaseSensitive
);
1623 QString
KFileItemModel::subPath(const KFileItem
& item
,
1624 const QString
& itemPath
,
1629 const int pathIndex
= itemPath
.indexOf('/', start
+ 1);
1630 *isDir
= (pathIndex
> 0) || item
.isDir();
1631 return itemPath
.mid(start
, pathIndex
- start
);
1634 bool KFileItemModel::useMaximumUpdateInterval() const
1636 const KDirLister
* dirLister
= m_dirLister
.data();
1637 return dirLister
&& !dirLister
->url().isLocalFile();
1640 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1642 Q_ASSERT(!m_itemData
.isEmpty());
1644 const int maxIndex
= count() - 1;
1645 QList
<QPair
<int, QVariant
> > groups
;
1649 bool isLetter
= false;
1650 for (int i
= 0; i
<= maxIndex
; ++i
) {
1651 if (isChildItem(i
)) {
1655 const QString name
= m_itemData
.at(i
)->values
.value("name").toString();
1657 // Use the first character of the name as group indication
1658 QChar newFirstChar
= name
.at(0).toUpper();
1659 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1660 newFirstChar
= name
.at(1).toUpper();
1663 if (firstChar
!= newFirstChar
) {
1664 QString newGroupValue
;
1665 if (newFirstChar
>= QLatin1Char('A') && newFirstChar
<= QLatin1Char('Z')) {
1666 // Apply group 'A' - 'Z'
1667 newGroupValue
= newFirstChar
;
1669 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
1670 // Apply group '0 - 9' for any name that starts with a digit
1671 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
1675 // If the current group is 'A' - 'Z' check whether a locale character
1676 // fits into the existing group.
1677 // TODO: This does not work in the case if e.g. the group 'O' starts with
1678 // an umlaut 'O' -> provide unit-test to document this known issue
1679 const QChar
prevChar(firstChar
.unicode() - ushort(1));
1680 const QChar
nextChar(firstChar
.unicode() + ushort(1));
1681 const QString
currChar(newFirstChar
);
1682 const bool partOfCurrentGroup
= currChar
.localeAwareCompare(prevChar
) > 0 &&
1683 currChar
.localeAwareCompare(nextChar
) < 0;
1684 if (partOfCurrentGroup
) {
1688 newGroupValue
= i18nc("@title:group", "Others");
1692 if (newGroupValue
!= groupValue
) {
1693 groupValue
= newGroupValue
;
1694 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1697 firstChar
= newFirstChar
;
1703 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
1705 Q_ASSERT(!m_itemData
.isEmpty());
1707 const int maxIndex
= count() - 1;
1708 QList
<QPair
<int, QVariant
> > groups
;
1711 for (int i
= 0; i
<= maxIndex
; ++i
) {
1712 if (isChildItem(i
)) {
1716 const KFileItem
& item
= m_itemData
.at(i
)->item
;
1717 const KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
1718 QString newGroupValue
;
1719 if (!item
.isNull() && item
.isDir()) {
1720 newGroupValue
= i18nc("@title:group Size", "Folders");
1721 } else if (fileSize
< 5 * 1024 * 1024) {
1722 newGroupValue
= i18nc("@title:group Size", "Small");
1723 } else if (fileSize
< 10 * 1024 * 1024) {
1724 newGroupValue
= i18nc("@title:group Size", "Medium");
1726 newGroupValue
= i18nc("@title:group Size", "Big");
1729 if (newGroupValue
!= groupValue
) {
1730 groupValue
= newGroupValue
;
1731 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1738 QList
<QPair
<int, QVariant
> > KFileItemModel::dateRoleGroups() const
1740 Q_ASSERT(!m_itemData
.isEmpty());
1742 const int maxIndex
= count() - 1;
1743 QList
<QPair
<int, QVariant
> > groups
;
1745 const QDate currentDate
= KDateTime::currentLocalDateTime().date();
1747 int yearForCurrentWeek
= 0;
1748 int currentWeek
= currentDate
.weekNumber(&yearForCurrentWeek
);
1749 if (yearForCurrentWeek
== currentDate
.year() + 1) {
1753 QDate previousModifiedDate
;
1755 for (int i
= 0; i
<= maxIndex
; ++i
) {
1756 if (isChildItem(i
)) {
1760 const KDateTime modifiedTime
= m_itemData
.at(i
)->item
.time(KFileItem::ModificationTime
);
1761 const QDate modifiedDate
= modifiedTime
.date();
1762 if (modifiedDate
== previousModifiedDate
) {
1763 // The current item is in the same group as the previous item
1766 previousModifiedDate
= modifiedDate
;
1768 const int daysDistance
= modifiedDate
.daysTo(currentDate
);
1770 int yearForModifiedWeek
= 0;
1771 int modifiedWeek
= modifiedDate
.weekNumber(&yearForModifiedWeek
);
1772 if (yearForModifiedWeek
== modifiedDate
.year() + 1) {
1776 QString newGroupValue
;
1777 if (currentDate
.year() == modifiedDate
.year() && currentDate
.month() == modifiedDate
.month()) {
1778 if (modifiedWeek
> currentWeek
) {
1779 // Usecase: modified date = 2010-01-01, current date = 2010-01-22
1780 // modified week = 53, current week = 3
1783 switch (currentWeek
- modifiedWeek
) {
1785 switch (daysDistance
) {
1786 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
1787 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
1788 default: newGroupValue
= modifiedTime
.toString(i18nc("@title:group The week day name: %A", "%A"));
1792 newGroupValue
= i18nc("@title:group Date", "Last Week");
1795 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
1798 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
1802 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
1808 const QDate lastMonthDate
= currentDate
.addMonths(-1);
1809 if (lastMonthDate
.year() == modifiedDate
.year() && lastMonthDate
.month() == modifiedDate
.month()) {
1810 if (daysDistance
== 1) {
1811 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Yesterday (%B, %Y)"));
1812 } else if (daysDistance
<= 7) {
1813 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)"));
1814 } else if (daysDistance
<= 7 * 2) {
1815 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)"));
1816 } else if (daysDistance
<= 7 * 3) {
1817 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)"));
1818 } else if (daysDistance
<= 7 * 4) {
1819 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)"));
1821 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"));
1824 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"));
1828 if (newGroupValue
!= groupValue
) {
1829 groupValue
= newGroupValue
;
1830 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1837 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
1839 Q_ASSERT(!m_itemData
.isEmpty());
1841 const int maxIndex
= count() - 1;
1842 QList
<QPair
<int, QVariant
> > groups
;
1844 QString permissionsString
;
1846 for (int i
= 0; i
<= maxIndex
; ++i
) {
1847 if (isChildItem(i
)) {
1851 const ItemData
* itemData
= m_itemData
.at(i
);
1852 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
1853 if (newPermissionsString
== permissionsString
) {
1856 permissionsString
= newPermissionsString
;
1858 const QFileInfo
info(itemData
->item
.url().pathOrUrl());
1862 if (info
.permission(QFile::ReadUser
)) {
1863 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1865 if (info
.permission(QFile::WriteUser
)) {
1866 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1868 if (info
.permission(QFile::ExeUser
)) {
1869 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1871 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
1875 if (info
.permission(QFile::ReadGroup
)) {
1876 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1878 if (info
.permission(QFile::WriteGroup
)) {
1879 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1881 if (info
.permission(QFile::ExeGroup
)) {
1882 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1884 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
1886 // Set others string
1888 if (info
.permission(QFile::ReadOther
)) {
1889 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1891 if (info
.permission(QFile::WriteOther
)) {
1892 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1894 if (info
.permission(QFile::ExeOther
)) {
1895 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1897 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
1899 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
1900 if (newGroupValue
!= groupValue
) {
1901 groupValue
= newGroupValue
;
1902 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1909 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
1911 Q_ASSERT(!m_itemData
.isEmpty());
1913 const int maxIndex
= count() - 1;
1914 QList
<QPair
<int, QVariant
> > groups
;
1916 int groupValue
= -1;
1917 for (int i
= 0; i
<= maxIndex
; ++i
) {
1918 if (isChildItem(i
)) {
1921 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
1922 if (newGroupValue
!= groupValue
) {
1923 groupValue
= newGroupValue
;
1924 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1931 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
1933 Q_ASSERT(!m_itemData
.isEmpty());
1935 const int maxIndex
= count() - 1;
1936 QList
<QPair
<int, QVariant
> > groups
;
1938 bool isFirstGroupValue
= true;
1940 for (int i
= 0; i
<= maxIndex
; ++i
) {
1941 if (isChildItem(i
)) {
1944 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
1945 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
1946 groupValue
= newGroupValue
;
1947 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1948 isFirstGroupValue
= false;
1955 KFileItemList
KFileItemModel::childItems(const KFileItem
& item
) const
1957 KFileItemList items
;
1959 int index
= m_items
.value(item
.url(), -1);
1961 const int parentLevel
= m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt();
1963 while (index
< m_itemData
.count() && m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt() > parentLevel
) {
1964 items
.append(m_itemData
.at(index
)->item
);
1972 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
1974 static const RoleInfoMap rolesInfoMap
[] = {
1975 // role roleType role translation group translation
1976 { 0, NoRole
, 0, 0, 0, 0 },
1977 { "name", NameRole
, I18N_NOOP2_NOSTRIP("@label", "Name"), 0, 0 },
1978 { "size", SizeRole
, I18N_NOOP2_NOSTRIP("@label", "Size"), 0, 0 },
1979 { "date", DateRole
, I18N_NOOP2_NOSTRIP("@label", "Date"), 0, 0 },
1980 { "permissions", PermissionsRole
, I18N_NOOP2_NOSTRIP("@label", "Permissions"), 0, 0 },
1981 { "owner", OwnerRole
, I18N_NOOP2_NOSTRIP("@label", "Owner"), 0, 0 },
1982 { "group", GroupRole
, I18N_NOOP2_NOSTRIP("@label", "Group"), 0, 0 },
1983 { "type", TypeRole
, I18N_NOOP2_NOSTRIP("@label", "Type"), 0, 0 },
1984 { "destination", DestinationRole
, I18N_NOOP2_NOSTRIP("@label", "Link Destination"), 0, 0 },
1985 { "path", PathRole
, I18N_NOOP2_NOSTRIP("@label", "Path"), 0, 0 },
1986 { "comment", CommentRole
, I18N_NOOP2_NOSTRIP("@label", "Comment"), 0, 0 },
1987 { "tags", TagsRole
, I18N_NOOP2_NOSTRIP("@label", "Tags"), 0, 0 },
1988 { "rating", RatingRole
, I18N_NOOP2_NOSTRIP("@label", "Rating"), 0, 0 }
1991 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
1992 return rolesInfoMap
;
1995 #include "kfileitemmodel.moc"