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"
23 #include <KGlobalSettings>
25 #include <KStringHandler>
28 #include "private/kfileitemmodelsortalgorithm.h"
29 #include "private/kfileitemmodeldirlister.h"
31 #include <QApplication>
35 // #define KFILEITEMMODEL_DEBUG
37 KFileItemModel::KFileItemModel(QObject
* parent
) :
38 KItemModelBase("text", parent
),
40 m_naturalSorting(KGlobalSettings::naturalSorting()),
41 m_sortDirsFirst(true),
43 m_sortingProgressPercent(-1),
45 m_caseSensitivity(Qt::CaseInsensitive
),
51 m_maximumUpdateIntervalTimer(0),
52 m_resortAllItemsTimer(0),
53 m_pendingItemsToInsert(),
55 m_expandedParentsCountRoot(UninitializedExpandedParentsCountRoot
),
59 m_dirLister
= new KFileItemModelDirLister(this);
60 m_dirLister
->setAutoUpdate(true);
61 m_dirLister
->setDelayedMimeTypes(true);
62 m_dirLister
->setMainWindow(qApp
->activeWindow());
64 connect(m_dirLister
, SIGNAL(started(KUrl
)), this, SIGNAL(directoryLoadingStarted()));
65 connect(m_dirLister
, SIGNAL(canceled()), this, SLOT(slotCanceled()));
66 connect(m_dirLister
, SIGNAL(completed(KUrl
)), this, SLOT(slotCompleted()));
67 connect(m_dirLister
, SIGNAL(newItems(KFileItemList
)), this, SLOT(slotNewItems(KFileItemList
)));
68 connect(m_dirLister
, SIGNAL(itemsDeleted(KFileItemList
)), this, SLOT(slotItemsDeleted(KFileItemList
)));
69 connect(m_dirLister
, SIGNAL(refreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)), this, SLOT(slotRefreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)));
70 connect(m_dirLister
, SIGNAL(clear()), this, SLOT(slotClear()));
71 connect(m_dirLister
, SIGNAL(clear(KUrl
)), this, SLOT(slotClear(KUrl
)));
72 connect(m_dirLister
, SIGNAL(infoMessage(QString
)), this, SIGNAL(infoMessage(QString
)));
73 connect(m_dirLister
, SIGNAL(errorMessage(QString
)), this, SIGNAL(errorMessage(QString
)));
74 connect(m_dirLister
, SIGNAL(redirection(KUrl
,KUrl
)), this, SIGNAL(directoryRedirection(KUrl
,KUrl
)));
76 // Apply default roles that should be determined
78 m_requestRole
[NameRole
] = true;
79 m_requestRole
[IsDirRole
] = true;
80 m_requestRole
[IsLinkRole
] = true;
81 m_roles
.insert("text");
82 m_roles
.insert("isDir");
83 m_roles
.insert("isLink");
85 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
86 // before the completed() or canceled() signal has been emitted.
87 m_maximumUpdateIntervalTimer
= new QTimer(this);
88 m_maximumUpdateIntervalTimer
->setInterval(2000);
89 m_maximumUpdateIntervalTimer
->setSingleShot(true);
90 connect(m_maximumUpdateIntervalTimer
, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
92 // When changing the value of an item which represents the sort-role a resorting must be
93 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
94 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
95 // resorting is postponed until the timer has been exceeded.
96 m_resortAllItemsTimer
= new QTimer(this);
97 m_resortAllItemsTimer
->setInterval(500);
98 m_resortAllItemsTimer
->setSingleShot(true);
99 connect(m_resortAllItemsTimer
, SIGNAL(timeout()), this, SLOT(resortAllItems()));
101 connect(KGlobalSettings::self(), SIGNAL(naturalSortingChanged()), this, SLOT(slotNaturalSortingChanged()));
104 KFileItemModel::~KFileItemModel()
106 qDeleteAll(m_itemData
);
110 void KFileItemModel::loadDirectory(const KUrl
& url
)
112 m_dirLister
->openUrl(url
);
115 void KFileItemModel::refreshDirectory(const KUrl
& url
)
117 m_dirLister
->openUrl(url
, KDirLister::Reload
);
120 KUrl
KFileItemModel::directory() const
122 return m_dirLister
->url();
125 void KFileItemModel::cancelDirectoryLoading()
130 int KFileItemModel::count() const
132 return m_itemData
.count();
135 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
137 if (index
>= 0 && index
< count()) {
138 return m_itemData
.at(index
)->values
;
140 return QHash
<QByteArray
, QVariant
>();
143 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
145 if (index
< 0 || index
>= count()) {
149 QHash
<QByteArray
, QVariant
> currentValues
= m_itemData
.at(index
)->values
;
151 // Determine which roles have been changed
152 QSet
<QByteArray
> changedRoles
;
153 QHashIterator
<QByteArray
, QVariant
> it(values
);
154 while (it
.hasNext()) {
156 const QByteArray role
= it
.key();
157 const QVariant value
= it
.value();
159 if (currentValues
[role
] != value
) {
160 currentValues
[role
] = value
;
161 changedRoles
.insert(role
);
165 if (changedRoles
.isEmpty()) {
169 m_itemData
[index
]->values
= currentValues
;
170 emit
itemsChanged(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
172 if (changedRoles
.contains(sortRole())) {
173 m_resortAllItemsTimer
->start();
179 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
181 if (dirsFirst
!= m_sortDirsFirst
) {
182 m_sortDirsFirst
= dirsFirst
;
187 bool KFileItemModel::sortDirectoriesFirst() const
189 return m_sortDirsFirst
;
192 void KFileItemModel::setShowHiddenFiles(bool show
)
194 m_dirLister
->setShowingDotFiles(show
);
195 m_dirLister
->emitChanges();
201 bool KFileItemModel::showHiddenFiles() const
203 return m_dirLister
->showingDotFiles();
206 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
208 m_dirLister
->setDirOnlyMode(enabled
);
211 bool KFileItemModel::showDirectoriesOnly() const
213 return m_dirLister
->dirOnlyMode();
216 QMimeData
* KFileItemModel::createMimeData(const QSet
<int>& indexes
) const
218 QMimeData
* data
= new QMimeData();
220 // The following code has been taken from KDirModel::mimeData()
221 // (kdelibs/kio/kio/kdirmodel.cpp)
222 // Copyright (C) 2006 David Faure <faure@kde.org>
224 KUrl::List mostLocalUrls
;
225 bool canUseMostLocalUrls
= true;
227 QSetIterator
<int> it(indexes
);
228 while (it
.hasNext()) {
229 const int index
= it
.next();
230 const KFileItem item
= fileItem(index
);
231 if (!item
.isNull()) {
235 mostLocalUrls
<< item
.mostLocalUrl(isLocal
);
237 canUseMostLocalUrls
= false;
242 const bool different
= canUseMostLocalUrls
&& mostLocalUrls
!= urls
;
243 urls
= KDirModel::simplifiedUrlList(urls
); // TODO: Check if we still need KDirModel for this in KDE 5.0
245 mostLocalUrls
= KDirModel::simplifiedUrlList(mostLocalUrls
);
246 urls
.populateMimeData(mostLocalUrls
, data
);
248 urls
.populateMimeData(data
);
254 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
256 startFromIndex
= qMax(0, startFromIndex
);
257 for (int i
= startFromIndex
; i
< count(); ++i
) {
258 if (data(i
)["text"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
262 for (int i
= 0; i
< startFromIndex
; ++i
) {
263 if (data(i
)["text"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
270 bool KFileItemModel::supportsDropping(int index
) const
272 const KFileItem item
= fileItem(index
);
273 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
276 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
278 static QHash
<QByteArray
, QString
> description
;
279 if (description
.isEmpty()) {
281 const RoleInfoMap
* map
= rolesInfoMap(count
);
282 for (int i
= 0; i
< count
; ++i
) {
283 description
.insert(map
[i
].role
, map
[i
].roleTranslation
);
287 return description
.value(role
);
290 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
292 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
293 #ifdef KFILEITEMMODEL_DEBUG
297 switch (typeForRole(sortRole())) {
298 case NameRole
: m_groups
= nameRoleGroups(); break;
299 case SizeRole
: m_groups
= sizeRoleGroups(); break;
300 case DateRole
: m_groups
= dateRoleGroups(); break;
301 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
302 case RatingRole
: m_groups
= ratingRoleGroups(); break;
303 default: m_groups
= genericStringRoleGroups(sortRole()); break;
306 #ifdef KFILEITEMMODEL_DEBUG
307 kDebug() << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
314 KFileItem
KFileItemModel::fileItem(int index
) const
316 if (index
>= 0 && index
< count()) {
317 return m_itemData
.at(index
)->item
;
323 KFileItem
KFileItemModel::fileItem(const KUrl
& url
) const
325 const int index
= m_items
.value(url
, -1);
327 return m_itemData
.at(index
)->item
;
332 int KFileItemModel::index(const KFileItem
& item
) const
338 return m_items
.value(item
.url(), -1);
341 int KFileItemModel::index(const KUrl
& url
) const
343 KUrl urlToFind
= url
;
344 urlToFind
.adjustPath(KUrl::RemoveTrailingSlash
);
345 return m_items
.value(urlToFind
, -1);
348 KFileItem
KFileItemModel::rootItem() const
350 return m_dirLister
->rootItem();
353 void KFileItemModel::clear()
358 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
360 if (m_roles
== roles
) {
366 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
367 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
368 if (supportedExpanding
&& !willSupportExpanding
) {
369 // No expanding is supported anymore. Take care to delete all items that have an expansion level
370 // that is not 0 (and hence are part of an expanded item).
371 removeExpandedItems();
378 QSetIterator
<QByteArray
> it(roles
);
379 while (it
.hasNext()) {
380 const QByteArray
& role
= it
.next();
381 m_requestRole
[typeForRole(role
)] = true;
385 // Update m_data with the changed requested roles
386 const int maxIndex
= count() - 1;
387 for (int i
= 0; i
<= maxIndex
; ++i
) {
388 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
);
391 kWarning() << "TODO: Emitting itemsChanged() with no information what has changed!";
392 emit
itemsChanged(KItemRangeList() << KItemRange(0, count()), QSet
<QByteArray
>());
396 QSet
<QByteArray
> KFileItemModel::roles() const
401 bool KFileItemModel::setExpanded(int index
, bool expanded
)
403 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
407 QHash
<QByteArray
, QVariant
> values
;
408 values
.insert("isExpanded", expanded
);
409 if (!setData(index
, values
)) {
413 const KUrl url
= m_itemData
.at(index
)->item
.url();
415 m_expandedDirs
.insert(url
);
416 m_dirLister
->openUrl(url
, KDirLister::Keep
);
418 m_expandedDirs
.remove(url
);
419 m_dirLister
->stop(url
);
422 KFileItemList itemsToRemove
;
423 const int expandedParentsCount
= data(index
)["expandedParentsCount"].toInt();
425 while (index
< count() && data(index
)["expandedParentsCount"].toInt() > expandedParentsCount
) {
426 itemsToRemove
.append(m_itemData
.at(index
)->item
);
429 removeItems(itemsToRemove
);
435 bool KFileItemModel::isExpanded(int index
) const
437 if (index
>= 0 && index
< count()) {
438 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
443 bool KFileItemModel::isExpandable(int index
) const
445 if (index
>= 0 && index
< count()) {
446 return m_itemData
.at(index
)->values
.value("isExpandable").toBool();
451 int KFileItemModel::expandedParentsCount(int index
) const
453 if (index
>= 0 && index
< count()) {
454 const int parentsCount
= m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt();
455 if (parentsCount
> 0) {
462 QSet
<KUrl
> KFileItemModel::expandedDirectories() const
464 return m_expandedDirs
;
467 void KFileItemModel::restoreExpandedDirectories(const QSet
<KUrl
>& urls
)
469 m_urlsToExpand
= urls
;
472 void KFileItemModel::expandParentDirectories(const KUrl
& url
)
474 const int pos
= m_dirLister
->url().path().length();
476 // Assure that each sub-path of the URL that should be
477 // expanded is added to m_urlsToExpand. KDirLister
478 // does not care whether the parent-URL has already been
480 KUrl urlToExpand
= m_dirLister
->url();
481 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator());
482 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
483 urlToExpand
.addPath(subDirs
.at(i
));
484 m_urlsToExpand
.insert(urlToExpand
);
487 // KDirLister::open() must called at least once to trigger an initial
488 // loading. The pending URLs that must be restored are handled
489 // in slotCompleted().
490 QSetIterator
<KUrl
> it2(m_urlsToExpand
);
491 while (it2
.hasNext()) {
492 const int idx
= index(it2
.next());
493 if (idx
>= 0 && !isExpanded(idx
)) {
494 setExpanded(idx
, true);
500 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
502 if (m_filter
.pattern() != nameFilter
) {
503 dispatchPendingItemsToInsert();
505 m_filter
.setPattern(nameFilter
);
507 // Check which shown items from m_itemData must get
508 // hidden and hence moved to m_filteredItems.
509 KFileItemList newFilteredItems
;
511 foreach (ItemData
* itemData
, m_itemData
) {
512 if (!m_filter
.matches(itemData
->item
)) {
513 // Only filter non-expanded items as child items may never
514 // exist without a parent item
515 if (!itemData
->values
.value("isExpanded").toBool()) {
516 newFilteredItems
.append(itemData
->item
);
517 m_filteredItems
.insert(itemData
->item
);
522 removeItems(newFilteredItems
);
524 // Check which hidden items from m_filteredItems should
525 // get visible again and hence removed from m_filteredItems.
526 KFileItemList newVisibleItems
;
528 QMutableSetIterator
<KFileItem
> it(m_filteredItems
);
529 while (it
.hasNext()) {
530 const KFileItem item
= it
.next();
531 if (m_filter
.matches(item
)) {
532 newVisibleItems
.append(item
);
537 insertItems(newVisibleItems
);
541 QString
KFileItemModel::nameFilter() const
543 return m_filter
.pattern();
546 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
548 static QList
<RoleInfo
> rolesInfo
;
549 if (rolesInfo
.isEmpty()) {
551 const RoleInfoMap
* map
= rolesInfoMap(count
);
552 for (int i
= 0; i
< count
; ++i
) {
553 if (map
[i
].roleType
!= NoRole
) {
555 info
.role
= map
[i
].role
;
556 info
.translation
= map
[i
].roleTranslation
;
557 info
.group
= map
[i
].groupTranslation
;
558 info
.requiresNepomuk
= map
[i
].requiresNepomuk
;
559 info
.requiresIndexer
= map
[i
].requiresIndexer
;
560 rolesInfo
.append(info
);
568 void KFileItemModel::onGroupedSortingChanged(bool current
)
574 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
577 m_sortRole
= typeForRole(current
);
579 #ifdef KFILEITEMMODEL_DEBUG
580 if (!m_requestRole
[m_sortRole
]) {
581 kWarning() << "The sort-role has been changed to a role that has not been received yet";
588 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
595 void KFileItemModel::resortAllItems()
597 m_resortAllItemsTimer
->stop();
599 const int itemCount
= count();
600 if (itemCount
<= 0) {
604 #ifdef KFILEITEMMODEL_DEBUG
607 kDebug() << "===========================================================";
608 kDebug() << "Resorting" << itemCount
<< "items";
611 // Remember the order of the current URLs so
612 // that it can be determined which indexes have
613 // been moved because of the resorting.
615 oldUrls
.reserve(itemCount
);
616 foreach (const ItemData
* itemData
, m_itemData
) {
617 oldUrls
.append(itemData
->item
.url());
624 KFileItemModelSortAlgorithm::sort(this, m_itemData
.begin(), m_itemData
.end());
625 for (int i
= 0; i
< itemCount
; ++i
) {
626 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
629 // Determine the indexes that have been moved
630 QList
<int> movedToIndexes
;
631 movedToIndexes
.reserve(itemCount
);
632 for (int i
= 0; i
< itemCount
; i
++) {
633 const int newIndex
= m_items
.value(oldUrls
.at(i
).url());
634 movedToIndexes
.append(newIndex
);
637 // Don't check whether items have really been moved and always emit a
638 // itemsMoved() signal after resorting: In case of grouped items
639 // the groups might change even if the items themselves don't change their
640 // position. Let the receiver of the signal decide whether a check for moved
641 // items makes sense.
642 emit
itemsMoved(KItemRange(0, itemCount
), movedToIndexes
);
644 #ifdef KFILEITEMMODEL_DEBUG
645 kDebug() << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
649 void KFileItemModel::slotCompleted()
651 dispatchPendingItemsToInsert();
653 if (!m_urlsToExpand
.isEmpty()) {
654 // Try to find a URL that can be expanded.
655 // Note that the parent folder must be expanded before any of its subfolders become visible.
656 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
657 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
658 foreach (const KUrl
& url
, m_urlsToExpand
) {
659 const int index
= m_items
.value(url
, -1);
661 m_urlsToExpand
.remove(url
);
662 if (setExpanded(index
, true)) {
663 // The dir lister has been triggered. This slot will be called
664 // again after the directory has been expanded.
670 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
671 // if these URLs have been deleted in the meantime.
672 m_urlsToExpand
.clear();
675 emit
directoryLoadingCompleted();
678 void KFileItemModel::slotCanceled()
680 m_maximumUpdateIntervalTimer
->stop();
681 dispatchPendingItemsToInsert();
684 void KFileItemModel::slotNewItems(const KFileItemList
& items
)
686 Q_ASSERT(!items
.isEmpty());
688 if (m_requestRole
[ExpandedParentsCountRole
] && m_expandedParentsCountRoot
>= 0) {
689 // To be able to compare whether the new items may be inserted as children
690 // of a parent item the pending items must be added to the model first.
691 dispatchPendingItemsToInsert();
693 KFileItem item
= items
.first();
695 // If the expanding of items is enabled, the call
696 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
697 // might result in emitting the same items twice due to the Keep-parameter.
698 // This case happens if an item gets expanded, collapsed and expanded again
699 // before the items could be loaded for the first expansion.
700 const int index
= m_items
.value(item
.url(), -1);
702 // The items are already part of the model.
706 // KDirLister keeps the children of items that got expanded once even if
707 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
708 // checked whether the parent for new items is still expanded.
709 KUrl parentUrl
= item
.url().upUrl();
710 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
711 const int parentIndex
= m_items
.value(parentUrl
, -1);
712 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
713 // The parent is not expanded.
718 if (m_filter
.pattern().isEmpty()) {
719 m_pendingItemsToInsert
.append(items
);
721 // The name-filter is active. Hide filtered items
722 // before inserting them into the model and remember
723 // the filtered items in m_filteredItems.
724 KFileItemList filteredItems
;
725 foreach (const KFileItem
& item
, items
) {
726 if (m_filter
.matches(item
)) {
727 filteredItems
.append(item
);
729 m_filteredItems
.insert(item
);
733 m_pendingItemsToInsert
.append(filteredItems
);
736 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer
->isActive()) {
737 // Assure that items get dispatched if no completed() or canceled() signal is
738 // emitted during the maximum update interval.
739 m_maximumUpdateIntervalTimer
->start();
743 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
745 dispatchPendingItemsToInsert();
747 KFileItemList itemsToRemove
= items
;
748 if (m_requestRole
[ExpandedParentsCountRole
] && m_expandedParentsCountRoot
>= 0) {
749 // Assure that removing a parent item also results in removing all children
750 foreach (const KFileItem
& item
, items
) {
751 itemsToRemove
.append(childItems(item
));
755 if (!m_filteredItems
.isEmpty()) {
756 foreach (const KFileItem
& item
, itemsToRemove
) {
757 m_filteredItems
.remove(item
);
761 removeItems(itemsToRemove
);
764 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
766 Q_ASSERT(!items
.isEmpty());
767 #ifdef KFILEITEMMODEL_DEBUG
768 kDebug() << "Refreshing" << items
.count() << "items";
773 // Get the indexes of all items that have been refreshed
775 indexes
.reserve(items
.count());
777 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
778 while (it
.hasNext()) {
779 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
780 const KFileItem
& oldItem
= itemPair
.first
;
781 const KFileItem
& newItem
= itemPair
.second
;
782 const int index
= m_items
.value(oldItem
.url(), -1);
784 m_itemData
[index
]->item
= newItem
;
786 // Keep old values as long as possible if they could not retrieved synchronously yet.
787 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
788 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
));
789 while (it
.hasNext()) {
791 m_itemData
[index
]->values
.insert(it
.key(), it
.value());
794 m_items
.remove(oldItem
.url());
795 m_items
.insert(newItem
.url(), index
);
796 indexes
.append(index
);
800 // If the changed items have been created recently, they might not be in m_items yet.
801 // In that case, the list 'indexes' might be empty.
802 if (indexes
.isEmpty()) {
806 // Extract the item-ranges out of the changed indexes
809 KItemRangeList itemRangeList
;
810 int previousIndex
= indexes
.at(0);
811 int rangeIndex
= previousIndex
;
814 const int maxIndex
= indexes
.count() - 1;
815 for (int i
= 1; i
<= maxIndex
; ++i
) {
816 const int currentIndex
= indexes
.at(i
);
817 if (currentIndex
== previousIndex
+ 1) {
820 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
822 rangeIndex
= currentIndex
;
825 previousIndex
= currentIndex
;
828 if (rangeCount
> 0) {
829 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
832 emit
itemsChanged(itemRangeList
, m_roles
);
837 void KFileItemModel::slotClear()
839 #ifdef KFILEITEMMODEL_DEBUG
840 kDebug() << "Clearing all items";
843 m_filteredItems
.clear();
846 m_maximumUpdateIntervalTimer
->stop();
847 m_resortAllItemsTimer
->stop();
848 m_pendingItemsToInsert
.clear();
850 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
852 const int removedCount
= m_itemData
.count();
853 if (removedCount
> 0) {
854 qDeleteAll(m_itemData
);
857 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
860 m_expandedDirs
.clear();
863 void KFileItemModel::slotClear(const KUrl
& url
)
868 void KFileItemModel::slotNaturalSortingChanged()
870 m_naturalSorting
= KGlobalSettings::naturalSorting();
874 void KFileItemModel::dispatchPendingItemsToInsert()
876 if (!m_pendingItemsToInsert
.isEmpty()) {
877 insertItems(m_pendingItemsToInsert
);
878 m_pendingItemsToInsert
.clear();
882 void KFileItemModel::insertItems(const KFileItemList
& items
)
884 if (items
.isEmpty()) {
888 if (m_sortRole
== TypeRole
) {
889 // Try to resolve the MIME-types synchronously to prevent a reordering of
890 // the items when sorting by type (per default MIME-types are resolved
891 // asynchronously by KFileItemModelRolesUpdater).
892 determineMimeTypes(items
, 200);
895 #ifdef KFILEITEMMODEL_DEBUG
898 kDebug() << "===========================================================";
899 kDebug() << "Inserting" << items
.count() << "items";
904 QList
<ItemData
*> sortedItems
= createItemDataList(items
);
905 KFileItemModelSortAlgorithm::sort(this, sortedItems
.begin(), sortedItems
.end());
907 #ifdef KFILEITEMMODEL_DEBUG
908 kDebug() << "[TIME] Sorting:" << timer
.elapsed();
911 KItemRangeList itemRanges
;
914 int insertedAtIndex
= -1; // Index for the current item-range
915 int insertedCount
= 0; // Count for the current item-range
916 int previouslyInsertedCount
= 0; // Sum of previously inserted items for all ranges
917 while (sourceIndex
< sortedItems
.count()) {
918 // Find target index from m_items to insert the current item
920 const int previousTargetIndex
= targetIndex
;
921 while (targetIndex
< m_itemData
.count()) {
922 if (!lessThan(m_itemData
.at(targetIndex
), sortedItems
.at(sourceIndex
))) {
928 if (targetIndex
- previousTargetIndex
> 0 && insertedAtIndex
>= 0) {
929 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
930 previouslyInsertedCount
+= insertedCount
;
931 insertedAtIndex
= targetIndex
- previouslyInsertedCount
;
935 // Insert item at the position targetIndex by transfering
936 // the ownership of the item-data from sortedItems to m_itemData.
937 // m_items will be inserted after the loop (see comment below)
938 m_itemData
.insert(targetIndex
, sortedItems
.at(sourceIndex
));
941 if (insertedAtIndex
< 0) {
942 insertedAtIndex
= targetIndex
;
943 Q_ASSERT(previouslyInsertedCount
== 0);
949 // The indexes of all m_items must be adjusted, not only the index
951 const int itemDataCount
= m_itemData
.count();
952 for (int i
= 0; i
< itemDataCount
; ++i
) {
953 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
956 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
957 emit
itemsInserted(itemRanges
);
959 #ifdef KFILEITEMMODEL_DEBUG
960 kDebug() << "[TIME] Inserting of" << items
.count() << "items:" << timer
.elapsed();
964 void KFileItemModel::removeItems(const KFileItemList
& items
)
966 if (items
.isEmpty()) {
970 #ifdef KFILEITEMMODEL_DEBUG
971 kDebug() << "Removing " << items
.count() << "items";
976 QList
<ItemData
*> sortedItems
;
977 sortedItems
.reserve(items
.count());
978 foreach (const KFileItem
& item
, items
) {
979 const int index
= m_items
.value(item
.url(), -1);
981 sortedItems
.append(m_itemData
.at(index
));
984 KFileItemModelSortAlgorithm::sort(this, sortedItems
.begin(), sortedItems
.end());
986 QList
<int> indexesToRemove
;
987 indexesToRemove
.reserve(items
.count());
989 // Calculate the item ranges that will get deleted
990 KItemRangeList itemRanges
;
991 int removedAtIndex
= -1;
992 int removedCount
= 0;
994 foreach (const ItemData
* itemData
, sortedItems
) {
995 const KFileItem
& itemToRemove
= itemData
->item
;
997 const int previousTargetIndex
= targetIndex
;
998 while (targetIndex
< m_itemData
.count()) {
999 if (m_itemData
.at(targetIndex
)->item
.url() == itemToRemove
.url()) {
1004 if (targetIndex
>= m_itemData
.count()) {
1005 kWarning() << "Item that should be deleted has not been found!";
1009 if (targetIndex
- previousTargetIndex
> 0 && removedAtIndex
>= 0) {
1010 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
1011 removedAtIndex
= targetIndex
;
1015 indexesToRemove
.append(targetIndex
);
1016 if (removedAtIndex
< 0) {
1017 removedAtIndex
= targetIndex
;
1024 for (int i
= indexesToRemove
.count() - 1; i
>= 0; --i
) {
1025 const int indexToRemove
= indexesToRemove
.at(i
);
1026 ItemData
* data
= m_itemData
.at(indexToRemove
);
1028 m_items
.remove(data
->item
.url());
1031 m_itemData
.removeAt(indexToRemove
);
1034 // The indexes of all m_items must be adjusted, not only the index
1035 // of the removed items
1036 const int itemDataCount
= m_itemData
.count();
1037 for (int i
= 0; i
< itemDataCount
; ++i
) {
1038 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
1042 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
1045 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
1046 emit
itemsRemoved(itemRanges
);
1049 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const KFileItemList
& items
) const
1051 QList
<ItemData
*> itemDataList
;
1052 itemDataList
.reserve(items
.count());
1054 foreach (const KFileItem
& item
, items
) {
1055 ItemData
* itemData
= new ItemData();
1056 itemData
->item
= item
;
1057 itemData
->values
= retrieveData(item
);
1058 itemData
->parent
= 0;
1060 const bool determineParent
= m_requestRole
[ExpandedParentsCountRole
]
1061 && itemData
->values
["expandedParentsCount"].toInt() > 0;
1062 if (determineParent
) {
1063 KUrl parentUrl
= item
.url().upUrl();
1064 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
1065 const int parentIndex
= m_items
.value(parentUrl
, -1);
1066 if (parentIndex
>= 0) {
1067 itemData
->parent
= m_itemData
.at(parentIndex
);
1069 kWarning() << "Parent item not found for" << item
.url();
1073 itemDataList
.append(itemData
);
1076 return itemDataList
;
1079 void KFileItemModel::removeExpandedItems()
1081 KFileItemList expandedItems
;
1083 const int maxIndex
= m_itemData
.count() - 1;
1084 for (int i
= 0; i
<= maxIndex
; ++i
) {
1085 const ItemData
* itemData
= m_itemData
.at(i
);
1086 if (itemData
->values
.value("expandedParentsCount").toInt() > 0) {
1087 expandedItems
.append(itemData
->item
);
1091 // The m_expandedParentsCountRoot may not get reset before all items with
1092 // a bigger count have been removed.
1093 removeItems(expandedItems
);
1095 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
1096 m_expandedDirs
.clear();
1099 void KFileItemModel::resetRoles()
1101 for (int i
= 0; i
< RolesCount
; ++i
) {
1102 m_requestRole
[i
] = false;
1106 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1108 static QHash
<QByteArray
, RoleType
> roles
;
1109 if (roles
.isEmpty()) {
1110 // Insert user visible roles that can be accessed with
1111 // KFileItemModel::roleInformation()
1113 const RoleInfoMap
* map
= rolesInfoMap(count
);
1114 for (int i
= 0; i
< count
; ++i
) {
1115 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1118 // Insert internal roles (take care to synchronize the implementation
1119 // with KFileItemModel::roleForType() in case if a change is done).
1120 roles
.insert("isDir", IsDirRole
);
1121 roles
.insert("isLink", IsLinkRole
);
1122 roles
.insert("isExpanded", IsExpandedRole
);
1123 roles
.insert("isExpandable", IsExpandableRole
);
1124 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1126 Q_ASSERT(roles
.count() == RolesCount
);
1129 return roles
.value(role
, NoRole
);
1132 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1134 static QHash
<RoleType
, QByteArray
> roles
;
1135 if (roles
.isEmpty()) {
1136 // Insert user visible roles that can be accessed with
1137 // KFileItemModel::roleInformation()
1139 const RoleInfoMap
* map
= rolesInfoMap(count
);
1140 for (int i
= 0; i
< count
; ++i
) {
1141 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1144 // Insert internal roles (take care to synchronize the implementation
1145 // with KFileItemModel::typeForRole() in case if a change is done).
1146 roles
.insert(IsDirRole
, "isDir");
1147 roles
.insert(IsLinkRole
, "isLink");
1148 roles
.insert(IsExpandedRole
, "isExpanded");
1149 roles
.insert(IsExpandableRole
, "isExpandable");
1150 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1152 Q_ASSERT(roles
.count() == RolesCount
);
1155 return roles
.value(roleType
);
1158 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
) const
1160 // It is important to insert only roles that are fast to retrieve. E.g.
1161 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1162 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1163 QHash
<QByteArray
, QVariant
> data
;
1164 data
.insert("url", item
.url());
1166 const bool isDir
= item
.isDir();
1167 if (m_requestRole
[IsDirRole
]) {
1168 data
.insert("isDir", isDir
);
1171 if (m_requestRole
[IsLinkRole
]) {
1172 const bool isLink
= item
.isLink();
1173 data
.insert("isLink", isLink
);
1176 if (m_requestRole
[NameRole
]) {
1177 data
.insert("text", item
.text());
1180 if (m_requestRole
[SizeRole
]) {
1182 data
.insert("size", QVariant());
1184 data
.insert("size", item
.size());
1188 if (m_requestRole
[DateRole
]) {
1189 // Don't use KFileItem::timeString() as this is too expensive when
1190 // having several thousands of items. Instead the formatting of the
1191 // date-time will be done on-demand by the view when the date will be shown.
1192 const KDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
1193 data
.insert("date", dateTime
.dateTime());
1196 if (m_requestRole
[PermissionsRole
]) {
1197 data
.insert("permissions", item
.permissionsString());
1200 if (m_requestRole
[OwnerRole
]) {
1201 data
.insert("owner", item
.user());
1204 if (m_requestRole
[GroupRole
]) {
1205 data
.insert("group", item
.group());
1208 if (m_requestRole
[DestinationRole
]) {
1209 QString destination
= item
.linkDest();
1210 if (destination
.isEmpty()) {
1211 destination
= QLatin1String("-");
1213 data
.insert("destination", destination
);
1216 if (m_requestRole
[PathRole
]) {
1218 if (item
.url().protocol() == QLatin1String("trash")) {
1219 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1221 // For performance reasons cache the home-path in a static QString
1222 // (see QDir::homePath() for more details)
1223 static QString homePath
;
1224 if (homePath
.isEmpty()) {
1225 homePath
= QDir::homePath();
1228 path
= item
.localPath();
1229 if (path
.startsWith(homePath
)) {
1230 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1234 const int index
= path
.lastIndexOf(item
.text());
1235 path
= path
.mid(0, index
- 1);
1236 data
.insert("path", path
);
1239 if (m_requestRole
[IsExpandedRole
]) {
1240 data
.insert("isExpanded", false);
1243 if (m_requestRole
[IsExpandableRole
]) {
1244 data
.insert("isExpandable", item
.isDir() && item
.url() == item
.targetUrl());
1247 if (m_requestRole
[ExpandedParentsCountRole
]) {
1248 if (m_expandedParentsCountRoot
== UninitializedExpandedParentsCountRoot
) {
1249 const KUrl rootUrl
= m_dirLister
->url();
1250 const QString protocol
= rootUrl
.protocol();
1251 const bool forceExpandedParentsCountRoot
= (protocol
== QLatin1String("trash") ||
1252 protocol
== QLatin1String("nepomuk") ||
1253 protocol
== QLatin1String("remote") ||
1254 protocol
.contains(QLatin1String("search")));
1255 if (forceExpandedParentsCountRoot
) {
1256 m_expandedParentsCountRoot
= ForceExpandedParentsCountRoot
;
1258 const QString rootDir
= rootUrl
.path(KUrl::AddTrailingSlash
);
1259 m_expandedParentsCountRoot
= rootDir
.count('/');
1263 if (m_expandedParentsCountRoot
== ForceExpandedParentsCountRoot
) {
1264 data
.insert("expandedParentsCount", -1);
1266 const QString dir
= item
.url().directory(KUrl::AppendTrailingSlash
);
1267 const int level
= dir
.count('/') - m_expandedParentsCountRoot
;
1268 data
.insert("expandedParentsCount", level
);
1272 if (item
.isMimeTypeKnown()) {
1273 data
.insert("iconName", item
.iconName());
1275 if (m_requestRole
[TypeRole
]) {
1276 data
.insert("type", item
.mimeComment());
1283 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
) const
1287 if (m_expandedParentsCountRoot
>= 0) {
1288 result
= expandedParentsCountCompare(a
, b
);
1290 // The items have parents with different expansion levels
1291 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1295 if (m_sortDirsFirst
|| m_sortRole
== SizeRole
) {
1296 const bool isDirA
= a
->item
.isDir();
1297 const bool isDirB
= b
->item
.isDir();
1298 if (isDirA
&& !isDirB
) {
1300 } else if (!isDirA
&& isDirB
) {
1305 result
= sortRoleCompare(a
, b
);
1307 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1310 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
) const
1312 const KFileItem
& itemA
= a
->item
;
1313 const KFileItem
& itemB
= b
->item
;
1317 switch (m_sortRole
) {
1319 // The name role is handled as default fallback after the switch
1323 if (itemA
.isDir()) {
1324 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1325 Q_ASSERT(itemB
.isDir());
1327 const QVariant valueA
= a
->values
.value("size");
1328 const QVariant valueB
= b
->values
.value("size");
1329 if (valueA
.isNull() && valueB
.isNull()) {
1331 } else if (valueA
.isNull()) {
1333 } else if (valueB
.isNull()) {
1336 result
= valueA
.toInt() - valueB
.toInt();
1339 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1340 Q_ASSERT(!itemB
.isDir());
1341 const KIO::filesize_t sizeA
= itemA
.size();
1342 const KIO::filesize_t sizeB
= itemB
.size();
1343 if (sizeA
> sizeB
) {
1345 } else if (sizeA
< sizeB
) {
1355 const KDateTime dateTimeA
= itemA
.time(KFileItem::ModificationTime
);
1356 const KDateTime dateTimeB
= itemB
.time(KFileItem::ModificationTime
);
1357 if (dateTimeA
< dateTimeB
) {
1359 } else if (dateTimeA
> dateTimeB
) {
1366 result
= a
->values
.value("rating").toInt() - b
->values
.value("rating").toInt();
1370 case ImageSizeRole
: {
1371 // Alway use a natural comparing to interpret the numbers of a string like
1372 // "1600 x 1200" for having a correct sorting.
1373 result
= KStringHandler::naturalCompare(a
->values
.value("imageSize").toString(),
1374 b
->values
.value("imageSize").toString(),
1380 const QByteArray role
= roleForType(m_sortRole
);
1381 result
= QString::compare(a
->values
.value(role
).toString(),
1382 b
->values
.value(role
).toString());
1389 // The current sort role was sufficient to define an order
1393 // Fallback #1: Compare the text of the items
1394 result
= stringCompare(itemA
.text(), itemB
.text());
1399 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1400 result
= stringCompare(itemA
.name(m_caseSensitivity
== Qt::CaseInsensitive
),
1401 itemB
.name(m_caseSensitivity
== Qt::CaseInsensitive
));
1406 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1407 // equal. In this case a comparison of the URL is done which is unique in all cases
1408 // within KDirLister.
1409 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1412 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
) const
1414 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1415 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1416 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1417 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1419 if (m_caseSensitivity
== Qt::CaseInsensitive
) {
1420 const int result
= m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseInsensitive
)
1421 : QString::compare(a
, b
, Qt::CaseInsensitive
);
1423 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1424 // comparison, still a deterministic sort order is required. A case sensitive
1425 // comparison is done as fallback.
1430 return m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseSensitive
)
1431 : QString::compare(a
, b
, Qt::CaseSensitive
);
1434 int KFileItemModel::expandedParentsCountCompare(const ItemData
* a
, const ItemData
* b
) const
1436 const KUrl urlA
= a
->item
.url();
1437 const KUrl urlB
= b
->item
.url();
1438 if (urlA
.directory() == urlB
.directory()) {
1439 // Both items have the same directory as parent
1443 // Check whether one item is the parent of the other item
1444 if (urlA
.isParentOf(urlB
)) {
1445 return (sortOrder() == Qt::AscendingOrder
) ? -1 : +1;
1446 } else if (urlB
.isParentOf(urlA
)) {
1447 return (sortOrder() == Qt::AscendingOrder
) ? +1 : -1;
1450 // Determine the maximum common path of both items and
1451 // remember the index in 'index'
1452 const QString pathA
= urlA
.path();
1453 const QString pathB
= urlB
.path();
1455 const int maxIndex
= qMin(pathA
.length(), pathB
.length()) - 1;
1457 while (index
<= maxIndex
&& pathA
.at(index
) == pathB
.at(index
)) {
1460 if (index
> maxIndex
) {
1463 while ((pathA
.at(index
) != QLatin1Char('/') || pathB
.at(index
) != QLatin1Char('/')) && index
> 0) {
1467 // Determine the first sub-path after the common path and
1468 // check whether it represents a directory or already a file
1470 const QString subPathA
= subPath(a
->item
, pathA
, index
, &isDirA
);
1472 const QString subPathB
= subPath(b
->item
, pathB
, index
, &isDirB
);
1474 if (m_sortDirsFirst
|| m_sortRole
== SizeRole
) {
1475 if (isDirA
&& !isDirB
) {
1476 return (sortOrder() == Qt::AscendingOrder
) ? -1 : +1;
1477 } else if (!isDirA
&& isDirB
) {
1478 return (sortOrder() == Qt::AscendingOrder
) ? +1 : -1;
1482 // Compare the items of the parents that represent the first
1483 // different path after the common path.
1484 const QString parentPathA
= pathA
.left(index
) + subPathA
;
1485 const QString parentPathB
= pathB
.left(index
) + subPathB
;
1487 const ItemData
* parentA
= a
;
1488 while (parentA
&& parentA
->item
.url().path() != parentPathA
) {
1489 parentA
= parentA
->parent
;
1492 const ItemData
* parentB
= b
;
1493 while (parentB
&& parentB
->item
.url().path() != parentPathB
) {
1494 parentB
= parentB
->parent
;
1497 if (parentA
&& parentB
) {
1498 return sortRoleCompare(parentA
, parentB
);
1501 kWarning() << "Child items without parent detected:" << a
->item
.url() << b
->item
.url();
1502 return QString::compare(urlA
.url(), urlB
.url(), Qt::CaseSensitive
);
1505 QString
KFileItemModel::subPath(const KFileItem
& item
,
1506 const QString
& itemPath
,
1511 const int pathIndex
= itemPath
.indexOf('/', start
+ 1);
1512 *isDir
= (pathIndex
> 0) || item
.isDir();
1513 return itemPath
.mid(start
, pathIndex
- start
);
1516 bool KFileItemModel::useMaximumUpdateInterval() const
1518 return !m_dirLister
->url().isLocalFile();
1521 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1523 Q_ASSERT(!m_itemData
.isEmpty());
1525 const int maxIndex
= count() - 1;
1526 QList
<QPair
<int, QVariant
> > groups
;
1530 bool isLetter
= false;
1531 for (int i
= 0; i
<= maxIndex
; ++i
) {
1532 if (isChildItem(i
)) {
1536 const QString name
= m_itemData
.at(i
)->values
.value("text").toString();
1538 // Use the first character of the name as group indication
1539 QChar newFirstChar
= name
.at(0).toUpper();
1540 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1541 newFirstChar
= name
.at(1).toUpper();
1544 if (firstChar
!= newFirstChar
) {
1545 QString newGroupValue
;
1546 if (newFirstChar
>= QLatin1Char('A') && newFirstChar
<= QLatin1Char('Z')) {
1547 // Apply group 'A' - 'Z'
1548 newGroupValue
= newFirstChar
;
1550 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
1551 // Apply group '0 - 9' for any name that starts with a digit
1552 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
1556 // If the current group is 'A' - 'Z' check whether a locale character
1557 // fits into the existing group.
1558 // TODO: This does not work in the case if e.g. the group 'O' starts with
1559 // an umlaut 'O' -> provide unit-test to document this known issue
1560 const QChar
prevChar(firstChar
.unicode() - ushort(1));
1561 const QChar
nextChar(firstChar
.unicode() + ushort(1));
1562 const QString
currChar(newFirstChar
);
1563 const bool partOfCurrentGroup
= currChar
.localeAwareCompare(prevChar
) > 0 &&
1564 currChar
.localeAwareCompare(nextChar
) < 0;
1565 if (partOfCurrentGroup
) {
1569 newGroupValue
= i18nc("@title:group", "Others");
1573 if (newGroupValue
!= groupValue
) {
1574 groupValue
= newGroupValue
;
1575 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1578 firstChar
= newFirstChar
;
1584 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
1586 Q_ASSERT(!m_itemData
.isEmpty());
1588 const int maxIndex
= count() - 1;
1589 QList
<QPair
<int, QVariant
> > groups
;
1592 for (int i
= 0; i
<= maxIndex
; ++i
) {
1593 if (isChildItem(i
)) {
1597 const KFileItem
& item
= m_itemData
.at(i
)->item
;
1598 const KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
1599 QString newGroupValue
;
1600 if (!item
.isNull() && item
.isDir()) {
1601 newGroupValue
= i18nc("@title:group Size", "Folders");
1602 } else if (fileSize
< 5 * 1024 * 1024) {
1603 newGroupValue
= i18nc("@title:group Size", "Small");
1604 } else if (fileSize
< 10 * 1024 * 1024) {
1605 newGroupValue
= i18nc("@title:group Size", "Medium");
1607 newGroupValue
= i18nc("@title:group Size", "Big");
1610 if (newGroupValue
!= groupValue
) {
1611 groupValue
= newGroupValue
;
1612 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1619 QList
<QPair
<int, QVariant
> > KFileItemModel::dateRoleGroups() const
1621 Q_ASSERT(!m_itemData
.isEmpty());
1623 const int maxIndex
= count() - 1;
1624 QList
<QPair
<int, QVariant
> > groups
;
1626 const QDate currentDate
= KDateTime::currentLocalDateTime().date();
1628 int yearForCurrentWeek
= 0;
1629 int currentWeek
= currentDate
.weekNumber(&yearForCurrentWeek
);
1630 if (yearForCurrentWeek
== currentDate
.year() + 1) {
1634 QDate previousModifiedDate
;
1636 for (int i
= 0; i
<= maxIndex
; ++i
) {
1637 if (isChildItem(i
)) {
1641 const KDateTime modifiedTime
= m_itemData
.at(i
)->item
.time(KFileItem::ModificationTime
);
1642 const QDate modifiedDate
= modifiedTime
.date();
1643 if (modifiedDate
== previousModifiedDate
) {
1644 // The current item is in the same group as the previous item
1647 previousModifiedDate
= modifiedDate
;
1649 const int daysDistance
= modifiedDate
.daysTo(currentDate
);
1651 int yearForModifiedWeek
= 0;
1652 int modifiedWeek
= modifiedDate
.weekNumber(&yearForModifiedWeek
);
1653 if (yearForModifiedWeek
== modifiedDate
.year() + 1) {
1657 QString newGroupValue
;
1658 if (currentDate
.year() == modifiedDate
.year() && currentDate
.month() == modifiedDate
.month()) {
1659 if (modifiedWeek
> currentWeek
) {
1660 // Usecase: modified date = 2010-01-01, current date = 2010-01-22
1661 // modified week = 53, current week = 3
1664 switch (currentWeek
- modifiedWeek
) {
1666 switch (daysDistance
) {
1667 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
1668 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
1669 default: newGroupValue
= modifiedTime
.toString(i18nc("@title:group The week day name: %A", "%A"));
1673 newGroupValue
= i18nc("@title:group Date", "Last Week");
1676 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
1679 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
1683 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
1689 const QDate lastMonthDate
= currentDate
.addMonths(-1);
1690 if (lastMonthDate
.year() == modifiedDate
.year() && lastMonthDate
.month() == modifiedDate
.month()) {
1691 if (daysDistance
== 1) {
1692 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Yesterday (%B, %Y)"));
1693 } else if (daysDistance
<= 7) {
1694 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)"));
1695 } else if (daysDistance
<= 7 * 2) {
1696 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)"));
1697 } else if (daysDistance
<= 7 * 3) {
1698 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)"));
1699 } else if (daysDistance
<= 7 * 4) {
1700 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)"));
1702 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"));
1705 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"));
1709 if (newGroupValue
!= groupValue
) {
1710 groupValue
= newGroupValue
;
1711 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1718 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
1720 Q_ASSERT(!m_itemData
.isEmpty());
1722 const int maxIndex
= count() - 1;
1723 QList
<QPair
<int, QVariant
> > groups
;
1725 QString permissionsString
;
1727 for (int i
= 0; i
<= maxIndex
; ++i
) {
1728 if (isChildItem(i
)) {
1732 const ItemData
* itemData
= m_itemData
.at(i
);
1733 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
1734 if (newPermissionsString
== permissionsString
) {
1737 permissionsString
= newPermissionsString
;
1739 const QFileInfo
info(itemData
->item
.url().pathOrUrl());
1743 if (info
.permission(QFile::ReadUser
)) {
1744 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1746 if (info
.permission(QFile::WriteUser
)) {
1747 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1749 if (info
.permission(QFile::ExeUser
)) {
1750 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1752 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
1756 if (info
.permission(QFile::ReadGroup
)) {
1757 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1759 if (info
.permission(QFile::WriteGroup
)) {
1760 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1762 if (info
.permission(QFile::ExeGroup
)) {
1763 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1765 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
1767 // Set others string
1769 if (info
.permission(QFile::ReadOther
)) {
1770 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1772 if (info
.permission(QFile::WriteOther
)) {
1773 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1775 if (info
.permission(QFile::ExeOther
)) {
1776 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1778 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
1780 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
1781 if (newGroupValue
!= groupValue
) {
1782 groupValue
= newGroupValue
;
1783 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1790 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
1792 Q_ASSERT(!m_itemData
.isEmpty());
1794 const int maxIndex
= count() - 1;
1795 QList
<QPair
<int, QVariant
> > groups
;
1797 int groupValue
= -1;
1798 for (int i
= 0; i
<= maxIndex
; ++i
) {
1799 if (isChildItem(i
)) {
1802 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
1803 if (newGroupValue
!= groupValue
) {
1804 groupValue
= newGroupValue
;
1805 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1812 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
1814 Q_ASSERT(!m_itemData
.isEmpty());
1816 const int maxIndex
= count() - 1;
1817 QList
<QPair
<int, QVariant
> > groups
;
1819 bool isFirstGroupValue
= true;
1821 for (int i
= 0; i
<= maxIndex
; ++i
) {
1822 if (isChildItem(i
)) {
1825 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
1826 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
1827 groupValue
= newGroupValue
;
1828 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1829 isFirstGroupValue
= false;
1836 KFileItemList
KFileItemModel::childItems(const KFileItem
& item
) const
1838 KFileItemList items
;
1840 int index
= m_items
.value(item
.url(), -1);
1842 const int parentLevel
= m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt();
1844 while (index
< m_itemData
.count() && m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt() > parentLevel
) {
1845 items
.append(m_itemData
.at(index
)->item
);
1853 void KFileItemModel::emitSortProgress(int resolvedCount
)
1855 // Be tolerant against a resolvedCount with a wrong range.
1856 // Although there should not be a case where KFileItemModelRolesUpdater
1857 // (= caller) provides a wrong range, it is important to emit
1858 // a useful progress information even if there is an unexpected
1859 // implementation issue.
1861 const int itemCount
= count();
1862 if (resolvedCount
>= itemCount
) {
1863 m_sortingProgressPercent
= -1;
1864 if (m_resortAllItemsTimer
->isActive()) {
1865 m_resortAllItemsTimer
->stop();
1869 emit
directorySortingProgress(100);
1870 } else if (itemCount
> 0) {
1871 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
1873 const int progress
= resolvedCount
* 100 / itemCount
;
1874 if (m_sortingProgressPercent
!= progress
) {
1875 m_sortingProgressPercent
= progress
;
1876 emit
directorySortingProgress(progress
);
1881 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
1883 static const RoleInfoMap rolesInfoMap
[] = {
1884 // | role | roleType | role translation | group translation | requires Nepomuk | requires indexer
1885 { 0, NoRole
, 0, 0, 0, 0, false, false },
1886 { "text", NameRole
, I18N_NOOP2_NOSTRIP("@label", "Name"), 0, 0, false, false },
1887 { "size", SizeRole
, I18N_NOOP2_NOSTRIP("@label", "Size"), 0, 0, false, false },
1888 { "date", DateRole
, I18N_NOOP2_NOSTRIP("@label", "Date"), 0, 0, false, false },
1889 { "type", TypeRole
, I18N_NOOP2_NOSTRIP("@label", "Type"), 0, 0, false, false },
1890 { "rating", RatingRole
, I18N_NOOP2_NOSTRIP("@label", "Rating"), 0, 0, true, false },
1891 { "tags", TagsRole
, I18N_NOOP2_NOSTRIP("@label", "Tags"), 0, 0, true, false },
1892 { "comment", CommentRole
, I18N_NOOP2_NOSTRIP("@label", "Comment"), 0, 0, true, false },
1893 { "wordCount", WordCountRole
, I18N_NOOP2_NOSTRIP("@label", "Word Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
1894 { "lineCount", LineCountRole
, I18N_NOOP2_NOSTRIP("@label", "Line Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
1895 { "imageSize", ImageSizeRole
, I18N_NOOP2_NOSTRIP("@label", "Image Size"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
1896 { "orientation", OrientationRole
, I18N_NOOP2_NOSTRIP("@label", "Orientation"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
1897 { "artist", ArtistRole
, I18N_NOOP2_NOSTRIP("@label", "Artist"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1898 { "album", AlbumRole
, I18N_NOOP2_NOSTRIP("@label", "Album"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1899 { "duration", DurationRole
, I18N_NOOP2_NOSTRIP("@label", "Duration"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1900 { "track", TrackRole
, I18N_NOOP2_NOSTRIP("@label", "Track"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1901 { "path", PathRole
, I18N_NOOP2_NOSTRIP("@label", "Path"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1902 { "destination", DestinationRole
, I18N_NOOP2_NOSTRIP("@label", "Link Destination"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1903 { "copiedFrom", CopiedFromRole
, I18N_NOOP2_NOSTRIP("@label", "Copied From"), I18N_NOOP2_NOSTRIP("@label", "Other"), true, false },
1904 { "permissions", PermissionsRole
, I18N_NOOP2_NOSTRIP("@label", "Permissions"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1905 { "owner", OwnerRole
, I18N_NOOP2_NOSTRIP("@label", "Owner"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1906 { "group", GroupRole
, I18N_NOOP2_NOSTRIP("@label", "User Group"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1909 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
1910 return rolesInfoMap
;
1913 void KFileItemModel::determineMimeTypes(const KFileItemList
& items
, int timeout
)
1915 QElapsedTimer timer
;
1917 foreach (KFileItem item
, items
) {
1918 item
.determineMimeType();
1919 if (timer
.elapsed() > timeout
) {
1920 // Don't block the user interface, let the remaining items
1921 // be resolved asynchronously.
1927 #include "kfileitemmodel.moc"