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 "kfileitemmodelsortalgorithm_p.h"
25 #include <KGlobalSettings>
27 #include <KStringHandler>
33 // #define KFILEITEMMODEL_DEBUG
35 KFileItemModel::KFileItemModel(KDirLister
* dirLister
, QObject
* parent
) :
36 KItemModelBase("name", parent
),
37 m_dirLister(dirLister
),
38 m_naturalSorting(KGlobalSettings::naturalSorting()),
39 m_sortFoldersFirst(true),
42 m_caseSensitivity(Qt::CaseInsensitive
),
48 m_maximumUpdateIntervalTimer(0),
49 m_resortAllItemsTimer(0),
50 m_pendingItemsToInsert(),
52 m_expandedParentsCountRoot(UninitializedExpandedParentsCountRoot
),
56 // Apply default roles that should be determined
58 m_requestRole
[NameRole
] = true;
59 m_requestRole
[IsDirRole
] = true;
60 m_roles
.insert("name");
61 m_roles
.insert("isDir");
65 connect(dirLister
, SIGNAL(canceled()), this, SLOT(slotCanceled()));
66 connect(dirLister
, SIGNAL(completed(KUrl
)), this, SLOT(slotCompleted()));
67 connect(dirLister
, SIGNAL(newItems(KFileItemList
)), this, SLOT(slotNewItems(KFileItemList
)));
68 connect(dirLister
, SIGNAL(itemsDeleted(KFileItemList
)), this, SLOT(slotItemsDeleted(KFileItemList
)));
69 connect(dirLister
, SIGNAL(refreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)), this, SLOT(slotRefreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)));
70 connect(dirLister
, SIGNAL(clear()), this, SLOT(slotClear()));
71 connect(dirLister
, SIGNAL(clear(KUrl
)), this, SLOT(slotClear(KUrl
)));
73 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
74 // before the completed() or canceled() signal has been emitted.
75 m_maximumUpdateIntervalTimer
= new QTimer(this);
76 m_maximumUpdateIntervalTimer
->setInterval(2000);
77 m_maximumUpdateIntervalTimer
->setSingleShot(true);
78 connect(m_maximumUpdateIntervalTimer
, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
80 // When changing the value of an item which represents the sort-role a resorting must be
81 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
82 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
83 // resorting is postponed until the timer has been exceeded.
84 m_resortAllItemsTimer
= new QTimer(this);
85 m_resortAllItemsTimer
->setInterval(500);
86 m_resortAllItemsTimer
->setSingleShot(true);
87 connect(m_resortAllItemsTimer
, SIGNAL(timeout()), this, SLOT(resortAllItems()));
89 connect(KGlobalSettings::self(), SIGNAL(naturalSortingChanged()), this, SLOT(slotNaturalSortingChanged()));
92 KFileItemModel::~KFileItemModel()
94 qDeleteAll(m_itemData
);
98 int KFileItemModel::count() const
100 return m_itemData
.count();
103 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
105 if (index
>= 0 && index
< count()) {
106 return m_itemData
.at(index
)->values
;
108 return QHash
<QByteArray
, QVariant
>();
111 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
113 if (index
< 0 || index
>= count()) {
117 QHash
<QByteArray
, QVariant
> currentValues
= m_itemData
.at(index
)->values
;
119 // Determine which roles have been changed
120 QSet
<QByteArray
> changedRoles
;
121 QHashIterator
<QByteArray
, QVariant
> it(values
);
122 while (it
.hasNext()) {
124 const QByteArray role
= it
.key();
125 const QVariant value
= it
.value();
127 if (currentValues
[role
] != value
) {
128 currentValues
[role
] = value
;
129 changedRoles
.insert(role
);
133 if (changedRoles
.isEmpty()) {
137 m_itemData
[index
]->values
= currentValues
;
138 emit
itemsChanged(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
140 if (changedRoles
.contains(sortRole())) {
141 m_resortAllItemsTimer
->start();
147 void KFileItemModel::setSortFoldersFirst(bool foldersFirst
)
149 if (foldersFirst
!= m_sortFoldersFirst
) {
150 m_sortFoldersFirst
= foldersFirst
;
155 bool KFileItemModel::sortFoldersFirst() const
157 return m_sortFoldersFirst
;
160 void KFileItemModel::setShowHiddenFiles(bool show
)
162 KDirLister
* dirLister
= m_dirLister
.data();
164 dirLister
->setShowingDotFiles(show
);
165 dirLister
->emitChanges();
172 bool KFileItemModel::showHiddenFiles() const
174 const KDirLister
* dirLister
= m_dirLister
.data();
175 return dirLister
? dirLister
->showingDotFiles() : false;
178 void KFileItemModel::setShowFoldersOnly(bool enabled
)
180 KDirLister
* dirLister
= m_dirLister
.data();
182 dirLister
->setDirOnlyMode(enabled
);
186 bool KFileItemModel::showFoldersOnly() const
188 KDirLister
* dirLister
= m_dirLister
.data();
189 return dirLister
? dirLister
->dirOnlyMode() : false;
192 QMimeData
* KFileItemModel::createMimeData(const QSet
<int>& indexes
) const
194 QMimeData
* data
= new QMimeData();
196 // The following code has been taken from KDirModel::mimeData()
197 // (kdelibs/kio/kio/kdirmodel.cpp)
198 // Copyright (C) 2006 David Faure <faure@kde.org>
200 KUrl::List mostLocalUrls
;
201 bool canUseMostLocalUrls
= true;
203 QSetIterator
<int> it(indexes
);
204 while (it
.hasNext()) {
205 const int index
= it
.next();
206 const KFileItem item
= fileItem(index
);
207 if (!item
.isNull()) {
211 mostLocalUrls
<< item
.mostLocalUrl(isLocal
);
213 canUseMostLocalUrls
= false;
218 const bool different
= canUseMostLocalUrls
&& mostLocalUrls
!= urls
;
219 urls
= KDirModel::simplifiedUrlList(urls
); // TODO: Check if we still need KDirModel for this in KDE 5.0
221 mostLocalUrls
= KDirModel::simplifiedUrlList(mostLocalUrls
);
222 urls
.populateMimeData(mostLocalUrls
, data
);
224 urls
.populateMimeData(data
);
230 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
232 startFromIndex
= qMax(0, startFromIndex
);
233 for (int i
= startFromIndex
; i
< count(); ++i
) {
234 if (data(i
)["name"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
238 for (int i
= 0; i
< startFromIndex
; ++i
) {
239 if (data(i
)["name"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
246 bool KFileItemModel::supportsDropping(int index
) const
248 const KFileItem item
= fileItem(index
);
249 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
252 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
254 static QHash
<QByteArray
, QString
> description
;
255 if (description
.isEmpty()) {
257 const RoleInfoMap
* map
= rolesInfoMap(count
);
258 for (int i
= 0; i
< count
; ++i
) {
259 description
.insert(map
[i
].role
, map
[i
].roleTranslation
);
263 return description
.value(role
);
266 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
268 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
269 #ifdef KFILEITEMMODEL_DEBUG
273 switch (typeForRole(sortRole())) {
274 case NameRole
: m_groups
= nameRoleGroups(); break;
275 case SizeRole
: m_groups
= sizeRoleGroups(); break;
276 case DateRole
: m_groups
= dateRoleGroups(); break;
277 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
278 case RatingRole
: m_groups
= ratingRoleGroups(); break;
279 default: m_groups
= genericStringRoleGroups(sortRole()); break;
282 #ifdef KFILEITEMMODEL_DEBUG
283 kDebug() << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
290 KFileItem
KFileItemModel::fileItem(int index
) const
292 if (index
>= 0 && index
< count()) {
293 return m_itemData
.at(index
)->item
;
299 KFileItem
KFileItemModel::fileItem(const KUrl
& url
) const
301 const int index
= m_items
.value(url
, -1);
303 return m_itemData
.at(index
)->item
;
308 int KFileItemModel::index(const KFileItem
& item
) const
314 return m_items
.value(item
.url(), -1);
317 int KFileItemModel::index(const KUrl
& url
) const
319 KUrl urlToFind
= url
;
320 urlToFind
.adjustPath(KUrl::RemoveTrailingSlash
);
321 return m_items
.value(urlToFind
, -1);
324 KFileItem
KFileItemModel::rootItem() const
326 const KDirLister
* dirLister
= m_dirLister
.data();
328 return dirLister
->rootItem();
333 void KFileItemModel::clear()
338 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
340 if (m_roles
== roles
) {
346 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
347 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
348 if (supportedExpanding
&& !willSupportExpanding
) {
349 // No expanding is supported anymore. Take care to delete all items that have an expansion level
350 // that is not 0 (and hence are part of an expanded item).
351 removeExpandedItems();
358 QSetIterator
<QByteArray
> it(roles
);
359 while (it
.hasNext()) {
360 const QByteArray
& role
= it
.next();
361 m_requestRole
[typeForRole(role
)] = true;
365 // Update m_data with the changed requested roles
366 const int maxIndex
= count() - 1;
367 for (int i
= 0; i
<= maxIndex
; ++i
) {
368 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
);
371 kWarning() << "TODO: Emitting itemsChanged() with no information what has changed!";
372 emit
itemsChanged(KItemRangeList() << KItemRange(0, count()), QSet
<QByteArray
>());
376 QSet
<QByteArray
> KFileItemModel::roles() const
381 bool KFileItemModel::setExpanded(int index
, bool expanded
)
383 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
387 QHash
<QByteArray
, QVariant
> values
;
388 values
.insert("isExpanded", expanded
);
389 if (!setData(index
, values
)) {
393 KDirLister
* dirLister
= m_dirLister
.data();
394 const KUrl url
= m_itemData
.at(index
)->item
.url();
396 m_expandedUrls
.insert(url
);
399 dirLister
->openUrl(url
, KDirLister::Keep
);
403 m_expandedUrls
.remove(url
);
406 dirLister
->stop(url
);
409 KFileItemList itemsToRemove
;
410 const int expandedParentsCount
= data(index
)["expandedParentsCount"].toInt();
412 while (index
< count() && data(index
)["expandedParentsCount"].toInt() > expandedParentsCount
) {
413 itemsToRemove
.append(m_itemData
.at(index
)->item
);
416 removeItems(itemsToRemove
);
423 bool KFileItemModel::isExpanded(int index
) const
425 if (index
>= 0 && index
< count()) {
426 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
431 bool KFileItemModel::isExpandable(int index
) const
433 if (index
>= 0 && index
< count()) {
434 return m_itemData
.at(index
)->values
.value("isExpandable").toBool();
439 int KFileItemModel::expandedParentsCount(int index
) const
441 if (index
>= 0 && index
< count()) {
442 const int parentsCount
= m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt();
443 if (parentsCount
> 0) {
450 QSet
<KUrl
> KFileItemModel::expandedUrls() const
452 return m_expandedUrls
;
455 void KFileItemModel::restoreExpandedUrls(const QSet
<KUrl
>& urls
)
457 m_urlsToExpand
= urls
;
460 void KFileItemModel::expandParentItems(const KUrl
& url
)
462 const KDirLister
* dirLister
= m_dirLister
.data();
467 const int pos
= dirLister
->url().path().length();
469 // Assure that each sub-path of the URL that should be
470 // expanded is added to m_urlsToExpand. KDirLister
471 // does not care whether the parent-URL has already been
473 KUrl urlToExpand
= dirLister
->url();
474 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator());
475 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
476 urlToExpand
.addPath(subDirs
.at(i
));
477 m_urlsToExpand
.insert(urlToExpand
);
480 // KDirLister::open() must called at least once to trigger an initial
481 // loading. The pending URLs that must be restored are handled
482 // in slotCompleted().
483 QSetIterator
<KUrl
> it2(m_urlsToExpand
);
484 while (it2
.hasNext()) {
485 const int idx
= index(it2
.next());
486 if (idx
>= 0 && !isExpanded(idx
)) {
487 setExpanded(idx
, true);
493 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
495 if (m_filter
.pattern() != nameFilter
) {
496 dispatchPendingItemsToInsert();
498 m_filter
.setPattern(nameFilter
);
500 // Check which shown items from m_itemData must get
501 // hidden and hence moved to m_filteredItems.
502 KFileItemList newFilteredItems
;
504 foreach (ItemData
* itemData
, m_itemData
) {
505 if (!m_filter
.matches(itemData
->item
)) {
506 // Only filter non-expanded items as child items may never
507 // exist without a parent item
508 if (!itemData
->values
.value("isExpanded").toBool()) {
509 newFilteredItems
.append(itemData
->item
);
510 m_filteredItems
.insert(itemData
->item
);
515 removeItems(newFilteredItems
);
517 // Check which hidden items from m_filteredItems should
518 // get visible again and hence removed from m_filteredItems.
519 KFileItemList newVisibleItems
;
521 QMutableSetIterator
<KFileItem
> it(m_filteredItems
);
522 while (it
.hasNext()) {
523 const KFileItem item
= it
.next();
524 if (m_filter
.matches(item
)) {
525 newVisibleItems
.append(item
);
526 m_filteredItems
.remove(item
);
530 insertItems(newVisibleItems
);
534 QString
KFileItemModel::nameFilter() const
536 return m_filter
.pattern();
539 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
541 static QList
<RoleInfo
> rolesInfo
;
542 if (rolesInfo
.isEmpty()) {
544 const RoleInfoMap
* map
= rolesInfoMap(count
);
545 for (int i
= 0; i
< count
; ++i
) {
546 if (map
[i
].roleType
!= NoRole
) {
548 info
.role
= map
[i
].role
;
549 info
.translation
= map
[i
].roleTranslation
;
550 info
.group
= map
[i
].groupTranslation
;
551 info
.requiresNepomuk
= map
[i
].requiresNepomuk
;
552 info
.requiresIndexer
= map
[i
].requiresIndexer
;
553 rolesInfo
.append(info
);
561 void KFileItemModel::onGroupedSortingChanged(bool current
)
567 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
570 m_sortRole
= typeForRole(current
);
572 #ifdef KFILEITEMMODEL_DEBUG
573 if (!m_requestRole
[m_sortRole
]) {
574 kWarning() << "The sort-role has been changed to a role that has not been received yet";
581 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
588 void KFileItemModel::resortAllItems()
590 m_resortAllItemsTimer
->stop();
592 const int itemCount
= count();
593 if (itemCount
<= 0) {
597 #ifdef KFILEITEMMODEL_DEBUG
600 kDebug() << "===========================================================";
601 kDebug() << "Resorting" << itemCount
<< "items";
604 // Remember the order of the current URLs so
605 // that it can be determined which indexes have
606 // been moved because of the resorting.
608 oldUrls
.reserve(itemCount
);
609 foreach (const ItemData
* itemData
, m_itemData
) {
610 oldUrls
.append(itemData
->item
.url());
617 KFileItemModelSortAlgorithm::sort(this, m_itemData
.begin(), m_itemData
.end());
618 for (int i
= 0; i
< itemCount
; ++i
) {
619 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
622 // Determine the indexes that have been moved
623 QList
<int> movedToIndexes
;
624 movedToIndexes
.reserve(itemCount
);
625 for (int i
= 0; i
< itemCount
; i
++) {
626 const int newIndex
= m_items
.value(oldUrls
.at(i
).url());
627 movedToIndexes
.append(newIndex
);
630 // Don't check whether items have really been moved and always emit a
631 // itemsMoved() signal after resorting: In case of grouped items
632 // the groups might change even if the items themselves don't change their
633 // position. Let the receiver of the signal decide whether a check for moved
634 // items makes sense.
635 emit
itemsMoved(KItemRange(0, itemCount
), movedToIndexes
);
637 #ifdef KFILEITEMMODEL_DEBUG
638 kDebug() << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
642 void KFileItemModel::slotCompleted()
644 dispatchPendingItemsToInsert();
646 if (!m_urlsToExpand
.isEmpty()) {
647 // Try to find a URL that can be expanded.
648 // Note that the parent folder must be expanded before any of its subfolders become visible.
649 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
650 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
651 foreach(const KUrl
& url
, m_urlsToExpand
) {
652 const int index
= m_items
.value(url
, -1);
654 m_urlsToExpand
.remove(url
);
655 if (setExpanded(index
, true)) {
656 // The dir lister has been triggered. This slot will be called
657 // again after the directory has been expanded.
663 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
664 // if these URLs have been deleted in the meantime.
665 m_urlsToExpand
.clear();
668 emit
loadingCompleted();
671 void KFileItemModel::slotCanceled()
673 m_maximumUpdateIntervalTimer
->stop();
674 dispatchPendingItemsToInsert();
677 void KFileItemModel::slotNewItems(const KFileItemList
& items
)
679 Q_ASSERT(!items
.isEmpty());
681 if (m_requestRole
[ExpandedParentsCountRole
] && m_expandedParentsCountRoot
>= 0) {
682 // To be able to compare whether the new items may be inserted as children
683 // of a parent item the pending items must be added to the model first.
684 dispatchPendingItemsToInsert();
686 KFileItem item
= items
.first();
688 // If the expanding of items is enabled, the call
689 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
690 // might result in emitting the same items twice due to the Keep-parameter.
691 // This case happens if an item gets expanded, collapsed and expanded again
692 // before the items could be loaded for the first expansion.
693 const int index
= m_items
.value(item
.url(), -1);
695 // The items are already part of the model.
699 // KDirLister keeps the children of items that got expanded once even if
700 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
701 // checked whether the parent for new items is still expanded.
702 KUrl parentUrl
= item
.url().upUrl();
703 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
704 const int parentIndex
= m_items
.value(parentUrl
, -1);
705 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
706 // The parent is not expanded.
711 if (m_filter
.pattern().isEmpty()) {
712 m_pendingItemsToInsert
.append(items
);
714 // The name-filter is active. Hide filtered items
715 // before inserting them into the model and remember
716 // the filtered items in m_filteredItems.
717 KFileItemList filteredItems
;
718 foreach (const KFileItem
& item
, items
) {
719 if (m_filter
.matches(item
)) {
720 filteredItems
.append(item
);
722 m_filteredItems
.insert(item
);
726 m_pendingItemsToInsert
.append(filteredItems
);
729 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer
->isActive()) {
730 // Assure that items get dispatched if no completed() or canceled() signal is
731 // emitted during the maximum update interval.
732 m_maximumUpdateIntervalTimer
->start();
736 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
738 dispatchPendingItemsToInsert();
740 KFileItemList itemsToRemove
= items
;
741 if (m_requestRole
[ExpandedParentsCountRole
] && m_expandedParentsCountRoot
>= 0) {
742 // Assure that removing a parent item also results in removing all children
743 foreach (const KFileItem
& item
, items
) {
744 itemsToRemove
.append(childItems(item
));
748 if (!m_filteredItems
.isEmpty()) {
749 foreach (const KFileItem
& item
, itemsToRemove
) {
750 m_filteredItems
.remove(item
);
754 removeItems(itemsToRemove
);
757 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
759 Q_ASSERT(!items
.isEmpty());
760 #ifdef KFILEITEMMODEL_DEBUG
761 kDebug() << "Refreshing" << items
.count() << "items";
766 // Get the indexes of all items that have been refreshed
768 indexes
.reserve(items
.count());
770 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
771 while (it
.hasNext()) {
772 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
773 const KFileItem
& oldItem
= itemPair
.first
;
774 const KFileItem
& newItem
= itemPair
.second
;
775 const int index
= m_items
.value(oldItem
.url(), -1);
777 m_itemData
[index
]->item
= newItem
;
779 // Keep old values as long as possible if they could not retrieved synchronously yet.
780 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
781 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
));
782 while (it
.hasNext()) {
784 m_itemData
[index
]->values
.insert(it
.key(), it
.value());
787 m_items
.remove(oldItem
.url());
788 m_items
.insert(newItem
.url(), index
);
789 indexes
.append(index
);
793 // If the changed items have been created recently, they might not be in m_items yet.
794 // In that case, the list 'indexes' might be empty.
795 if (indexes
.isEmpty()) {
799 // Extract the item-ranges out of the changed indexes
802 KItemRangeList itemRangeList
;
803 int previousIndex
= indexes
.at(0);
804 int rangeIndex
= previousIndex
;
807 const int maxIndex
= indexes
.count() - 1;
808 for (int i
= 1; i
<= maxIndex
; ++i
) {
809 const int currentIndex
= indexes
.at(i
);
810 if (currentIndex
== previousIndex
+ 1) {
813 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
815 rangeIndex
= currentIndex
;
818 previousIndex
= currentIndex
;
821 if (rangeCount
> 0) {
822 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
825 emit
itemsChanged(itemRangeList
, m_roles
);
830 void KFileItemModel::slotClear()
832 #ifdef KFILEITEMMODEL_DEBUG
833 kDebug() << "Clearing all items";
836 m_filteredItems
.clear();
839 m_maximumUpdateIntervalTimer
->stop();
840 m_resortAllItemsTimer
->stop();
841 m_pendingItemsToInsert
.clear();
843 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
845 const int removedCount
= m_itemData
.count();
846 if (removedCount
> 0) {
847 qDeleteAll(m_itemData
);
850 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
853 m_expandedUrls
.clear();
856 void KFileItemModel::slotClear(const KUrl
& url
)
861 void KFileItemModel::slotNaturalSortingChanged()
863 m_naturalSorting
= KGlobalSettings::naturalSorting();
867 void KFileItemModel::dispatchPendingItemsToInsert()
869 if (!m_pendingItemsToInsert
.isEmpty()) {
870 insertItems(m_pendingItemsToInsert
);
871 m_pendingItemsToInsert
.clear();
875 void KFileItemModel::insertItems(const KFileItemList
& items
)
877 if (items
.isEmpty()) {
881 #ifdef KFILEITEMMODEL_DEBUG
884 kDebug() << "===========================================================";
885 kDebug() << "Inserting" << items
.count() << "items";
890 QList
<ItemData
*> sortedItems
= createItemDataList(items
);
891 KFileItemModelSortAlgorithm::sort(this, sortedItems
.begin(), sortedItems
.end());
893 #ifdef KFILEITEMMODEL_DEBUG
894 kDebug() << "[TIME] Sorting:" << timer
.elapsed();
897 KItemRangeList itemRanges
;
900 int insertedAtIndex
= -1; // Index for the current item-range
901 int insertedCount
= 0; // Count for the current item-range
902 int previouslyInsertedCount
= 0; // Sum of previously inserted items for all ranges
903 while (sourceIndex
< sortedItems
.count()) {
904 // Find target index from m_items to insert the current item
906 const int previousTargetIndex
= targetIndex
;
907 while (targetIndex
< m_itemData
.count()) {
908 if (!lessThan(m_itemData
.at(targetIndex
), sortedItems
.at(sourceIndex
))) {
914 if (targetIndex
- previousTargetIndex
> 0 && insertedAtIndex
>= 0) {
915 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
916 previouslyInsertedCount
+= insertedCount
;
917 insertedAtIndex
= targetIndex
- previouslyInsertedCount
;
921 // Insert item at the position targetIndex by transfering
922 // the ownership of the item-data from sortedItems to m_itemData.
923 // m_items will be inserted after the loop (see comment below)
924 m_itemData
.insert(targetIndex
, sortedItems
.at(sourceIndex
));
927 if (insertedAtIndex
< 0) {
928 insertedAtIndex
= targetIndex
;
929 Q_ASSERT(previouslyInsertedCount
== 0);
935 // The indexes of all m_items must be adjusted, not only the index
937 const int itemDataCount
= m_itemData
.count();
938 for (int i
= 0; i
< itemDataCount
; ++i
) {
939 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
942 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
943 emit
itemsInserted(itemRanges
);
945 #ifdef KFILEITEMMODEL_DEBUG
946 kDebug() << "[TIME] Inserting of" << items
.count() << "items:" << timer
.elapsed();
950 void KFileItemModel::removeItems(const KFileItemList
& items
)
952 if (items
.isEmpty()) {
956 #ifdef KFILEITEMMODEL_DEBUG
957 kDebug() << "Removing " << items
.count() << "items";
962 QList
<ItemData
*> sortedItems
;
963 sortedItems
.reserve(items
.count());
964 foreach (const KFileItem
& item
, items
) {
965 const int index
= m_items
.value(item
.url(), -1);
967 sortedItems
.append(m_itemData
.at(index
));
970 KFileItemModelSortAlgorithm::sort(this, sortedItems
.begin(), sortedItems
.end());
972 QList
<int> indexesToRemove
;
973 indexesToRemove
.reserve(items
.count());
975 // Calculate the item ranges that will get deleted
976 KItemRangeList itemRanges
;
977 int removedAtIndex
= -1;
978 int removedCount
= 0;
980 foreach (const ItemData
* itemData
, sortedItems
) {
981 const KFileItem
& itemToRemove
= itemData
->item
;
983 const int previousTargetIndex
= targetIndex
;
984 while (targetIndex
< m_itemData
.count()) {
985 if (m_itemData
.at(targetIndex
)->item
.url() == itemToRemove
.url()) {
990 if (targetIndex
>= m_itemData
.count()) {
991 kWarning() << "Item that should be deleted has not been found!";
995 if (targetIndex
- previousTargetIndex
> 0 && removedAtIndex
>= 0) {
996 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
997 removedAtIndex
= targetIndex
;
1001 indexesToRemove
.append(targetIndex
);
1002 if (removedAtIndex
< 0) {
1003 removedAtIndex
= targetIndex
;
1010 for (int i
= indexesToRemove
.count() - 1; i
>= 0; --i
) {
1011 const int indexToRemove
= indexesToRemove
.at(i
);
1012 ItemData
* data
= m_itemData
.at(indexToRemove
);
1014 m_items
.remove(data
->item
.url());
1017 m_itemData
.removeAt(indexToRemove
);
1020 // The indexes of all m_items must be adjusted, not only the index
1021 // of the removed items
1022 const int itemDataCount
= m_itemData
.count();
1023 for (int i
= 0; i
< itemDataCount
; ++i
) {
1024 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
1028 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
1031 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
1032 emit
itemsRemoved(itemRanges
);
1035 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const KFileItemList
& items
) const
1037 QList
<ItemData
*> itemDataList
;
1038 itemDataList
.reserve(items
.count());
1040 foreach (const KFileItem
& item
, items
) {
1041 ItemData
* itemData
= new ItemData();
1042 itemData
->item
= item
;
1043 itemData
->values
= retrieveData(item
);
1044 itemData
->parent
= 0;
1046 const bool determineParent
= m_requestRole
[ExpandedParentsCountRole
]
1047 && itemData
->values
["expandedParentsCount"].toInt() > 0;
1048 if (determineParent
) {
1049 KUrl parentUrl
= item
.url().upUrl();
1050 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
1051 const int parentIndex
= m_items
.value(parentUrl
, -1);
1052 if (parentIndex
>= 0) {
1053 itemData
->parent
= m_itemData
.at(parentIndex
);
1055 kWarning() << "Parent item not found for" << item
.url();
1059 itemDataList
.append(itemData
);
1062 return itemDataList
;
1065 void KFileItemModel::removeExpandedItems()
1067 KFileItemList expandedItems
;
1069 const int maxIndex
= m_itemData
.count() - 1;
1070 for (int i
= 0; i
<= maxIndex
; ++i
) {
1071 const ItemData
* itemData
= m_itemData
.at(i
);
1072 if (itemData
->values
.value("expandedParentsCount").toInt() > 0) {
1073 expandedItems
.append(itemData
->item
);
1077 // The m_expandedParentsCountRoot may not get reset before all items with
1078 // a bigger count have been removed.
1079 removeItems(expandedItems
);
1081 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
1082 m_expandedUrls
.clear();
1085 void KFileItemModel::resetRoles()
1087 for (int i
= 0; i
< RolesCount
; ++i
) {
1088 m_requestRole
[i
] = false;
1092 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1094 static QHash
<QByteArray
, RoleType
> roles
;
1095 if (roles
.isEmpty()) {
1096 // Insert user visible roles that can be accessed with
1097 // KFileItemModel::roleInformation()
1099 const RoleInfoMap
* map
= rolesInfoMap(count
);
1100 for (int i
= 0; i
< count
; ++i
) {
1101 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1104 // Insert internal roles (take care to synchronize the implementation
1105 // with KFileItemModel::roleForType() in case if a change is done).
1106 roles
.insert("isDir", IsDirRole
);
1107 roles
.insert("isExpanded", IsExpandedRole
);
1108 roles
.insert("isExpandable", IsExpandableRole
);
1109 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1111 Q_ASSERT(roles
.count() == RolesCount
);
1114 return roles
.value(role
, NoRole
);
1117 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1119 static QHash
<RoleType
, QByteArray
> roles
;
1120 if (roles
.isEmpty()) {
1121 // Insert user visible roles that can be accessed with
1122 // KFileItemModel::roleInformation()
1124 const RoleInfoMap
* map
= rolesInfoMap(count
);
1125 for (int i
= 0; i
< count
; ++i
) {
1126 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1129 // Insert internal roles (take care to synchronize the implementation
1130 // with KFileItemModel::typeForRole() in case if a change is done).
1131 roles
.insert(IsDirRole
, "isDir");
1132 roles
.insert(IsExpandedRole
, "isExpanded");
1133 roles
.insert(IsExpandableRole
, "isExpandable");
1134 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1136 Q_ASSERT(roles
.count() == RolesCount
);
1139 return roles
.value(roleType
);
1142 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
) const
1144 // It is important to insert only roles that are fast to retrieve. E.g.
1145 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1146 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1147 QHash
<QByteArray
, QVariant
> data
;
1148 data
.insert("url", item
.url());
1150 const bool isDir
= item
.isDir();
1151 if (m_requestRole
[IsDirRole
]) {
1152 data
.insert("isDir", isDir
);
1155 if (m_requestRole
[NameRole
]) {
1156 data
.insert("name", item
.text());
1159 if (m_requestRole
[SizeRole
]) {
1161 data
.insert("size", QVariant());
1163 data
.insert("size", item
.size());
1167 if (m_requestRole
[DateRole
]) {
1168 // Don't use KFileItem::timeString() as this is too expensive when
1169 // having several thousands of items. Instead the formatting of the
1170 // date-time will be done on-demand by the view when the date will be shown.
1171 const KDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
1172 data
.insert("date", dateTime
.dateTime());
1175 if (m_requestRole
[PermissionsRole
]) {
1176 data
.insert("permissions", item
.permissionsString());
1179 if (m_requestRole
[OwnerRole
]) {
1180 data
.insert("owner", item
.user());
1183 if (m_requestRole
[GroupRole
]) {
1184 data
.insert("group", item
.group());
1187 if (m_requestRole
[DestinationRole
]) {
1188 QString destination
= item
.linkDest();
1189 if (destination
.isEmpty()) {
1190 destination
= QLatin1String("-");
1192 data
.insert("destination", destination
);
1195 if (m_requestRole
[PathRole
]) {
1197 if (item
.url().protocol() == QLatin1String("trash")) {
1198 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1200 path
= item
.localPath();
1203 const int index
= path
.lastIndexOf(item
.text());
1204 path
= path
.mid(0, index
- 1);
1205 data
.insert("path", path
);
1208 if (m_requestRole
[IsExpandedRole
]) {
1209 data
.insert("isExpanded", false);
1212 if (m_requestRole
[IsExpandableRole
]) {
1213 data
.insert("isExpandable", item
.isDir() && item
.url() == item
.targetUrl());
1216 if (m_requestRole
[ExpandedParentsCountRole
]) {
1217 if (m_expandedParentsCountRoot
== UninitializedExpandedParentsCountRoot
&& m_dirLister
.data()) {
1218 const KUrl rootUrl
= m_dirLister
.data()->url();
1219 const QString protocol
= rootUrl
.protocol();
1220 const bool forceExpandedParentsCountRoot
= (protocol
== QLatin1String("trash") ||
1221 protocol
== QLatin1String("nepomuk") ||
1222 protocol
== QLatin1String("remote") ||
1223 protocol
.contains(QLatin1String("search")));
1224 if (forceExpandedParentsCountRoot
) {
1225 m_expandedParentsCountRoot
= ForceExpandedParentsCountRoot
;
1227 const QString rootDir
= rootUrl
.path(KUrl::AddTrailingSlash
);
1228 m_expandedParentsCountRoot
= rootDir
.count('/');
1232 if (m_expandedParentsCountRoot
== ForceExpandedParentsCountRoot
) {
1233 data
.insert("expandedParentsCount", -1);
1235 const QString dir
= item
.url().directory(KUrl::AppendTrailingSlash
);
1236 const int level
= dir
.count('/') - m_expandedParentsCountRoot
;
1237 data
.insert("expandedParentsCount", level
);
1241 if (item
.isMimeTypeKnown()) {
1242 data
.insert("iconName", item
.iconName());
1244 if (m_requestRole
[TypeRole
]) {
1245 data
.insert("type", item
.mimeComment());
1252 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
) const
1256 if (m_expandedParentsCountRoot
>= 0) {
1257 result
= expandedParentsCountCompare(a
, b
);
1259 // The items have parents with different expansion levels
1260 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1264 if (m_sortFoldersFirst
|| m_sortRole
== SizeRole
) {
1265 const bool isDirA
= a
->item
.isDir();
1266 const bool isDirB
= b
->item
.isDir();
1267 if (isDirA
&& !isDirB
) {
1269 } else if (!isDirA
&& isDirB
) {
1274 result
= sortRoleCompare(a
, b
);
1276 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1279 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
) const
1281 const KFileItem
& itemA
= a
->item
;
1282 const KFileItem
& itemB
= b
->item
;
1286 switch (m_sortRole
) {
1288 // The name role is handled as default fallback after the switch
1292 if (itemA
.isDir()) {
1293 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1294 Q_ASSERT(itemB
.isDir());
1296 const QVariant valueA
= a
->values
.value("size");
1297 const QVariant valueB
= b
->values
.value("size");
1298 if (valueA
.isNull() && valueB
.isNull()) {
1300 } else if (valueA
.isNull()) {
1302 } else if (valueB
.isNull()) {
1305 result
= valueA
.toInt() - valueB
.toInt();
1308 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1309 Q_ASSERT(!itemB
.isDir());
1310 const KIO::filesize_t sizeA
= itemA
.size();
1311 const KIO::filesize_t sizeB
= itemB
.size();
1312 if (sizeA
> sizeB
) {
1314 } else if (sizeA
< sizeB
) {
1324 const KDateTime dateTimeA
= itemA
.time(KFileItem::ModificationTime
);
1325 const KDateTime dateTimeB
= itemB
.time(KFileItem::ModificationTime
);
1326 if (dateTimeA
< dateTimeB
) {
1328 } else if (dateTimeA
> dateTimeB
) {
1335 result
= a
->values
.value("rating").toInt() - b
->values
.value("rating").toInt();
1339 case ImageSizeRole
: {
1340 // Alway use a natural comparing to interpret the numbers of a string like
1341 // "1600 x 1200" for having a correct sorting.
1342 result
= KStringHandler::naturalCompare(a
->values
.value("imageSize").toString(),
1343 b
->values
.value("imageSize").toString(),
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 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
) const
1392 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1393 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1394 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1395 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1397 if (m_caseSensitivity
== Qt::CaseInsensitive
) {
1398 const int result
= m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseInsensitive
)
1399 : QString::compare(a
, b
, Qt::CaseInsensitive
);
1401 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1402 // comparison, still a deterministic sort order is required. A case sensitive
1403 // comparison is done as fallback.
1408 return m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseSensitive
)
1409 : QString::compare(a
, b
, Qt::CaseSensitive
);
1412 int KFileItemModel::expandedParentsCountCompare(const ItemData
* a
, const ItemData
* b
) const
1414 const KUrl urlA
= a
->item
.url();
1415 const KUrl urlB
= b
->item
.url();
1416 if (urlA
.directory() == urlB
.directory()) {
1417 // Both items have the same directory as parent
1421 // Check whether one item is the parent of the other item
1422 if (urlA
.isParentOf(urlB
)) {
1423 return (sortOrder() == Qt::AscendingOrder
) ? -1 : +1;
1424 } else if (urlB
.isParentOf(urlA
)) {
1425 return (sortOrder() == Qt::AscendingOrder
) ? +1 : -1;
1428 // Determine the maximum common path of both items and
1429 // remember the index in 'index'
1430 const QString pathA
= urlA
.path();
1431 const QString pathB
= urlB
.path();
1433 const int maxIndex
= qMin(pathA
.length(), pathB
.length()) - 1;
1435 while (index
<= maxIndex
&& pathA
.at(index
) == pathB
.at(index
)) {
1438 if (index
> maxIndex
) {
1441 while ((pathA
.at(index
) != QLatin1Char('/') || pathB
.at(index
) != QLatin1Char('/')) && index
> 0) {
1445 // Determine the first sub-path after the common path and
1446 // check whether it represents a directory or already a file
1448 const QString subPathA
= subPath(a
->item
, pathA
, index
, &isDirA
);
1450 const QString subPathB
= subPath(b
->item
, pathB
, index
, &isDirB
);
1452 if (m_sortFoldersFirst
|| m_sortRole
== SizeRole
) {
1453 if (isDirA
&& !isDirB
) {
1454 return (sortOrder() == Qt::AscendingOrder
) ? -1 : +1;
1455 } else if (!isDirA
&& isDirB
) {
1456 return (sortOrder() == Qt::AscendingOrder
) ? +1 : -1;
1460 // Compare the items of the parents that represent the first
1461 // different path after the common path.
1462 const QString parentPathA
= pathA
.left(index
) + subPathA
;
1463 const QString parentPathB
= pathB
.left(index
) + subPathB
;
1465 const ItemData
* parentA
= a
;
1466 while (parentA
&& parentA
->item
.url().path() != parentPathA
) {
1467 parentA
= parentA
->parent
;
1470 const ItemData
* parentB
= b
;
1471 while (parentB
&& parentB
->item
.url().path() != parentPathB
) {
1472 parentB
= parentB
->parent
;
1475 if (parentA
&& parentB
) {
1476 return sortRoleCompare(parentA
, parentB
);
1479 kWarning() << "Child items without parent detected:" << a
->item
.url() << b
->item
.url();
1480 return QString::compare(urlA
.url(), urlB
.url(), Qt::CaseSensitive
);
1483 QString
KFileItemModel::subPath(const KFileItem
& item
,
1484 const QString
& itemPath
,
1489 const int pathIndex
= itemPath
.indexOf('/', start
+ 1);
1490 *isDir
= (pathIndex
> 0) || item
.isDir();
1491 return itemPath
.mid(start
, pathIndex
- start
);
1494 bool KFileItemModel::useMaximumUpdateInterval() const
1496 const KDirLister
* dirLister
= m_dirLister
.data();
1497 return dirLister
&& !dirLister
->url().isLocalFile();
1500 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1502 Q_ASSERT(!m_itemData
.isEmpty());
1504 const int maxIndex
= count() - 1;
1505 QList
<QPair
<int, QVariant
> > groups
;
1509 bool isLetter
= false;
1510 for (int i
= 0; i
<= maxIndex
; ++i
) {
1511 if (isChildItem(i
)) {
1515 const QString name
= m_itemData
.at(i
)->values
.value("name").toString();
1517 // Use the first character of the name as group indication
1518 QChar newFirstChar
= name
.at(0).toUpper();
1519 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1520 newFirstChar
= name
.at(1).toUpper();
1523 if (firstChar
!= newFirstChar
) {
1524 QString newGroupValue
;
1525 if (newFirstChar
>= QLatin1Char('A') && newFirstChar
<= QLatin1Char('Z')) {
1526 // Apply group 'A' - 'Z'
1527 newGroupValue
= newFirstChar
;
1529 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
1530 // Apply group '0 - 9' for any name that starts with a digit
1531 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
1535 // If the current group is 'A' - 'Z' check whether a locale character
1536 // fits into the existing group.
1537 // TODO: This does not work in the case if e.g. the group 'O' starts with
1538 // an umlaut 'O' -> provide unit-test to document this known issue
1539 const QChar
prevChar(firstChar
.unicode() - ushort(1));
1540 const QChar
nextChar(firstChar
.unicode() + ushort(1));
1541 const QString
currChar(newFirstChar
);
1542 const bool partOfCurrentGroup
= currChar
.localeAwareCompare(prevChar
) > 0 &&
1543 currChar
.localeAwareCompare(nextChar
) < 0;
1544 if (partOfCurrentGroup
) {
1548 newGroupValue
= i18nc("@title:group", "Others");
1552 if (newGroupValue
!= groupValue
) {
1553 groupValue
= newGroupValue
;
1554 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1557 firstChar
= newFirstChar
;
1563 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
1565 Q_ASSERT(!m_itemData
.isEmpty());
1567 const int maxIndex
= count() - 1;
1568 QList
<QPair
<int, QVariant
> > groups
;
1571 for (int i
= 0; i
<= maxIndex
; ++i
) {
1572 if (isChildItem(i
)) {
1576 const KFileItem
& item
= m_itemData
.at(i
)->item
;
1577 const KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
1578 QString newGroupValue
;
1579 if (!item
.isNull() && item
.isDir()) {
1580 newGroupValue
= i18nc("@title:group Size", "Folders");
1581 } else if (fileSize
< 5 * 1024 * 1024) {
1582 newGroupValue
= i18nc("@title:group Size", "Small");
1583 } else if (fileSize
< 10 * 1024 * 1024) {
1584 newGroupValue
= i18nc("@title:group Size", "Medium");
1586 newGroupValue
= i18nc("@title:group Size", "Big");
1589 if (newGroupValue
!= groupValue
) {
1590 groupValue
= newGroupValue
;
1591 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1598 QList
<QPair
<int, QVariant
> > KFileItemModel::dateRoleGroups() const
1600 Q_ASSERT(!m_itemData
.isEmpty());
1602 const int maxIndex
= count() - 1;
1603 QList
<QPair
<int, QVariant
> > groups
;
1605 const QDate currentDate
= KDateTime::currentLocalDateTime().date();
1607 int yearForCurrentWeek
= 0;
1608 int currentWeek
= currentDate
.weekNumber(&yearForCurrentWeek
);
1609 if (yearForCurrentWeek
== currentDate
.year() + 1) {
1613 QDate previousModifiedDate
;
1615 for (int i
= 0; i
<= maxIndex
; ++i
) {
1616 if (isChildItem(i
)) {
1620 const KDateTime modifiedTime
= m_itemData
.at(i
)->item
.time(KFileItem::ModificationTime
);
1621 const QDate modifiedDate
= modifiedTime
.date();
1622 if (modifiedDate
== previousModifiedDate
) {
1623 // The current item is in the same group as the previous item
1626 previousModifiedDate
= modifiedDate
;
1628 const int daysDistance
= modifiedDate
.daysTo(currentDate
);
1630 int yearForModifiedWeek
= 0;
1631 int modifiedWeek
= modifiedDate
.weekNumber(&yearForModifiedWeek
);
1632 if (yearForModifiedWeek
== modifiedDate
.year() + 1) {
1636 QString newGroupValue
;
1637 if (currentDate
.year() == modifiedDate
.year() && currentDate
.month() == modifiedDate
.month()) {
1638 if (modifiedWeek
> currentWeek
) {
1639 // Usecase: modified date = 2010-01-01, current date = 2010-01-22
1640 // modified week = 53, current week = 3
1643 switch (currentWeek
- modifiedWeek
) {
1645 switch (daysDistance
) {
1646 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
1647 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
1648 default: newGroupValue
= modifiedTime
.toString(i18nc("@title:group The week day name: %A", "%A"));
1652 newGroupValue
= i18nc("@title:group Date", "Last Week");
1655 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
1658 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
1662 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
1668 const QDate lastMonthDate
= currentDate
.addMonths(-1);
1669 if (lastMonthDate
.year() == modifiedDate
.year() && lastMonthDate
.month() == modifiedDate
.month()) {
1670 if (daysDistance
== 1) {
1671 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Yesterday (%B, %Y)"));
1672 } else if (daysDistance
<= 7) {
1673 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)"));
1674 } else if (daysDistance
<= 7 * 2) {
1675 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)"));
1676 } else if (daysDistance
<= 7 * 3) {
1677 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)"));
1678 } else if (daysDistance
<= 7 * 4) {
1679 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)"));
1681 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"));
1684 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"));
1688 if (newGroupValue
!= groupValue
) {
1689 groupValue
= newGroupValue
;
1690 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1697 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
1699 Q_ASSERT(!m_itemData
.isEmpty());
1701 const int maxIndex
= count() - 1;
1702 QList
<QPair
<int, QVariant
> > groups
;
1704 QString permissionsString
;
1706 for (int i
= 0; i
<= maxIndex
; ++i
) {
1707 if (isChildItem(i
)) {
1711 const ItemData
* itemData
= m_itemData
.at(i
);
1712 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
1713 if (newPermissionsString
== permissionsString
) {
1716 permissionsString
= newPermissionsString
;
1718 const QFileInfo
info(itemData
->item
.url().pathOrUrl());
1722 if (info
.permission(QFile::ReadUser
)) {
1723 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1725 if (info
.permission(QFile::WriteUser
)) {
1726 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1728 if (info
.permission(QFile::ExeUser
)) {
1729 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1731 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
1735 if (info
.permission(QFile::ReadGroup
)) {
1736 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1738 if (info
.permission(QFile::WriteGroup
)) {
1739 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1741 if (info
.permission(QFile::ExeGroup
)) {
1742 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1744 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
1746 // Set others string
1748 if (info
.permission(QFile::ReadOther
)) {
1749 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1751 if (info
.permission(QFile::WriteOther
)) {
1752 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1754 if (info
.permission(QFile::ExeOther
)) {
1755 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1757 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
1759 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
1760 if (newGroupValue
!= groupValue
) {
1761 groupValue
= newGroupValue
;
1762 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1769 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
1771 Q_ASSERT(!m_itemData
.isEmpty());
1773 const int maxIndex
= count() - 1;
1774 QList
<QPair
<int, QVariant
> > groups
;
1776 int groupValue
= -1;
1777 for (int i
= 0; i
<= maxIndex
; ++i
) {
1778 if (isChildItem(i
)) {
1781 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
1782 if (newGroupValue
!= groupValue
) {
1783 groupValue
= newGroupValue
;
1784 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1791 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
1793 Q_ASSERT(!m_itemData
.isEmpty());
1795 const int maxIndex
= count() - 1;
1796 QList
<QPair
<int, QVariant
> > groups
;
1798 bool isFirstGroupValue
= true;
1800 for (int i
= 0; i
<= maxIndex
; ++i
) {
1801 if (isChildItem(i
)) {
1804 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
1805 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
1806 groupValue
= newGroupValue
;
1807 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1808 isFirstGroupValue
= false;
1815 KFileItemList
KFileItemModel::childItems(const KFileItem
& item
) const
1817 KFileItemList items
;
1819 int index
= m_items
.value(item
.url(), -1);
1821 const int parentLevel
= m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt();
1823 while (index
< m_itemData
.count() && m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt() > parentLevel
) {
1824 items
.append(m_itemData
.at(index
)->item
);
1832 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
1834 static const RoleInfoMap rolesInfoMap
[] = {
1835 // | role | roleType | role translation | group translation | requires Nepomuk | requires indexer
1836 { 0, NoRole
, 0, 0, 0, 0, false, false },
1837 { "name", NameRole
, I18N_NOOP2_NOSTRIP("@label", "Name"), 0, 0, false, false },
1838 { "size", SizeRole
, I18N_NOOP2_NOSTRIP("@label", "Size"), 0, 0, false, false },
1839 { "date", DateRole
, I18N_NOOP2_NOSTRIP("@label", "Date"), 0, 0, false, false },
1840 { "type", TypeRole
, I18N_NOOP2_NOSTRIP("@label", "Type"), 0, 0, false, false },
1841 { "rating", RatingRole
, I18N_NOOP2_NOSTRIP("@label", "Rating"), 0, 0, true, false },
1842 { "tags", TagsRole
, I18N_NOOP2_NOSTRIP("@label", "Tags"), 0, 0, true, false },
1843 { "comment", CommentRole
, I18N_NOOP2_NOSTRIP("@label", "Comment"), 0, 0, true, false },
1844 { "wordCount", WordCountRole
, I18N_NOOP2_NOSTRIP("@label", "Word Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
1845 { "lineCount", LineCountRole
, I18N_NOOP2_NOSTRIP("@label", "Line Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
1846 { "imageSize", ImageSizeRole
, I18N_NOOP2_NOSTRIP("@label", "Image Size"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
1847 { "orientation", OrientationRole
, I18N_NOOP2_NOSTRIP("@label", "Orientation"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
1848 { "artist", ArtistRole
, I18N_NOOP2_NOSTRIP("@label", "Artist"), I18N_NOOP2_NOSTRIP("@label", "Music"), true, true },
1849 { "album", AlbumRole
, I18N_NOOP2_NOSTRIP("@label", "Album"), I18N_NOOP2_NOSTRIP("@label", "Music"), true, true },
1850 { "duration", DurationRole
, I18N_NOOP2_NOSTRIP("@label", "Duration"), I18N_NOOP2_NOSTRIP("@label", "Music"), true, true },
1851 { "track", TrackRole
, I18N_NOOP2_NOSTRIP("@label", "Track"), I18N_NOOP2_NOSTRIP("@label", "Music"), true, true },
1852 { "path", PathRole
, I18N_NOOP2_NOSTRIP("@label", "Path"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1853 { "destination", DestinationRole
, I18N_NOOP2_NOSTRIP("@label", "Link Destination"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1854 { "copiedFrom", CopiedFromRole
, I18N_NOOP2_NOSTRIP("@label", "Copied From"), I18N_NOOP2_NOSTRIP("@label", "Other"), true, false },
1855 { "permissions", PermissionsRole
, I18N_NOOP2_NOSTRIP("@label", "Permissions"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1856 { "owner", OwnerRole
, I18N_NOOP2_NOSTRIP("@label", "Owner"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1857 { "group", GroupRole
, I18N_NOOP2_NOSTRIP("@label", "User Group"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1860 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
1861 return rolesInfoMap
;
1864 #include "kfileitemmodel.moc"