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_maximumUpdateIntervalTimer(0),
48 m_resortAllItemsTimer(0),
49 m_pendingItemsToInsert(),
51 m_expandedParentsCountRoot(UninitializedExpandedParentsCountRoot
),
55 // Apply default roles that should be determined
57 m_requestRole
[NameRole
] = true;
58 m_requestRole
[IsDirRole
] = true;
59 m_roles
.insert("name");
60 m_roles
.insert("isDir");
64 connect(dirLister
, SIGNAL(canceled()), this, SLOT(slotCanceled()));
65 connect(dirLister
, SIGNAL(completed(KUrl
)), this, SLOT(slotCompleted()));
66 connect(dirLister
, SIGNAL(newItems(KFileItemList
)), this, SLOT(slotNewItems(KFileItemList
)));
67 connect(dirLister
, SIGNAL(itemsDeleted(KFileItemList
)), this, SLOT(slotItemsDeleted(KFileItemList
)));
68 connect(dirLister
, SIGNAL(refreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)), this, SLOT(slotRefreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)));
69 connect(dirLister
, SIGNAL(clear()), this, SLOT(slotClear()));
70 connect(dirLister
, SIGNAL(clear(KUrl
)), this, SLOT(slotClear(KUrl
)));
72 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
73 // before the completed() or canceled() signal has been emitted.
74 m_maximumUpdateIntervalTimer
= new QTimer(this);
75 m_maximumUpdateIntervalTimer
->setInterval(2000);
76 m_maximumUpdateIntervalTimer
->setSingleShot(true);
77 connect(m_maximumUpdateIntervalTimer
, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
79 // When changing the value of an item which represents the sort-role a resorting must be
80 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
81 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
82 // resorting is postponed until the timer has been exceeded.
83 m_resortAllItemsTimer
= new QTimer(this);
84 m_resortAllItemsTimer
->setInterval(500);
85 m_resortAllItemsTimer
->setSingleShot(true);
86 connect(m_resortAllItemsTimer
, SIGNAL(timeout()), this, SLOT(resortAllItems()));
88 connect(KGlobalSettings::self(), SIGNAL(naturalSortingChanged()), this, SLOT(slotNaturalSortingChanged()));
91 KFileItemModel::~KFileItemModel()
93 qDeleteAll(m_itemData
);
97 int KFileItemModel::count() const
99 return m_itemData
.count();
102 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
104 if (index
>= 0 && index
< count()) {
105 return m_itemData
.at(index
)->values
;
107 return QHash
<QByteArray
, QVariant
>();
110 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
112 if (index
< 0 || index
>= count()) {
116 QHash
<QByteArray
, QVariant
> currentValues
= m_itemData
.at(index
)->values
;
118 // Determine which roles have been changed
119 QSet
<QByteArray
> changedRoles
;
120 QHashIterator
<QByteArray
, QVariant
> it(values
);
121 while (it
.hasNext()) {
123 const QByteArray role
= it
.key();
124 const QVariant value
= it
.value();
126 if (currentValues
[role
] != value
) {
127 currentValues
[role
] = value
;
128 changedRoles
.insert(role
);
132 if (changedRoles
.isEmpty()) {
136 m_itemData
[index
]->values
= currentValues
;
137 emit
itemsChanged(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
139 if (changedRoles
.contains(sortRole())) {
140 m_resortAllItemsTimer
->start();
146 void KFileItemModel::setSortFoldersFirst(bool foldersFirst
)
148 if (foldersFirst
!= m_sortFoldersFirst
) {
149 m_sortFoldersFirst
= foldersFirst
;
154 bool KFileItemModel::sortFoldersFirst() const
156 return m_sortFoldersFirst
;
159 void KFileItemModel::setShowHiddenFiles(bool show
)
161 KDirLister
* dirLister
= m_dirLister
.data();
163 dirLister
->setShowingDotFiles(show
);
164 dirLister
->emitChanges();
171 bool KFileItemModel::showHiddenFiles() const
173 const KDirLister
* dirLister
= m_dirLister
.data();
174 return dirLister
? dirLister
->showingDotFiles() : false;
177 void KFileItemModel::setShowFoldersOnly(bool enabled
)
179 KDirLister
* dirLister
= m_dirLister
.data();
181 dirLister
->setDirOnlyMode(enabled
);
185 bool KFileItemModel::showFoldersOnly() const
187 KDirLister
* dirLister
= m_dirLister
.data();
188 return dirLister
? dirLister
->dirOnlyMode() : false;
191 QMimeData
* KFileItemModel::createMimeData(const QSet
<int>& indexes
) const
193 QMimeData
* data
= new QMimeData();
195 // The following code has been taken from KDirModel::mimeData()
196 // (kdelibs/kio/kio/kdirmodel.cpp)
197 // Copyright (C) 2006 David Faure <faure@kde.org>
199 KUrl::List mostLocalUrls
;
200 bool canUseMostLocalUrls
= true;
202 QSetIterator
<int> it(indexes
);
203 while (it
.hasNext()) {
204 const int index
= it
.next();
205 const KFileItem item
= fileItem(index
);
206 if (!item
.isNull()) {
210 mostLocalUrls
<< item
.mostLocalUrl(isLocal
);
212 canUseMostLocalUrls
= false;
217 const bool different
= canUseMostLocalUrls
&& mostLocalUrls
!= urls
;
218 urls
= KDirModel::simplifiedUrlList(urls
); // TODO: Check if we still need KDirModel for this in KDE 5.0
220 mostLocalUrls
= KDirModel::simplifiedUrlList(mostLocalUrls
);
221 urls
.populateMimeData(mostLocalUrls
, data
);
223 urls
.populateMimeData(data
);
229 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
231 startFromIndex
= qMax(0, startFromIndex
);
232 for (int i
= startFromIndex
; i
< count(); ++i
) {
233 if (data(i
)["name"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
237 for (int i
= 0; i
< startFromIndex
; ++i
) {
238 if (data(i
)["name"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
245 bool KFileItemModel::supportsDropping(int index
) const
247 const KFileItem item
= fileItem(index
);
248 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
251 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
253 static QHash
<QByteArray
, QString
> description
;
254 if (description
.isEmpty()) {
256 const RoleInfoMap
* map
= rolesInfoMap(count
);
257 for (int i
= 0; i
< count
; ++i
) {
258 description
.insert(map
[i
].role
, map
[i
].roleTranslation
);
262 return description
.value(role
);
265 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
267 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
268 #ifdef KFILEITEMMODEL_DEBUG
272 switch (typeForRole(sortRole())) {
273 case NameRole
: m_groups
= nameRoleGroups(); break;
274 case SizeRole
: m_groups
= sizeRoleGroups(); break;
275 case DateRole
: m_groups
= dateRoleGroups(); break;
276 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
277 case OwnerRole
: m_groups
= genericStringRoleGroups("owner"); break;
278 case GroupRole
: m_groups
= genericStringRoleGroups("group"); break;
279 case TypeRole
: m_groups
= genericStringRoleGroups("type"); break;
280 case DestinationRole
: m_groups
= genericStringRoleGroups("destination"); break;
281 case PathRole
: m_groups
= genericStringRoleGroups("path"); break;
282 case CommentRole
: m_groups
= genericStringRoleGroups("comment"); break;
283 case TagsRole
: m_groups
= genericStringRoleGroups("tags"); break;
284 case RatingRole
: m_groups
= ratingRoleGroups(); break;
286 case IsDirRole
: break;
287 case IsExpandedRole
: break;
288 case ExpandedParentsCountRole
: break;
289 default: Q_ASSERT(false); break;
292 #ifdef KFILEITEMMODEL_DEBUG
293 kDebug() << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
300 KFileItem
KFileItemModel::fileItem(int index
) const
302 if (index
>= 0 && index
< count()) {
303 return m_itemData
.at(index
)->item
;
309 KFileItem
KFileItemModel::fileItem(const KUrl
& url
) const
311 const int index
= m_items
.value(url
, -1);
313 return m_itemData
.at(index
)->item
;
318 int KFileItemModel::index(const KFileItem
& item
) const
324 return m_items
.value(item
.url(), -1);
327 int KFileItemModel::index(const KUrl
& url
) const
329 KUrl urlToFind
= url
;
330 urlToFind
.adjustPath(KUrl::RemoveTrailingSlash
);
331 return m_items
.value(urlToFind
, -1);
334 KFileItem
KFileItemModel::rootItem() const
336 const KDirLister
* dirLister
= m_dirLister
.data();
338 return dirLister
->rootItem();
343 void KFileItemModel::clear()
348 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
350 if (m_roles
== roles
) {
356 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
357 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
358 if (supportedExpanding
&& !willSupportExpanding
) {
359 // No expanding is supported anymore. Take care to delete all items that have an expansion level
360 // that is not 0 (and hence are part of an expanded item).
361 removeExpandedItems();
368 QSetIterator
<QByteArray
> it(roles
);
369 while (it
.hasNext()) {
370 const QByteArray
& role
= it
.next();
371 m_requestRole
[typeForRole(role
)] = true;
375 // Update m_data with the changed requested roles
376 const int maxIndex
= count() - 1;
377 for (int i
= 0; i
<= maxIndex
; ++i
) {
378 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
);
381 kWarning() << "TODO: Emitting itemsChanged() with no information what has changed!";
382 emit
itemsChanged(KItemRangeList() << KItemRange(0, count()), QSet
<QByteArray
>());
386 QSet
<QByteArray
> KFileItemModel::roles() const
391 bool KFileItemModel::setExpanded(int index
, bool expanded
)
393 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
397 QHash
<QByteArray
, QVariant
> values
;
398 values
.insert("isExpanded", expanded
);
399 if (!setData(index
, values
)) {
403 KDirLister
* dirLister
= m_dirLister
.data();
404 const KUrl url
= m_itemData
.at(index
)->item
.url();
406 m_expandedUrls
.insert(url
);
409 dirLister
->openUrl(url
, KDirLister::Keep
);
413 m_expandedUrls
.remove(url
);
416 dirLister
->stop(url
);
419 KFileItemList itemsToRemove
;
420 const int expandedParentsCount
= data(index
)["expandedParentsCount"].toInt();
422 while (index
< count() && data(index
)["expandedParentsCount"].toInt() > expandedParentsCount
) {
423 itemsToRemove
.append(m_itemData
.at(index
)->item
);
426 removeItems(itemsToRemove
);
433 bool KFileItemModel::isExpanded(int index
) const
435 if (index
>= 0 && index
< count()) {
436 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
441 bool KFileItemModel::isExpandable(int index
) const
443 if (index
>= 0 && index
< count()) {
444 return m_itemData
.at(index
)->values
.value("isExpandable").toBool();
449 int KFileItemModel::expandedParentsCount(int index
) const
451 if (index
>= 0 && index
< count()) {
452 const int parentsCount
= m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt();
453 if (parentsCount
> 0) {
460 QSet
<KUrl
> KFileItemModel::expandedUrls() const
462 return m_expandedUrls
;
465 void KFileItemModel::restoreExpandedUrls(const QSet
<KUrl
>& urls
)
467 m_urlsToExpand
= urls
;
470 void KFileItemModel::expandParentItems(const KUrl
& url
)
472 const KDirLister
* dirLister
= m_dirLister
.data();
477 const int pos
= dirLister
->url().path().length();
479 // Assure that each sub-path of the URL that should be
480 // expanded is added to m_urlsToExpand. KDirLister
481 // does not care whether the parent-URL has already been
483 KUrl urlToExpand
= dirLister
->url();
484 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator());
485 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
486 urlToExpand
.addPath(subDirs
.at(i
));
487 m_urlsToExpand
.insert(urlToExpand
);
490 // KDirLister::open() must called at least once to trigger an initial
491 // loading. The pending URLs that must be restored are handled
492 // in slotCompleted().
493 QSetIterator
<KUrl
> it2(m_urlsToExpand
);
494 while (it2
.hasNext()) {
495 const int idx
= index(it2
.next());
496 if (idx
>= 0 && !isExpanded(idx
)) {
497 setExpanded(idx
, true);
503 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
505 if (m_filter
.pattern() != nameFilter
) {
506 dispatchPendingItemsToInsert();
508 m_filter
.setPattern(nameFilter
);
510 // Check which shown items from m_itemData must get
511 // hidden and hence moved to m_filteredItems.
512 KFileItemList newFilteredItems
;
514 foreach (ItemData
* itemData
, m_itemData
) {
515 if (!m_filter
.matches(itemData
->item
)) {
516 // Only filter non-expanded items as child items may never
517 // exist without a parent item
518 if (!itemData
->values
.value("isExpanded").toBool()) {
519 newFilteredItems
.append(itemData
->item
);
520 m_filteredItems
.insert(itemData
->item
);
525 removeItems(newFilteredItems
);
527 // Check which hidden items from m_filteredItems should
528 // get visible again and hence removed from m_filteredItems.
529 KFileItemList newVisibleItems
;
531 QMutableSetIterator
<KFileItem
> it(m_filteredItems
);
532 while (it
.hasNext()) {
533 const KFileItem item
= it
.next();
534 if (m_filter
.matches(item
)) {
535 newVisibleItems
.append(item
);
536 m_filteredItems
.remove(item
);
540 insertItems(newVisibleItems
);
544 QString
KFileItemModel::nameFilter() const
546 return m_filter
.pattern();
549 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
551 static QList
<RoleInfo
> rolesInfo
;
552 if (rolesInfo
.isEmpty()) {
554 const RoleInfoMap
* map
= rolesInfoMap(count
);
555 for (int i
= 0; i
< count
; ++i
) {
556 if (map
[i
].roleType
!= NoRole
) {
558 info
.role
= map
[i
].role
;
559 info
.translation
= map
[i
].roleTranslation
;
560 info
.group
= map
[i
].groupTranslation
;
561 rolesInfo
.append(info
);
569 void KFileItemModel::onGroupedSortingChanged(bool current
)
575 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
578 m_sortRole
= typeForRole(current
);
580 #ifdef KFILEITEMMODEL_DEBUG
581 if (!m_requestRole
[m_sortRole
]) {
582 kWarning() << "The sort-role has been changed to a role that has not been received yet";
589 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
596 void KFileItemModel::resortAllItems()
598 m_resortAllItemsTimer
->stop();
600 const int itemCount
= count();
601 if (itemCount
<= 0) {
605 #ifdef KFILEITEMMODEL_DEBUG
608 kDebug() << "===========================================================";
609 kDebug() << "Resorting" << itemCount
<< "items";
612 // Remember the order of the current URLs so
613 // that it can be determined which indexes have
614 // been moved because of the resorting.
616 oldUrls
.reserve(itemCount
);
617 foreach (const ItemData
* itemData
, m_itemData
) {
618 oldUrls
.append(itemData
->item
.url());
625 sort(m_itemData
.begin(), m_itemData
.end());
626 for (int i
= 0; i
< itemCount
; ++i
) {
627 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
630 // Determine the indexes that have been moved
631 QList
<int> movedToIndexes
;
632 movedToIndexes
.reserve(itemCount
);
633 for (int i
= 0; i
< itemCount
; i
++) {
634 const int newIndex
= m_items
.value(oldUrls
.at(i
).url());
635 movedToIndexes
.append(newIndex
);
638 // Don't check whether items have really been moved and always emit a
639 // itemsMoved() signal after resorting: In case of grouped items
640 // the groups might change even if the items themselves don't change their
641 // position. Let the receiver of the signal decide whether a check for moved
642 // items makes sense.
643 emit
itemsMoved(KItemRange(0, itemCount
), movedToIndexes
);
645 #ifdef KFILEITEMMODEL_DEBUG
646 kDebug() << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
650 void KFileItemModel::slotCompleted()
652 dispatchPendingItemsToInsert();
654 if (!m_urlsToExpand
.isEmpty()) {
655 // Try to find a URL that can be expanded.
656 // Note that the parent folder must be expanded before any of its subfolders become visible.
657 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
658 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
659 foreach(const KUrl
& url
, m_urlsToExpand
) {
660 const int index
= m_items
.value(url
, -1);
662 m_urlsToExpand
.remove(url
);
663 if (setExpanded(index
, true)) {
664 // The dir lister has been triggered. This slot will be called
665 // again after the directory has been expanded.
671 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
672 // if these URLs have been deleted in the meantime.
673 m_urlsToExpand
.clear();
676 emit
loadingCompleted();
679 void KFileItemModel::slotCanceled()
681 m_maximumUpdateIntervalTimer
->stop();
682 dispatchPendingItemsToInsert();
685 void KFileItemModel::slotNewItems(const KFileItemList
& items
)
687 Q_ASSERT(!items
.isEmpty());
689 if (m_requestRole
[ExpandedParentsCountRole
] && m_expandedParentsCountRoot
>= 0) {
690 // To be able to compare whether the new items may be inserted as children
691 // of a parent item the pending items must be added to the model first.
692 dispatchPendingItemsToInsert();
694 KFileItem item
= items
.first();
696 // If the expanding of items is enabled, the call
697 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
698 // might result in emitting the same items twice due to the Keep-parameter.
699 // This case happens if an item gets expanded, collapsed and expanded again
700 // before the items could be loaded for the first expansion.
701 const int index
= m_items
.value(item
.url(), -1);
703 // The items are already part of the model.
707 // KDirLister keeps the children of items that got expanded once even if
708 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
709 // checked whether the parent for new items is still expanded.
710 KUrl parentUrl
= item
.url().upUrl();
711 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
712 const int parentIndex
= m_items
.value(parentUrl
, -1);
713 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
714 // The parent is not expanded.
719 if (m_filter
.pattern().isEmpty()) {
720 m_pendingItemsToInsert
.append(items
);
722 // The name-filter is active. Hide filtered items
723 // before inserting them into the model and remember
724 // the filtered items in m_filteredItems.
725 KFileItemList filteredItems
;
726 foreach (const KFileItem
& item
, items
) {
727 if (m_filter
.matches(item
)) {
728 filteredItems
.append(item
);
730 m_filteredItems
.insert(item
);
734 m_pendingItemsToInsert
.append(filteredItems
);
737 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer
->isActive()) {
738 // Assure that items get dispatched if no completed() or canceled() signal is
739 // emitted during the maximum update interval.
740 m_maximumUpdateIntervalTimer
->start();
744 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
746 dispatchPendingItemsToInsert();
748 KFileItemList itemsToRemove
= items
;
749 if (m_requestRole
[ExpandedParentsCountRole
] && m_expandedParentsCountRoot
>= 0) {
750 // Assure that removing a parent item also results in removing all children
751 foreach (const KFileItem
& item
, items
) {
752 itemsToRemove
.append(childItems(item
));
756 if (!m_filteredItems
.isEmpty()) {
757 foreach (const KFileItem
& item
, itemsToRemove
) {
758 m_filteredItems
.remove(item
);
762 removeItems(itemsToRemove
);
765 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
767 Q_ASSERT(!items
.isEmpty());
768 #ifdef KFILEITEMMODEL_DEBUG
769 kDebug() << "Refreshing" << items
.count() << "items";
774 // Get the indexes of all items that have been refreshed
776 indexes
.reserve(items
.count());
778 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
779 while (it
.hasNext()) {
780 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
781 const KFileItem
& oldItem
= itemPair
.first
;
782 const KFileItem
& newItem
= itemPair
.second
;
783 const int index
= m_items
.value(oldItem
.url(), -1);
785 m_itemData
[index
]->item
= newItem
;
787 // Keep old values as long as possible if they could not retrieved synchronously yet.
788 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
789 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
));
790 while (it
.hasNext()) {
792 m_itemData
[index
]->values
.insert(it
.key(), it
.value());
795 m_items
.remove(oldItem
.url());
796 m_items
.insert(newItem
.url(), index
);
797 indexes
.append(index
);
801 // If the changed items have been created recently, they might not be in m_items yet.
802 // In that case, the list 'indexes' might be empty.
803 if (indexes
.isEmpty()) {
807 // Extract the item-ranges out of the changed indexes
810 KItemRangeList itemRangeList
;
811 int previousIndex
= indexes
.at(0);
812 int rangeIndex
= previousIndex
;
815 const int maxIndex
= indexes
.count() - 1;
816 for (int i
= 1; i
<= maxIndex
; ++i
) {
817 const int currentIndex
= indexes
.at(i
);
818 if (currentIndex
== previousIndex
+ 1) {
821 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
823 rangeIndex
= currentIndex
;
826 previousIndex
= currentIndex
;
829 if (rangeCount
> 0) {
830 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
833 emit
itemsChanged(itemRangeList
, m_roles
);
838 void KFileItemModel::slotClear()
840 #ifdef KFILEITEMMODEL_DEBUG
841 kDebug() << "Clearing all items";
844 m_filteredItems
.clear();
847 m_maximumUpdateIntervalTimer
->stop();
848 m_resortAllItemsTimer
->stop();
849 m_pendingItemsToInsert
.clear();
851 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
853 const int removedCount
= m_itemData
.count();
854 if (removedCount
> 0) {
855 qDeleteAll(m_itemData
);
858 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
861 m_expandedUrls
.clear();
864 void KFileItemModel::slotClear(const KUrl
& url
)
869 void KFileItemModel::slotNaturalSortingChanged()
871 m_naturalSorting
= KGlobalSettings::naturalSorting();
875 void KFileItemModel::dispatchPendingItemsToInsert()
877 if (!m_pendingItemsToInsert
.isEmpty()) {
878 insertItems(m_pendingItemsToInsert
);
879 m_pendingItemsToInsert
.clear();
883 void KFileItemModel::insertItems(const KFileItemList
& items
)
885 if (items
.isEmpty()) {
889 #ifdef KFILEITEMMODEL_DEBUG
892 kDebug() << "===========================================================";
893 kDebug() << "Inserting" << items
.count() << "items";
898 QList
<ItemData
*> sortedItems
= createItemDataList(items
);
899 sort(sortedItems
.begin(), sortedItems
.end());
901 #ifdef KFILEITEMMODEL_DEBUG
902 kDebug() << "[TIME] Sorting:" << timer
.elapsed();
905 KItemRangeList itemRanges
;
908 int insertedAtIndex
= -1; // Index for the current item-range
909 int insertedCount
= 0; // Count for the current item-range
910 int previouslyInsertedCount
= 0; // Sum of previously inserted items for all ranges
911 while (sourceIndex
< sortedItems
.count()) {
912 // Find target index from m_items to insert the current item
914 const int previousTargetIndex
= targetIndex
;
915 while (targetIndex
< m_itemData
.count()) {
916 if (!lessThan(m_itemData
.at(targetIndex
), sortedItems
.at(sourceIndex
))) {
922 if (targetIndex
- previousTargetIndex
> 0 && insertedAtIndex
>= 0) {
923 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
924 previouslyInsertedCount
+= insertedCount
;
925 insertedAtIndex
= targetIndex
- previouslyInsertedCount
;
929 // Insert item at the position targetIndex by transfering
930 // the ownership of the item-data from sortedItems to m_itemData.
931 // m_items will be inserted after the loop (see comment below)
932 m_itemData
.insert(targetIndex
, sortedItems
.at(sourceIndex
));
935 if (insertedAtIndex
< 0) {
936 insertedAtIndex
= targetIndex
;
937 Q_ASSERT(previouslyInsertedCount
== 0);
943 // The indexes of all m_items must be adjusted, not only the index
945 const int itemDataCount
= m_itemData
.count();
946 for (int i
= 0; i
< itemDataCount
; ++i
) {
947 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
950 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
951 emit
itemsInserted(itemRanges
);
953 #ifdef KFILEITEMMODEL_DEBUG
954 kDebug() << "[TIME] Inserting of" << items
.count() << "items:" << timer
.elapsed();
958 void KFileItemModel::removeItems(const KFileItemList
& items
)
960 if (items
.isEmpty()) {
964 #ifdef KFILEITEMMODEL_DEBUG
965 kDebug() << "Removing " << items
.count() << "items";
970 QList
<ItemData
*> sortedItems
;
971 sortedItems
.reserve(items
.count());
972 foreach (const KFileItem
& item
, items
) {
973 const int index
= m_items
.value(item
.url(), -1);
975 sortedItems
.append(m_itemData
.at(index
));
978 sort(sortedItems
.begin(), sortedItems
.end());
980 QList
<int> indexesToRemove
;
981 indexesToRemove
.reserve(items
.count());
983 // Calculate the item ranges that will get deleted
984 KItemRangeList itemRanges
;
985 int removedAtIndex
= -1;
986 int removedCount
= 0;
988 foreach (const ItemData
* itemData
, sortedItems
) {
989 const KFileItem
& itemToRemove
= itemData
->item
;
991 const int previousTargetIndex
= targetIndex
;
992 while (targetIndex
< m_itemData
.count()) {
993 if (m_itemData
.at(targetIndex
)->item
.url() == itemToRemove
.url()) {
998 if (targetIndex
>= m_itemData
.count()) {
999 kWarning() << "Item that should be deleted has not been found!";
1003 if (targetIndex
- previousTargetIndex
> 0 && removedAtIndex
>= 0) {
1004 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
1005 removedAtIndex
= targetIndex
;
1009 indexesToRemove
.append(targetIndex
);
1010 if (removedAtIndex
< 0) {
1011 removedAtIndex
= targetIndex
;
1018 for (int i
= indexesToRemove
.count() - 1; i
>= 0; --i
) {
1019 const int indexToRemove
= indexesToRemove
.at(i
);
1020 ItemData
* data
= m_itemData
.at(indexToRemove
);
1022 m_items
.remove(data
->item
.url());
1025 m_itemData
.removeAt(indexToRemove
);
1028 // The indexes of all m_items must be adjusted, not only the index
1029 // of the removed items
1030 const int itemDataCount
= m_itemData
.count();
1031 for (int i
= 0; i
< itemDataCount
; ++i
) {
1032 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
1036 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
1039 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
1040 emit
itemsRemoved(itemRanges
);
1043 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const KFileItemList
& items
) const
1045 QList
<ItemData
*> itemDataList
;
1046 itemDataList
.reserve(items
.count());
1048 foreach (const KFileItem
& item
, items
) {
1049 ItemData
* itemData
= new ItemData();
1050 itemData
->item
= item
;
1051 itemData
->values
= retrieveData(item
);
1052 itemData
->parent
= 0;
1054 const bool determineParent
= m_requestRole
[ExpandedParentsCountRole
]
1055 && itemData
->values
["expandedParentsCount"].toInt() > 0;
1056 if (determineParent
) {
1057 KUrl parentUrl
= item
.url().upUrl();
1058 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
1059 const int parentIndex
= m_items
.value(parentUrl
, -1);
1060 if (parentIndex
>= 0) {
1061 itemData
->parent
= m_itemData
.at(parentIndex
);
1063 kWarning() << "Parent item not found for" << item
.url();
1067 itemDataList
.append(itemData
);
1070 return itemDataList
;
1073 void KFileItemModel::removeExpandedItems()
1075 KFileItemList expandedItems
;
1077 const int maxIndex
= m_itemData
.count() - 1;
1078 for (int i
= 0; i
<= maxIndex
; ++i
) {
1079 const ItemData
* itemData
= m_itemData
.at(i
);
1080 if (itemData
->values
.value("expandedParentsCount").toInt() > 0) {
1081 expandedItems
.append(itemData
->item
);
1085 // The m_expandedParentsCountRoot may not get reset before all items with
1086 // a bigger count have been removed.
1087 Q_ASSERT(m_expandedParentsCountRoot
>= 0);
1088 removeItems(expandedItems
);
1090 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
1091 m_expandedUrls
.clear();
1094 void KFileItemModel::resetRoles()
1096 for (int i
= 0; i
< RolesCount
; ++i
) {
1097 m_requestRole
[i
] = false;
1101 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1103 static QHash
<QByteArray
, RoleType
> roles
;
1104 if (roles
.isEmpty()) {
1105 // Insert user visible roles that can be accessed with
1106 // KFileItemModel::roleInformation()
1108 const RoleInfoMap
* map
= rolesInfoMap(count
);
1109 for (int i
= 0; i
< count
; ++i
) {
1110 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1113 // Insert internal roles (take care to synchronize the implementation
1114 // with KFileItemModel::roleForType() in case if a change is done).
1115 roles
.insert("isDir", IsDirRole
);
1116 roles
.insert("isExpanded", IsExpandedRole
);
1117 roles
.insert("isExpandable", IsExpandableRole
);
1118 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1120 Q_ASSERT(roles
.count() == RolesCount
);
1123 return roles
.value(role
, NoRole
);
1126 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1128 static QHash
<RoleType
, QByteArray
> roles
;
1129 if (roles
.isEmpty()) {
1130 // Insert user visible roles that can be accessed with
1131 // KFileItemModel::roleInformation()
1133 const RoleInfoMap
* map
= rolesInfoMap(count
);
1134 for (int i
= 0; i
< count
; ++i
) {
1135 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1138 // Insert internal roles (take care to synchronize the implementation
1139 // with KFileItemModel::typeForRole() in case if a change is done).
1140 roles
.insert(IsDirRole
, "isDir");
1141 roles
.insert(IsExpandedRole
, "isExpanded");
1142 roles
.insert(IsExpandableRole
, "isExpandable");
1143 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1145 Q_ASSERT(roles
.count() == RolesCount
);
1148 return roles
.value(roleType
);
1151 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
) const
1153 // It is important to insert only roles that are fast to retrieve. E.g.
1154 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1155 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1156 QHash
<QByteArray
, QVariant
> data
;
1157 data
.insert("url", item
.url());
1159 const bool isDir
= item
.isDir();
1160 if (m_requestRole
[IsDirRole
]) {
1161 data
.insert("isDir", isDir
);
1164 if (m_requestRole
[NameRole
]) {
1165 data
.insert("name", item
.text());
1168 if (m_requestRole
[SizeRole
]) {
1170 data
.insert("size", QVariant());
1172 data
.insert("size", item
.size());
1176 if (m_requestRole
[DateRole
]) {
1177 // Don't use KFileItem::timeString() as this is too expensive when
1178 // having several thousands of items. Instead the formatting of the
1179 // date-time will be done on-demand by the view when the date will be shown.
1180 const KDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
1181 data
.insert("date", dateTime
.dateTime());
1184 if (m_requestRole
[PermissionsRole
]) {
1185 data
.insert("permissions", item
.permissionsString());
1188 if (m_requestRole
[OwnerRole
]) {
1189 data
.insert("owner", item
.user());
1192 if (m_requestRole
[GroupRole
]) {
1193 data
.insert("group", item
.group());
1196 if (m_requestRole
[DestinationRole
]) {
1197 QString destination
= item
.linkDest();
1198 if (destination
.isEmpty()) {
1199 destination
= i18nc("@item:intable", "No destination");
1201 data
.insert("destination", destination
);
1204 if (m_requestRole
[PathRole
]) {
1206 if (item
.url().protocol() == QLatin1String("trash")) {
1207 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1209 path
= item
.localPath();
1212 const int index
= path
.lastIndexOf(item
.text());
1213 path
= path
.mid(0, index
- 1);
1214 data
.insert("path", path
);
1217 if (m_requestRole
[IsExpandedRole
]) {
1218 data
.insert("isExpanded", false);
1221 if (m_requestRole
[IsExpandableRole
]) {
1222 data
.insert("isExpandable", item
.isDir() && item
.url() == item
.targetUrl());
1225 if (m_requestRole
[ExpandedParentsCountRole
]) {
1226 if (m_expandedParentsCountRoot
== UninitializedExpandedParentsCountRoot
&& m_dirLister
.data()) {
1227 const KUrl rootUrl
= m_dirLister
.data()->url();
1228 const QString protocol
= rootUrl
.protocol();
1229 const bool forceExpandedParentsCountRoot
= (protocol
== QLatin1String("trash") ||
1230 protocol
== QLatin1String("nepomuk") ||
1231 protocol
== QLatin1String("remote") ||
1232 protocol
.contains(QLatin1String("search")));
1233 if (forceExpandedParentsCountRoot
) {
1234 m_expandedParentsCountRoot
= ForceExpandedParentsCountRoot
;
1236 const QString rootDir
= rootUrl
.path(KUrl::AddTrailingSlash
);
1237 m_expandedParentsCountRoot
= rootDir
.count('/');
1241 if (m_expandedParentsCountRoot
== ForceExpandedParentsCountRoot
) {
1242 data
.insert("expandedParentsCount", -1);
1244 const QString dir
= item
.url().directory(KUrl::AppendTrailingSlash
);
1245 const int level
= dir
.count('/') - m_expandedParentsCountRoot
;
1246 data
.insert("expandedParentsCount", level
);
1250 if (item
.isMimeTypeKnown()) {
1251 data
.insert("iconName", item
.iconName());
1253 if (m_requestRole
[TypeRole
]) {
1254 data
.insert("type", item
.mimeComment());
1261 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
) const
1265 if (m_expandedParentsCountRoot
>= 0) {
1266 result
= expandedParentsCountCompare(a
, b
);
1268 // The items have parents with different expansion levels
1269 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1273 if (m_sortFoldersFirst
|| m_sortRole
== SizeRole
) {
1274 const bool isDirA
= a
->item
.isDir();
1275 const bool isDirB
= b
->item
.isDir();
1276 if (isDirA
&& !isDirB
) {
1278 } else if (!isDirA
&& isDirB
) {
1283 result
= sortRoleCompare(a
, b
);
1285 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1288 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
) const
1290 const KFileItem
& itemA
= a
->item
;
1291 const KFileItem
& itemB
= b
->item
;
1295 switch (m_sortRole
) {
1297 // The name role is handled as default fallback after the switch
1301 if (itemA
.isDir()) {
1302 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1303 Q_ASSERT(itemB
.isDir());
1305 const QVariant valueA
= a
->values
.value("size");
1306 const QVariant valueB
= b
->values
.value("size");
1307 if (valueA
.isNull() && valueB
.isNull()) {
1309 } else if (valueA
.isNull()) {
1311 } else if (valueB
.isNull()) {
1314 result
= valueA
.toInt() - valueB
.toInt();
1317 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1318 Q_ASSERT(!itemB
.isDir());
1319 const KIO::filesize_t sizeA
= itemA
.size();
1320 const KIO::filesize_t sizeB
= itemB
.size();
1321 if (sizeA
> sizeB
) {
1323 } else if (sizeA
< sizeB
) {
1333 const KDateTime dateTimeA
= itemA
.time(KFileItem::ModificationTime
);
1334 const KDateTime dateTimeB
= itemB
.time(KFileItem::ModificationTime
);
1335 if (dateTimeA
< dateTimeB
) {
1337 } else if (dateTimeA
> dateTimeB
) {
1344 result
= a
->values
.value("rating").toInt() - b
->values
.value("rating").toInt();
1348 case PermissionsRole
:
1352 case DestinationRole
:
1356 const QByteArray role
= roleForType(m_sortRole
);
1357 result
= QString::compare(a
->values
.value(role
).toString(),
1358 b
->values
.value(role
).toString());
1367 // The current sort role was sufficient to define an order
1371 // Fallback #1: Compare the text of the items
1372 result
= stringCompare(itemA
.text(), itemB
.text());
1377 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1378 result
= stringCompare(itemA
.name(m_caseSensitivity
== Qt::CaseInsensitive
),
1379 itemB
.name(m_caseSensitivity
== Qt::CaseInsensitive
));
1384 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1385 // equal. In this case a comparison of the URL is done which is unique in all cases
1386 // within KDirLister.
1387 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1390 void KFileItemModel::sort(QList
<ItemData
*>::iterator begin
,
1391 QList
<ItemData
*>::iterator end
)
1393 // The implementation is based on qStableSortHelper() from qalgorithms.h
1394 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1395 // In opposite to qStableSort() it allows to use a member-function for the comparison of elements.
1397 const int span
= end
- begin
;
1402 const QList
<ItemData
*>::iterator middle
= begin
+ span
/ 2;
1403 sort(begin
, middle
);
1405 merge(begin
, middle
, end
);
1408 void KFileItemModel::merge(QList
<ItemData
*>::iterator begin
,
1409 QList
<ItemData
*>::iterator pivot
,
1410 QList
<ItemData
*>::iterator end
)
1412 // The implementation is based on qMerge() from qalgorithms.h
1413 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1415 const int len1
= pivot
- begin
;
1416 const int len2
= end
- pivot
;
1418 if (len1
== 0 || len2
== 0) {
1422 if (len1
+ len2
== 2) {
1423 if (lessThan(*(begin
+ 1), *(begin
))) {
1424 qSwap(*begin
, *(begin
+ 1));
1429 QList
<ItemData
*>::iterator firstCut
;
1430 QList
<ItemData
*>::iterator secondCut
;
1433 const int len1Half
= len1
/ 2;
1434 firstCut
= begin
+ len1Half
;
1435 secondCut
= lowerBound(pivot
, end
, *firstCut
);
1436 len2Half
= secondCut
- pivot
;
1438 len2Half
= len2
/ 2;
1439 secondCut
= pivot
+ len2Half
;
1440 firstCut
= upperBound(begin
, pivot
, *secondCut
);
1443 reverse(firstCut
, pivot
);
1444 reverse(pivot
, secondCut
);
1445 reverse(firstCut
, secondCut
);
1447 const QList
<ItemData
*>::iterator newPivot
= firstCut
+ len2Half
;
1448 merge(begin
, firstCut
, newPivot
);
1449 merge(newPivot
, secondCut
, end
);
1452 QList
<KFileItemModel::ItemData
*>::iterator
KFileItemModel::lowerBound(QList
<ItemData
*>::iterator begin
,
1453 QList
<ItemData
*>::iterator end
,
1454 const ItemData
* value
)
1456 // The implementation is based on qLowerBound() from qalgorithms.h
1457 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1459 QList
<ItemData
*>::iterator middle
;
1460 int n
= int(end
- begin
);
1465 middle
= begin
+ half
;
1466 if (lessThan(*middle
, value
)) {
1476 QList
<KFileItemModel::ItemData
*>::iterator
KFileItemModel::upperBound(QList
<ItemData
*>::iterator begin
,
1477 QList
<ItemData
*>::iterator end
,
1478 const ItemData
* value
)
1480 // The implementation is based on qUpperBound() from qalgorithms.h
1481 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1483 QList
<ItemData
*>::iterator middle
;
1484 int n
= end
- begin
;
1489 middle
= begin
+ half
;
1490 if (lessThan(value
, *middle
)) {
1500 void KFileItemModel::reverse(QList
<ItemData
*>::iterator begin
,
1501 QList
<ItemData
*>::iterator end
)
1503 // The implementation is based on qReverse() from qalgorithms.h
1504 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1507 while (begin
< end
) {
1508 qSwap(*begin
++, *end
--);
1512 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
) const
1514 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1515 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1516 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1517 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1519 if (m_caseSensitivity
== Qt::CaseInsensitive
) {
1520 const int result
= m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseInsensitive
)
1521 : QString::compare(a
, b
, Qt::CaseInsensitive
);
1523 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1524 // comparison, still a deterministic sort order is required. A case sensitive
1525 // comparison is done as fallback.
1530 return m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseSensitive
)
1531 : QString::compare(a
, b
, Qt::CaseSensitive
);
1534 int KFileItemModel::expandedParentsCountCompare(const ItemData
* a
, const ItemData
* b
) const
1536 const KUrl urlA
= a
->item
.url();
1537 const KUrl urlB
= b
->item
.url();
1538 if (urlA
.directory() == urlB
.directory()) {
1539 // Both items have the same directory as parent
1543 // Check whether one item is the parent of the other item
1544 if (urlA
.isParentOf(urlB
)) {
1545 return (sortOrder() == Qt::AscendingOrder
) ? -1 : +1;
1546 } else if (urlB
.isParentOf(urlA
)) {
1547 return (sortOrder() == Qt::AscendingOrder
) ? +1 : -1;
1550 // Determine the maximum common path of both items and
1551 // remember the index in 'index'
1552 const QString pathA
= urlA
.path();
1553 const QString pathB
= urlB
.path();
1555 const int maxIndex
= qMin(pathA
.length(), pathB
.length()) - 1;
1557 while (index
<= maxIndex
&& pathA
.at(index
) == pathB
.at(index
)) {
1560 if (index
> maxIndex
) {
1563 while ((pathA
.at(index
) != QLatin1Char('/') || pathB
.at(index
) != QLatin1Char('/')) && index
> 0) {
1567 // Determine the first sub-path after the common path and
1568 // check whether it represents a directory or already a file
1570 const QString subPathA
= subPath(a
->item
, pathA
, index
, &isDirA
);
1572 const QString subPathB
= subPath(b
->item
, pathB
, index
, &isDirB
);
1574 if (m_sortFoldersFirst
|| m_sortRole
== SizeRole
) {
1575 if (isDirA
&& !isDirB
) {
1576 return (sortOrder() == Qt::AscendingOrder
) ? -1 : +1;
1577 } else if (!isDirA
&& isDirB
) {
1578 return (sortOrder() == Qt::AscendingOrder
) ? +1 : -1;
1582 // Compare the items of the parents that represent the first
1583 // different path after the common path.
1584 const QString parentPathA
= pathA
.left(index
) + subPathA
;
1585 const QString parentPathB
= pathB
.left(index
) + subPathB
;
1587 const ItemData
* parentA
= a
;
1588 while (parentA
&& parentA
->item
.url().path() != parentPathA
) {
1589 parentA
= parentA
->parent
;
1592 const ItemData
* parentB
= b
;
1593 while (parentB
&& parentB
->item
.url().path() != parentPathB
) {
1594 parentB
= parentB
->parent
;
1597 if (parentA
&& parentB
) {
1598 return sortRoleCompare(parentA
, parentB
);
1601 kWarning() << "Child items without parent detected:" << a
->item
.url() << b
->item
.url();
1602 return QString::compare(urlA
.url(), urlB
.url(), Qt::CaseSensitive
);
1605 QString
KFileItemModel::subPath(const KFileItem
& item
,
1606 const QString
& itemPath
,
1611 const int pathIndex
= itemPath
.indexOf('/', start
+ 1);
1612 *isDir
= (pathIndex
> 0) || item
.isDir();
1613 return itemPath
.mid(start
, pathIndex
- start
);
1616 bool KFileItemModel::useMaximumUpdateInterval() const
1618 const KDirLister
* dirLister
= m_dirLister
.data();
1619 return dirLister
&& !dirLister
->url().isLocalFile();
1622 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1624 Q_ASSERT(!m_itemData
.isEmpty());
1626 const int maxIndex
= count() - 1;
1627 QList
<QPair
<int, QVariant
> > groups
;
1631 bool isLetter
= false;
1632 for (int i
= 0; i
<= maxIndex
; ++i
) {
1633 if (isChildItem(i
)) {
1637 const QString name
= m_itemData
.at(i
)->values
.value("name").toString();
1639 // Use the first character of the name as group indication
1640 QChar newFirstChar
= name
.at(0).toUpper();
1641 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1642 newFirstChar
= name
.at(1).toUpper();
1645 if (firstChar
!= newFirstChar
) {
1646 QString newGroupValue
;
1647 if (newFirstChar
>= QLatin1Char('A') && newFirstChar
<= QLatin1Char('Z')) {
1648 // Apply group 'A' - 'Z'
1649 newGroupValue
= newFirstChar
;
1651 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
1652 // Apply group '0 - 9' for any name that starts with a digit
1653 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
1657 // If the current group is 'A' - 'Z' check whether a locale character
1658 // fits into the existing group.
1659 // TODO: This does not work in the case if e.g. the group 'O' starts with
1660 // an umlaut 'O' -> provide unit-test to document this known issue
1661 const QChar
prevChar(firstChar
.unicode() - ushort(1));
1662 const QChar
nextChar(firstChar
.unicode() + ushort(1));
1663 const QString
currChar(newFirstChar
);
1664 const bool partOfCurrentGroup
= currChar
.localeAwareCompare(prevChar
) > 0 &&
1665 currChar
.localeAwareCompare(nextChar
) < 0;
1666 if (partOfCurrentGroup
) {
1670 newGroupValue
= i18nc("@title:group", "Others");
1674 if (newGroupValue
!= groupValue
) {
1675 groupValue
= newGroupValue
;
1676 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1679 firstChar
= newFirstChar
;
1685 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
1687 Q_ASSERT(!m_itemData
.isEmpty());
1689 const int maxIndex
= count() - 1;
1690 QList
<QPair
<int, QVariant
> > groups
;
1693 for (int i
= 0; i
<= maxIndex
; ++i
) {
1694 if (isChildItem(i
)) {
1698 const KFileItem
& item
= m_itemData
.at(i
)->item
;
1699 const KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
1700 QString newGroupValue
;
1701 if (!item
.isNull() && item
.isDir()) {
1702 newGroupValue
= i18nc("@title:group Size", "Folders");
1703 } else if (fileSize
< 5 * 1024 * 1024) {
1704 newGroupValue
= i18nc("@title:group Size", "Small");
1705 } else if (fileSize
< 10 * 1024 * 1024) {
1706 newGroupValue
= i18nc("@title:group Size", "Medium");
1708 newGroupValue
= i18nc("@title:group Size", "Big");
1711 if (newGroupValue
!= groupValue
) {
1712 groupValue
= newGroupValue
;
1713 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1720 QList
<QPair
<int, QVariant
> > KFileItemModel::dateRoleGroups() const
1722 Q_ASSERT(!m_itemData
.isEmpty());
1724 const int maxIndex
= count() - 1;
1725 QList
<QPair
<int, QVariant
> > groups
;
1727 const QDate currentDate
= KDateTime::currentLocalDateTime().date();
1729 int yearForCurrentWeek
= 0;
1730 int currentWeek
= currentDate
.weekNumber(&yearForCurrentWeek
);
1731 if (yearForCurrentWeek
== currentDate
.year() + 1) {
1735 QDate previousModifiedDate
;
1737 for (int i
= 0; i
<= maxIndex
; ++i
) {
1738 if (isChildItem(i
)) {
1742 const KDateTime modifiedTime
= m_itemData
.at(i
)->item
.time(KFileItem::ModificationTime
);
1743 const QDate modifiedDate
= modifiedTime
.date();
1744 if (modifiedDate
== previousModifiedDate
) {
1745 // The current item is in the same group as the previous item
1748 previousModifiedDate
= modifiedDate
;
1750 const int daysDistance
= modifiedDate
.daysTo(currentDate
);
1752 int yearForModifiedWeek
= 0;
1753 int modifiedWeek
= modifiedDate
.weekNumber(&yearForModifiedWeek
);
1754 if (yearForModifiedWeek
== modifiedDate
.year() + 1) {
1758 QString newGroupValue
;
1759 if (currentDate
.year() == modifiedDate
.year() && currentDate
.month() == modifiedDate
.month()) {
1760 if (modifiedWeek
> currentWeek
) {
1761 // Usecase: modified date = 2010-01-01, current date = 2010-01-22
1762 // modified week = 53, current week = 3
1765 switch (currentWeek
- modifiedWeek
) {
1767 switch (daysDistance
) {
1768 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
1769 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
1770 default: newGroupValue
= modifiedTime
.toString(i18nc("@title:group The week day name: %A", "%A"));
1774 newGroupValue
= i18nc("@title:group Date", "Last Week");
1777 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
1780 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
1784 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
1790 const QDate lastMonthDate
= currentDate
.addMonths(-1);
1791 if (lastMonthDate
.year() == modifiedDate
.year() && lastMonthDate
.month() == modifiedDate
.month()) {
1792 if (daysDistance
== 1) {
1793 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Yesterday (%B, %Y)"));
1794 } else if (daysDistance
<= 7) {
1795 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)"));
1796 } else if (daysDistance
<= 7 * 2) {
1797 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)"));
1798 } else if (daysDistance
<= 7 * 3) {
1799 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)"));
1800 } else if (daysDistance
<= 7 * 4) {
1801 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)"));
1803 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"));
1806 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"));
1810 if (newGroupValue
!= groupValue
) {
1811 groupValue
= newGroupValue
;
1812 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1819 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
1821 Q_ASSERT(!m_itemData
.isEmpty());
1823 const int maxIndex
= count() - 1;
1824 QList
<QPair
<int, QVariant
> > groups
;
1826 QString permissionsString
;
1828 for (int i
= 0; i
<= maxIndex
; ++i
) {
1829 if (isChildItem(i
)) {
1833 const ItemData
* itemData
= m_itemData
.at(i
);
1834 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
1835 if (newPermissionsString
== permissionsString
) {
1838 permissionsString
= newPermissionsString
;
1840 const QFileInfo
info(itemData
->item
.url().pathOrUrl());
1844 if (info
.permission(QFile::ReadUser
)) {
1845 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1847 if (info
.permission(QFile::WriteUser
)) {
1848 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1850 if (info
.permission(QFile::ExeUser
)) {
1851 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1853 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
1857 if (info
.permission(QFile::ReadGroup
)) {
1858 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1860 if (info
.permission(QFile::WriteGroup
)) {
1861 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1863 if (info
.permission(QFile::ExeGroup
)) {
1864 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1866 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
1868 // Set others string
1870 if (info
.permission(QFile::ReadOther
)) {
1871 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1873 if (info
.permission(QFile::WriteOther
)) {
1874 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1876 if (info
.permission(QFile::ExeOther
)) {
1877 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1879 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
1881 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
1882 if (newGroupValue
!= groupValue
) {
1883 groupValue
= newGroupValue
;
1884 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1891 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
1893 Q_ASSERT(!m_itemData
.isEmpty());
1895 const int maxIndex
= count() - 1;
1896 QList
<QPair
<int, QVariant
> > groups
;
1898 int groupValue
= -1;
1899 for (int i
= 0; i
<= maxIndex
; ++i
) {
1900 if (isChildItem(i
)) {
1903 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
1904 if (newGroupValue
!= groupValue
) {
1905 groupValue
= newGroupValue
;
1906 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1913 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
1915 Q_ASSERT(!m_itemData
.isEmpty());
1917 const int maxIndex
= count() - 1;
1918 QList
<QPair
<int, QVariant
> > groups
;
1920 bool isFirstGroupValue
= true;
1922 for (int i
= 0; i
<= maxIndex
; ++i
) {
1923 if (isChildItem(i
)) {
1926 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
1927 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
1928 groupValue
= newGroupValue
;
1929 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1930 isFirstGroupValue
= false;
1937 KFileItemList
KFileItemModel::childItems(const KFileItem
& item
) const
1939 KFileItemList items
;
1941 int index
= m_items
.value(item
.url(), -1);
1943 const int parentLevel
= m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt();
1945 while (index
< m_itemData
.count() && m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt() > parentLevel
) {
1946 items
.append(m_itemData
.at(index
)->item
);
1954 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
1956 static const RoleInfoMap rolesInfoMap
[] = {
1957 // role roleType role translation group translation
1958 { 0, NoRole
, 0, 0, 0, 0 },
1959 { "name", NameRole
, I18N_NOOP2_NOSTRIP("@label", "Name"), 0, 0 },
1960 { "size", SizeRole
, I18N_NOOP2_NOSTRIP("@label", "Size"), 0, 0 },
1961 { "date", DateRole
, I18N_NOOP2_NOSTRIP("@label", "Date"), 0, 0 },
1962 { "type", TypeRole
, I18N_NOOP2_NOSTRIP("@label", "Type"), 0, 0 },
1963 { "rating", RatingRole
, I18N_NOOP2_NOSTRIP("@label", "Rating"), 0, 0 },
1964 { "tags", TagsRole
, I18N_NOOP2_NOSTRIP("@label", "Tags"), 0, 0 },
1965 { "comment", CommentRole
, I18N_NOOP2_NOSTRIP("@label", "Comment"), 0, 0 },
1966 { "wordCount", WordCountRole
, I18N_NOOP2_NOSTRIP("@label", "Word Count"), I18N_NOOP2_NOSTRIP("@label", "Document") },
1967 { "lineCount", LineCountRole
, I18N_NOOP2_NOSTRIP("@label", "Line Count"), I18N_NOOP2_NOSTRIP("@label", "Document") },
1968 { "imageSize", ImageSizeRole
, I18N_NOOP2_NOSTRIP("@label", "Image Size"), I18N_NOOP2_NOSTRIP("@label", "Image") },
1969 { "orientation", OrientationRole
, I18N_NOOP2_NOSTRIP("@label", "Orientation"), I18N_NOOP2_NOSTRIP("@label", "Image") },
1970 { "artist", ArtistRole
, I18N_NOOP2_NOSTRIP("@label", "Artist"), I18N_NOOP2_NOSTRIP("@label", "Music") },
1971 { "album", AlbumRole
, I18N_NOOP2_NOSTRIP("@label", "Album"), I18N_NOOP2_NOSTRIP("@label", "Music") },
1972 { "duration", DurationRole
, I18N_NOOP2_NOSTRIP("@label", "Duration"), I18N_NOOP2_NOSTRIP("@label", "Music") },
1973 { "track", TrackRole
, I18N_NOOP2_NOSTRIP("@label", "Track"), I18N_NOOP2_NOSTRIP("@label", "Music") },
1974 { "path", PathRole
, I18N_NOOP2_NOSTRIP("@label", "Path"), I18N_NOOP2_NOSTRIP("@label", "Other") },
1975 { "destination", DestinationRole
, I18N_NOOP2_NOSTRIP("@label", "Link Destination"), I18N_NOOP2_NOSTRIP("@label", "Other") },
1976 { "copiedFrom", CopiedFromRole
, I18N_NOOP2_NOSTRIP("@label", "Copied From"), I18N_NOOP2_NOSTRIP("@label", "Other") },
1977 { "permissions", PermissionsRole
, I18N_NOOP2_NOSTRIP("@label", "Permissions"), I18N_NOOP2_NOSTRIP("@label", "Other") },
1978 { "owner", OwnerRole
, I18N_NOOP2_NOSTRIP("@label", "Owner"), I18N_NOOP2_NOSTRIP("@label", "Other") },
1979 { "group", GroupRole
, I18N_NOOP2_NOSTRIP("@label", "Group"), I18N_NOOP2_NOSTRIP("@label", "Other") },
1982 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
1983 return rolesInfoMap
;
1986 #include "kfileitemmodel.moc"