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>
36 // #define KFILEITEMMODEL_DEBUG
38 KFileItemModel::KFileItemModel(QObject
* parent
) :
39 KItemModelBase("text", parent
),
41 m_naturalSorting(KGlobalSettings::naturalSorting()),
42 m_sortDirsFirst(true),
44 m_sortingProgressPercent(-1),
46 m_caseSensitivity(Qt::CaseInsensitive
),
52 m_maximumUpdateIntervalTimer(0),
53 m_resortAllItemsTimer(0),
54 m_pendingItemsToInsert(),
56 m_expandedParentsCountRoot(UninitializedExpandedParentsCountRoot
),
60 m_dirLister
= new KFileItemModelDirLister(this);
61 m_dirLister
->setDelayedMimeTypes(true);
63 const QWidget
* parentWidget
= qobject_cast
<QWidget
*>(parent
);
65 m_dirLister
->setMainWindow(parentWidget
->window());
68 connect(m_dirLister
, SIGNAL(started(KUrl
)), this, SIGNAL(directoryLoadingStarted()));
69 connect(m_dirLister
, SIGNAL(canceled()), this, SLOT(slotCanceled()));
70 connect(m_dirLister
, SIGNAL(completed(KUrl
)), this, SLOT(slotCompleted()));
71 connect(m_dirLister
, SIGNAL(newItems(KFileItemList
)), this, SLOT(slotNewItems(KFileItemList
)));
72 connect(m_dirLister
, SIGNAL(itemsDeleted(KFileItemList
)), this, SLOT(slotItemsDeleted(KFileItemList
)));
73 connect(m_dirLister
, SIGNAL(refreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)), this, SLOT(slotRefreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)));
74 connect(m_dirLister
, SIGNAL(clear()), this, SLOT(slotClear()));
75 connect(m_dirLister
, SIGNAL(clear(KUrl
)), this, SLOT(slotClear(KUrl
)));
76 connect(m_dirLister
, SIGNAL(infoMessage(QString
)), this, SIGNAL(infoMessage(QString
)));
77 connect(m_dirLister
, SIGNAL(errorMessage(QString
)), this, SIGNAL(errorMessage(QString
)));
78 connect(m_dirLister
, SIGNAL(redirection(KUrl
,KUrl
)), this, SIGNAL(directoryRedirection(KUrl
,KUrl
)));
79 connect(m_dirLister
, SIGNAL(urlIsFileError(KUrl
)), this, SIGNAL(urlIsFileError(KUrl
)));
81 // Apply default roles that should be determined
83 m_requestRole
[NameRole
] = true;
84 m_requestRole
[IsDirRole
] = true;
85 m_requestRole
[IsLinkRole
] = true;
86 m_roles
.insert("text");
87 m_roles
.insert("isDir");
88 m_roles
.insert("isLink");
90 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
91 // before the completed() or canceled() signal has been emitted.
92 m_maximumUpdateIntervalTimer
= new QTimer(this);
93 m_maximumUpdateIntervalTimer
->setInterval(2000);
94 m_maximumUpdateIntervalTimer
->setSingleShot(true);
95 connect(m_maximumUpdateIntervalTimer
, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
97 // When changing the value of an item which represents the sort-role a resorting must be
98 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
99 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
100 // resorting is postponed until the timer has been exceeded.
101 m_resortAllItemsTimer
= new QTimer(this);
102 m_resortAllItemsTimer
->setInterval(500);
103 m_resortAllItemsTimer
->setSingleShot(true);
104 connect(m_resortAllItemsTimer
, SIGNAL(timeout()), this, SLOT(resortAllItems()));
106 connect(KGlobalSettings::self(), SIGNAL(naturalSortingChanged()), this, SLOT(slotNaturalSortingChanged()));
109 KFileItemModel::~KFileItemModel()
111 qDeleteAll(m_itemData
);
115 void KFileItemModel::loadDirectory(const KUrl
& url
)
117 m_dirLister
->openUrl(url
);
120 void KFileItemModel::refreshDirectory(const KUrl
& url
)
122 m_dirLister
->openUrl(url
, KDirLister::Reload
);
125 KUrl
KFileItemModel::directory() const
127 return m_dirLister
->url();
130 void KFileItemModel::cancelDirectoryLoading()
135 int KFileItemModel::count() const
137 return m_itemData
.count();
140 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
142 if (index
>= 0 && index
< count()) {
143 return m_itemData
.at(index
)->values
;
145 return QHash
<QByteArray
, QVariant
>();
148 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
150 if (index
< 0 || index
>= count()) {
154 QHash
<QByteArray
, QVariant
> currentValues
= m_itemData
.at(index
)->values
;
156 // Determine which roles have been changed
157 QSet
<QByteArray
> changedRoles
;
158 QHashIterator
<QByteArray
, QVariant
> it(values
);
159 while (it
.hasNext()) {
161 const QByteArray role
= it
.key();
162 const QVariant value
= it
.value();
164 if (currentValues
[role
] != value
) {
165 currentValues
[role
] = value
;
166 changedRoles
.insert(role
);
170 if (changedRoles
.isEmpty()) {
174 m_itemData
[index
]->values
= currentValues
;
175 if (changedRoles
.contains("text")) {
176 KUrl url
= m_itemData
[index
]->item
.url();
177 url
.setFileName(currentValues
["text"].toString());
178 m_itemData
[index
]->item
.setUrl(url
);
181 emit
itemsChanged(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
183 if (changedRoles
.contains(sortRole())) {
184 m_resortAllItemsTimer
->start();
190 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
192 if (dirsFirst
!= m_sortDirsFirst
) {
193 m_sortDirsFirst
= dirsFirst
;
198 bool KFileItemModel::sortDirectoriesFirst() const
200 return m_sortDirsFirst
;
203 void KFileItemModel::setShowHiddenFiles(bool show
)
205 m_dirLister
->setShowingDotFiles(show
);
206 m_dirLister
->emitChanges();
212 bool KFileItemModel::showHiddenFiles() const
214 return m_dirLister
->showingDotFiles();
217 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
219 m_dirLister
->setDirOnlyMode(enabled
);
222 bool KFileItemModel::showDirectoriesOnly() const
224 return m_dirLister
->dirOnlyMode();
227 QMimeData
* KFileItemModel::createMimeData(const QSet
<int>& indexes
) const
229 QMimeData
* data
= new QMimeData();
231 // The following code has been taken from KDirModel::mimeData()
232 // (kdelibs/kio/kio/kdirmodel.cpp)
233 // Copyright (C) 2006 David Faure <faure@kde.org>
235 KUrl::List mostLocalUrls
;
236 bool canUseMostLocalUrls
= true;
238 QSetIterator
<int> it(indexes
);
239 while (it
.hasNext()) {
240 const int index
= it
.next();
241 const KFileItem item
= fileItem(index
);
242 if (!item
.isNull()) {
246 mostLocalUrls
<< item
.mostLocalUrl(isLocal
);
248 canUseMostLocalUrls
= false;
253 const bool different
= canUseMostLocalUrls
&& mostLocalUrls
!= urls
;
254 urls
= KDirModel::simplifiedUrlList(urls
); // TODO: Check if we still need KDirModel for this in KDE 5.0
256 mostLocalUrls
= KDirModel::simplifiedUrlList(mostLocalUrls
);
257 urls
.populateMimeData(mostLocalUrls
, data
);
259 urls
.populateMimeData(data
);
265 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
267 startFromIndex
= qMax(0, startFromIndex
);
268 for (int i
= startFromIndex
; i
< count(); ++i
) {
269 if (data(i
)["text"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
273 for (int i
= 0; i
< startFromIndex
; ++i
) {
274 if (data(i
)["text"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
281 bool KFileItemModel::supportsDropping(int index
) const
283 const KFileItem item
= fileItem(index
);
284 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
287 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
289 static QHash
<QByteArray
, QString
> description
;
290 if (description
.isEmpty()) {
292 const RoleInfoMap
* map
= rolesInfoMap(count
);
293 for (int i
= 0; i
< count
; ++i
) {
294 description
.insert(map
[i
].role
, i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
));
298 return description
.value(role
);
301 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
303 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
304 #ifdef KFILEITEMMODEL_DEBUG
308 switch (typeForRole(sortRole())) {
309 case NameRole
: m_groups
= nameRoleGroups(); break;
310 case SizeRole
: m_groups
= sizeRoleGroups(); break;
311 case DateRole
: m_groups
= dateRoleGroups(); break;
312 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
313 case RatingRole
: m_groups
= ratingRoleGroups(); break;
314 default: m_groups
= genericStringRoleGroups(sortRole()); break;
317 #ifdef KFILEITEMMODEL_DEBUG
318 kDebug() << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
325 KFileItem
KFileItemModel::fileItem(int index
) const
327 if (index
>= 0 && index
< count()) {
328 return m_itemData
.at(index
)->item
;
334 KFileItem
KFileItemModel::fileItem(const KUrl
& url
) const
336 const int index
= m_items
.value(url
, -1);
338 return m_itemData
.at(index
)->item
;
343 int KFileItemModel::index(const KFileItem
& item
) const
349 return m_items
.value(item
.url(), -1);
352 int KFileItemModel::index(const KUrl
& url
) const
354 KUrl urlToFind
= url
;
355 urlToFind
.adjustPath(KUrl::RemoveTrailingSlash
);
356 return m_items
.value(urlToFind
, -1);
359 KFileItem
KFileItemModel::rootItem() const
361 return m_dirLister
->rootItem();
364 void KFileItemModel::clear()
369 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
371 if (m_roles
== roles
) {
377 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
378 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
379 if (supportedExpanding
&& !willSupportExpanding
) {
380 // No expanding is supported anymore. Take care to delete all items that have an expansion level
381 // that is not 0 (and hence are part of an expanded item).
382 removeExpandedItems();
389 QSetIterator
<QByteArray
> it(roles
);
390 while (it
.hasNext()) {
391 const QByteArray
& role
= it
.next();
392 m_requestRole
[typeForRole(role
)] = true;
396 // Update m_data with the changed requested roles
397 const int maxIndex
= count() - 1;
398 for (int i
= 0; i
<= maxIndex
; ++i
) {
399 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
);
402 kWarning() << "TODO: Emitting itemsChanged() with no information what has changed!";
403 emit
itemsChanged(KItemRangeList() << KItemRange(0, count()), QSet
<QByteArray
>());
407 QSet
<QByteArray
> KFileItemModel::roles() const
412 bool KFileItemModel::setExpanded(int index
, bool expanded
)
414 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
418 QHash
<QByteArray
, QVariant
> values
;
419 values
.insert("isExpanded", expanded
);
420 if (!setData(index
, values
)) {
424 const KUrl url
= m_itemData
.at(index
)->item
.url();
426 m_expandedDirs
.insert(url
);
427 m_dirLister
->openUrl(url
, KDirLister::Keep
);
429 m_expandedDirs
.remove(url
);
430 m_dirLister
->stop(url
);
433 KFileItemList itemsToRemove
;
434 const int expandedParentsCount
= data(index
)["expandedParentsCount"].toInt();
436 while (index
< count() && data(index
)["expandedParentsCount"].toInt() > expandedParentsCount
) {
437 itemsToRemove
.append(m_itemData
.at(index
)->item
);
440 removeItems(itemsToRemove
);
446 bool KFileItemModel::isExpanded(int index
) const
448 if (index
>= 0 && index
< count()) {
449 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
454 bool KFileItemModel::isExpandable(int index
) const
456 if (index
>= 0 && index
< count()) {
457 return m_itemData
.at(index
)->values
.value("isExpandable").toBool();
462 int KFileItemModel::expandedParentsCount(int index
) const
464 if (index
>= 0 && index
< count()) {
465 const int parentsCount
= m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt();
466 if (parentsCount
> 0) {
473 QSet
<KUrl
> KFileItemModel::expandedDirectories() const
475 return m_expandedDirs
;
478 void KFileItemModel::restoreExpandedDirectories(const QSet
<KUrl
>& urls
)
480 m_urlsToExpand
= urls
;
483 void KFileItemModel::expandParentDirectories(const KUrl
& url
)
485 const int pos
= m_dirLister
->url().path().length();
487 // Assure that each sub-path of the URL that should be
488 // expanded is added to m_urlsToExpand. KDirLister
489 // does not care whether the parent-URL has already been
491 KUrl urlToExpand
= m_dirLister
->url();
492 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator());
493 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
494 urlToExpand
.addPath(subDirs
.at(i
));
495 m_urlsToExpand
.insert(urlToExpand
);
498 // KDirLister::open() must called at least once to trigger an initial
499 // loading. The pending URLs that must be restored are handled
500 // in slotCompleted().
501 QSetIterator
<KUrl
> it2(m_urlsToExpand
);
502 while (it2
.hasNext()) {
503 const int idx
= index(it2
.next());
504 if (idx
>= 0 && !isExpanded(idx
)) {
505 setExpanded(idx
, true);
511 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
513 if (m_filter
.pattern() != nameFilter
) {
514 dispatchPendingItemsToInsert();
515 m_filter
.setPattern(nameFilter
);
520 QString
KFileItemModel::nameFilter() const
522 return m_filter
.pattern();
525 void KFileItemModel::setMimeTypeFilters(const QStringList
& filters
)
527 if (m_filter
.mimeTypes() != filters
) {
528 dispatchPendingItemsToInsert();
529 m_filter
.setMimeTypes(filters
);
534 QStringList
KFileItemModel::mimeTypeFilters() const
536 return m_filter
.mimeTypes();
540 void KFileItemModel::applyFilters()
542 // Check which shown items from m_itemData must get
543 // hidden and hence moved to m_filteredItems.
544 KFileItemList newFilteredItems
;
546 foreach (ItemData
* itemData
, m_itemData
) {
547 // Only filter non-expanded items as child items may never
548 // exist without a parent item
549 if (!itemData
->values
.value("isExpanded").toBool()) {
550 if (!m_filter
.matches(itemData
->item
)) {
551 newFilteredItems
.append(itemData
->item
);
552 m_filteredItems
.insert(itemData
->item
);
557 removeItems(newFilteredItems
);
559 // Check which hidden items from m_filteredItems should
560 // get visible again and hence removed from m_filteredItems.
561 KFileItemList newVisibleItems
;
563 QMutableSetIterator
<KFileItem
> it(m_filteredItems
);
564 while (it
.hasNext()) {
565 const KFileItem item
= it
.next();
566 if (m_filter
.matches(item
)) {
567 newVisibleItems
.append(item
);
572 insertItems(newVisibleItems
);
575 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
577 static QList
<RoleInfo
> rolesInfo
;
578 if (rolesInfo
.isEmpty()) {
580 const RoleInfoMap
* map
= rolesInfoMap(count
);
581 for (int i
= 0; i
< count
; ++i
) {
582 if (map
[i
].roleType
!= NoRole
) {
584 info
.role
= map
[i
].role
;
585 info
.translation
= i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
);
586 if (map
[i
].groupTranslation
) {
587 info
.group
= i18nc(map
[i
].groupTranslationContext
, map
[i
].groupTranslation
);
589 // For top level roles, groupTranslation is 0. We must make sure that
590 // info.group is an empty string then because the code that generates
591 // menus tries to put the actions into sub menus otherwise.
592 info
.group
= QString();
594 info
.requiresNepomuk
= map
[i
].requiresNepomuk
;
595 info
.requiresIndexer
= map
[i
].requiresIndexer
;
596 rolesInfo
.append(info
);
604 void KFileItemModel::onGroupedSortingChanged(bool current
)
610 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
613 m_sortRole
= typeForRole(current
);
615 #ifdef KFILEITEMMODEL_DEBUG
616 if (!m_requestRole
[m_sortRole
]) {
617 kWarning() << "The sort-role has been changed to a role that has not been received yet";
624 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
631 void KFileItemModel::resortAllItems()
633 m_resortAllItemsTimer
->stop();
635 const int itemCount
= count();
636 if (itemCount
<= 0) {
640 #ifdef KFILEITEMMODEL_DEBUG
643 kDebug() << "===========================================================";
644 kDebug() << "Resorting" << itemCount
<< "items";
647 // Remember the order of the current URLs so
648 // that it can be determined which indexes have
649 // been moved because of the resorting.
651 oldUrls
.reserve(itemCount
);
652 foreach (const ItemData
* itemData
, m_itemData
) {
653 oldUrls
.append(itemData
->item
.url());
660 sort(m_itemData
.begin(), m_itemData
.end());
661 for (int i
= 0; i
< itemCount
; ++i
) {
662 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
665 // Determine the indexes that have been moved
666 QList
<int> movedToIndexes
;
667 movedToIndexes
.reserve(itemCount
);
668 for (int i
= 0; i
< itemCount
; i
++) {
669 const int newIndex
= m_items
.value(oldUrls
.at(i
).url());
670 movedToIndexes
.append(newIndex
);
673 // Don't check whether items have really been moved and always emit a
674 // itemsMoved() signal after resorting: In case of grouped items
675 // the groups might change even if the items themselves don't change their
676 // position. Let the receiver of the signal decide whether a check for moved
677 // items makes sense.
678 emit
itemsMoved(KItemRange(0, itemCount
), movedToIndexes
);
680 #ifdef KFILEITEMMODEL_DEBUG
681 kDebug() << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
685 void KFileItemModel::slotCompleted()
687 dispatchPendingItemsToInsert();
689 if (!m_urlsToExpand
.isEmpty()) {
690 // Try to find a URL that can be expanded.
691 // Note that the parent folder must be expanded before any of its subfolders become visible.
692 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
693 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
694 foreach (const KUrl
& url
, m_urlsToExpand
) {
695 const int index
= m_items
.value(url
, -1);
697 m_urlsToExpand
.remove(url
);
698 if (setExpanded(index
, true)) {
699 // The dir lister has been triggered. This slot will be called
700 // again after the directory has been expanded.
706 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
707 // if these URLs have been deleted in the meantime.
708 m_urlsToExpand
.clear();
711 emit
directoryLoadingCompleted();
714 void KFileItemModel::slotCanceled()
716 m_maximumUpdateIntervalTimer
->stop();
717 dispatchPendingItemsToInsert();
719 emit
directoryLoadingCanceled();
722 void KFileItemModel::slotNewItems(const KFileItemList
& items
)
724 Q_ASSERT(!items
.isEmpty());
726 if (m_requestRole
[ExpandedParentsCountRole
] && m_expandedParentsCountRoot
>= 0) {
727 // To be able to compare whether the new items may be inserted as children
728 // of a parent item the pending items must be added to the model first.
729 dispatchPendingItemsToInsert();
731 KFileItem item
= items
.first();
733 // If the expanding of items is enabled, the call
734 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
735 // might result in emitting the same items twice due to the Keep-parameter.
736 // This case happens if an item gets expanded, collapsed and expanded again
737 // before the items could be loaded for the first expansion.
738 const int index
= m_items
.value(item
.url(), -1);
740 // The items are already part of the model.
744 // KDirLister keeps the children of items that got expanded once even if
745 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
746 // checked whether the parent for new items is still expanded.
747 KUrl parentUrl
= item
.url().upUrl();
748 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
749 const int parentIndex
= m_items
.value(parentUrl
, -1);
750 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
751 // The parent is not expanded.
756 if (!m_filter
.hasSetFilters()) {
757 m_pendingItemsToInsert
.append(items
);
759 // The name or type filter is active. Hide filtered items
760 // before inserting them into the model and remember
761 // the filtered items in m_filteredItems.
762 KFileItemList filteredItems
;
763 foreach (const KFileItem
& item
, items
) {
764 if (m_filter
.matches(item
)) {
765 filteredItems
.append(item
);
767 m_filteredItems
.insert(item
);
771 m_pendingItemsToInsert
.append(filteredItems
);
774 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer
->isActive()) {
775 // Assure that items get dispatched if no completed() or canceled() signal is
776 // emitted during the maximum update interval.
777 m_maximumUpdateIntervalTimer
->start();
781 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
783 dispatchPendingItemsToInsert();
785 KFileItemList itemsToRemove
= items
;
786 if (m_requestRole
[ExpandedParentsCountRole
] && m_expandedParentsCountRoot
>= 0) {
787 // Assure that removing a parent item also results in removing all children
788 foreach (const KFileItem
& item
, items
) {
789 itemsToRemove
.append(childItems(item
));
793 if (!m_filteredItems
.isEmpty()) {
794 foreach (const KFileItem
& item
, itemsToRemove
) {
795 m_filteredItems
.remove(item
);
799 removeItems(itemsToRemove
);
802 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
804 Q_ASSERT(!items
.isEmpty());
805 #ifdef KFILEITEMMODEL_DEBUG
806 kDebug() << "Refreshing" << items
.count() << "items";
811 // Get the indexes of all items that have been refreshed
813 indexes
.reserve(items
.count());
815 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
816 while (it
.hasNext()) {
817 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
818 const KFileItem
& oldItem
= itemPair
.first
;
819 const KFileItem
& newItem
= itemPair
.second
;
820 const int index
= m_items
.value(oldItem
.url(), -1);
822 m_itemData
[index
]->item
= newItem
;
824 // Keep old values as long as possible if they could not retrieved synchronously yet.
825 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
826 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
));
827 while (it
.hasNext()) {
829 m_itemData
[index
]->values
.insert(it
.key(), it
.value());
832 m_items
.remove(oldItem
.url());
833 m_items
.insert(newItem
.url(), index
);
834 indexes
.append(index
);
838 // If the changed items have been created recently, they might not be in m_items yet.
839 // In that case, the list 'indexes' might be empty.
840 if (indexes
.isEmpty()) {
844 // Extract the item-ranges out of the changed indexes
847 KItemRangeList itemRangeList
;
848 int previousIndex
= indexes
.at(0);
849 int rangeIndex
= previousIndex
;
852 const int maxIndex
= indexes
.count() - 1;
853 for (int i
= 1; i
<= maxIndex
; ++i
) {
854 const int currentIndex
= indexes
.at(i
);
855 if (currentIndex
== previousIndex
+ 1) {
858 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
860 rangeIndex
= currentIndex
;
863 previousIndex
= currentIndex
;
866 if (rangeCount
> 0) {
867 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
870 emit
itemsChanged(itemRangeList
, m_roles
);
875 void KFileItemModel::slotClear()
877 #ifdef KFILEITEMMODEL_DEBUG
878 kDebug() << "Clearing all items";
881 m_filteredItems
.clear();
884 m_maximumUpdateIntervalTimer
->stop();
885 m_resortAllItemsTimer
->stop();
886 m_pendingItemsToInsert
.clear();
888 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
890 const int removedCount
= m_itemData
.count();
891 if (removedCount
> 0) {
892 qDeleteAll(m_itemData
);
895 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
898 m_expandedDirs
.clear();
901 void KFileItemModel::slotClear(const KUrl
& url
)
906 void KFileItemModel::slotNaturalSortingChanged()
908 m_naturalSorting
= KGlobalSettings::naturalSorting();
912 void KFileItemModel::dispatchPendingItemsToInsert()
914 if (!m_pendingItemsToInsert
.isEmpty()) {
915 insertItems(m_pendingItemsToInsert
);
916 m_pendingItemsToInsert
.clear();
920 void KFileItemModel::insertItems(const KFileItemList
& items
)
922 if (items
.isEmpty()) {
926 if (m_sortRole
== TypeRole
) {
927 // Try to resolve the MIME-types synchronously to prevent a reordering of
928 // the items when sorting by type (per default MIME-types are resolved
929 // asynchronously by KFileItemModelRolesUpdater).
930 determineMimeTypes(items
, 200);
933 #ifdef KFILEITEMMODEL_DEBUG
936 kDebug() << "===========================================================";
937 kDebug() << "Inserting" << items
.count() << "items";
942 QList
<ItemData
*> sortedItems
= createItemDataList(items
);
943 sort(sortedItems
.begin(), sortedItems
.end());
945 #ifdef KFILEITEMMODEL_DEBUG
946 kDebug() << "[TIME] Sorting:" << timer
.elapsed();
949 KItemRangeList itemRanges
;
952 int insertedAtIndex
= -1; // Index for the current item-range
953 int insertedCount
= 0; // Count for the current item-range
954 int previouslyInsertedCount
= 0; // Sum of previously inserted items for all ranges
955 while (sourceIndex
< sortedItems
.count()) {
956 // Find target index from m_items to insert the current item
958 const int previousTargetIndex
= targetIndex
;
959 while (targetIndex
< m_itemData
.count()) {
960 if (!lessThan(m_itemData
.at(targetIndex
), sortedItems
.at(sourceIndex
))) {
966 if (targetIndex
- previousTargetIndex
> 0 && insertedAtIndex
>= 0) {
967 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
968 previouslyInsertedCount
+= insertedCount
;
969 insertedAtIndex
= targetIndex
- previouslyInsertedCount
;
973 // Insert item at the position targetIndex by transferring
974 // the ownership of the item-data from sortedItems to m_itemData.
975 // m_items will be inserted after the loop (see comment below)
976 m_itemData
.insert(targetIndex
, sortedItems
.at(sourceIndex
));
979 if (insertedAtIndex
< 0) {
980 insertedAtIndex
= targetIndex
;
981 Q_ASSERT(previouslyInsertedCount
== 0);
987 // The indexes of all m_items must be adjusted, not only the index
989 const int itemDataCount
= m_itemData
.count();
990 for (int i
= 0; i
< itemDataCount
; ++i
) {
991 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
994 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
995 emit
itemsInserted(itemRanges
);
997 #ifdef KFILEITEMMODEL_DEBUG
998 kDebug() << "[TIME] Inserting of" << items
.count() << "items:" << timer
.elapsed();
1002 void KFileItemModel::removeItems(const KFileItemList
& items
)
1004 if (items
.isEmpty()) {
1008 #ifdef KFILEITEMMODEL_DEBUG
1009 kDebug() << "Removing " << items
.count() << "items";
1014 QList
<ItemData
*> sortedItems
;
1015 sortedItems
.reserve(items
.count());
1016 foreach (const KFileItem
& item
, items
) {
1017 const int index
= m_items
.value(item
.url(), -1);
1019 sortedItems
.append(m_itemData
.at(index
));
1022 sort(sortedItems
.begin(), sortedItems
.end());
1024 QList
<int> indexesToRemove
;
1025 indexesToRemove
.reserve(items
.count());
1027 // Calculate the item ranges that will get deleted
1028 KItemRangeList itemRanges
;
1029 int removedAtIndex
= -1;
1030 int removedCount
= 0;
1031 int targetIndex
= 0;
1032 foreach (const ItemData
* itemData
, sortedItems
) {
1033 const KFileItem
& itemToRemove
= itemData
->item
;
1035 const int previousTargetIndex
= targetIndex
;
1036 while (targetIndex
< m_itemData
.count()) {
1037 if (m_itemData
.at(targetIndex
)->item
.url() == itemToRemove
.url()) {
1042 if (targetIndex
>= m_itemData
.count()) {
1043 kWarning() << "Item that should be deleted has not been found!";
1047 if (targetIndex
- previousTargetIndex
> 0 && removedAtIndex
>= 0) {
1048 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
1049 removedAtIndex
= targetIndex
;
1053 indexesToRemove
.append(targetIndex
);
1054 if (removedAtIndex
< 0) {
1055 removedAtIndex
= targetIndex
;
1062 for (int i
= indexesToRemove
.count() - 1; i
>= 0; --i
) {
1063 const int indexToRemove
= indexesToRemove
.at(i
);
1064 ItemData
* data
= m_itemData
.at(indexToRemove
);
1066 m_items
.remove(data
->item
.url());
1069 m_itemData
.removeAt(indexToRemove
);
1072 // The indexes of all m_items must be adjusted, not only the index
1073 // of the removed items
1074 const int itemDataCount
= m_itemData
.count();
1075 for (int i
= 0; i
< itemDataCount
; ++i
) {
1076 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
1080 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
1083 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
1084 emit
itemsRemoved(itemRanges
);
1087 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const KFileItemList
& items
) const
1089 QList
<ItemData
*> itemDataList
;
1090 itemDataList
.reserve(items
.count());
1092 foreach (const KFileItem
& item
, items
) {
1093 ItemData
* itemData
= new ItemData();
1094 itemData
->item
= item
;
1095 itemData
->values
= retrieveData(item
);
1096 itemData
->parent
= 0;
1098 const bool determineParent
= m_requestRole
[ExpandedParentsCountRole
]
1099 && itemData
->values
["expandedParentsCount"].toInt() > 0;
1100 if (determineParent
) {
1101 KUrl parentUrl
= item
.url().upUrl();
1102 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
1103 const int parentIndex
= m_items
.value(parentUrl
, -1);
1104 if (parentIndex
>= 0) {
1105 itemData
->parent
= m_itemData
.at(parentIndex
);
1107 kWarning() << "Parent item not found for" << item
.url();
1111 itemDataList
.append(itemData
);
1114 return itemDataList
;
1117 void KFileItemModel::removeExpandedItems()
1119 KFileItemList expandedItems
;
1121 const int maxIndex
= m_itemData
.count() - 1;
1122 for (int i
= 0; i
<= maxIndex
; ++i
) {
1123 const ItemData
* itemData
= m_itemData
.at(i
);
1124 if (itemData
->values
.value("expandedParentsCount").toInt() > 0) {
1125 expandedItems
.append(itemData
->item
);
1129 // The m_expandedParentsCountRoot may not get reset before all items with
1130 // a bigger count have been removed.
1131 removeItems(expandedItems
);
1133 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
1134 m_expandedDirs
.clear();
1137 void KFileItemModel::resetRoles()
1139 for (int i
= 0; i
< RolesCount
; ++i
) {
1140 m_requestRole
[i
] = false;
1144 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1146 static QHash
<QByteArray
, RoleType
> roles
;
1147 if (roles
.isEmpty()) {
1148 // Insert user visible roles that can be accessed with
1149 // KFileItemModel::roleInformation()
1151 const RoleInfoMap
* map
= rolesInfoMap(count
);
1152 for (int i
= 0; i
< count
; ++i
) {
1153 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1156 // Insert internal roles (take care to synchronize the implementation
1157 // with KFileItemModel::roleForType() in case if a change is done).
1158 roles
.insert("isDir", IsDirRole
);
1159 roles
.insert("isLink", IsLinkRole
);
1160 roles
.insert("isExpanded", IsExpandedRole
);
1161 roles
.insert("isExpandable", IsExpandableRole
);
1162 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1164 Q_ASSERT(roles
.count() == RolesCount
);
1167 return roles
.value(role
, NoRole
);
1170 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1172 static QHash
<RoleType
, QByteArray
> roles
;
1173 if (roles
.isEmpty()) {
1174 // Insert user visible roles that can be accessed with
1175 // KFileItemModel::roleInformation()
1177 const RoleInfoMap
* map
= rolesInfoMap(count
);
1178 for (int i
= 0; i
< count
; ++i
) {
1179 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1182 // Insert internal roles (take care to synchronize the implementation
1183 // with KFileItemModel::typeForRole() in case if a change is done).
1184 roles
.insert(IsDirRole
, "isDir");
1185 roles
.insert(IsLinkRole
, "isLink");
1186 roles
.insert(IsExpandedRole
, "isExpanded");
1187 roles
.insert(IsExpandableRole
, "isExpandable");
1188 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1190 Q_ASSERT(roles
.count() == RolesCount
);
1193 return roles
.value(roleType
);
1196 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
) const
1198 // It is important to insert only roles that are fast to retrieve. E.g.
1199 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1200 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1201 QHash
<QByteArray
, QVariant
> data
;
1202 data
.insert("url", item
.url());
1204 const bool isDir
= item
.isDir();
1205 if (m_requestRole
[IsDirRole
]) {
1206 data
.insert("isDir", isDir
);
1209 if (m_requestRole
[IsLinkRole
]) {
1210 const bool isLink
= item
.isLink();
1211 data
.insert("isLink", isLink
);
1214 if (m_requestRole
[NameRole
]) {
1215 data
.insert("text", item
.text());
1218 if (m_requestRole
[SizeRole
]) {
1220 data
.insert("size", QVariant());
1222 data
.insert("size", item
.size());
1226 if (m_requestRole
[DateRole
]) {
1227 // Don't use KFileItem::timeString() as this is too expensive when
1228 // having several thousands of items. Instead the formatting of the
1229 // date-time will be done on-demand by the view when the date will be shown.
1230 const KDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
1231 data
.insert("date", dateTime
.dateTime());
1234 if (m_requestRole
[PermissionsRole
]) {
1235 data
.insert("permissions", item
.permissionsString());
1238 if (m_requestRole
[OwnerRole
]) {
1239 data
.insert("owner", item
.user());
1242 if (m_requestRole
[GroupRole
]) {
1243 data
.insert("group", item
.group());
1246 if (m_requestRole
[DestinationRole
]) {
1247 QString destination
= item
.linkDest();
1248 if (destination
.isEmpty()) {
1249 destination
= QLatin1String("-");
1251 data
.insert("destination", destination
);
1254 if (m_requestRole
[PathRole
]) {
1256 if (item
.url().protocol() == QLatin1String("trash")) {
1257 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1259 // For performance reasons cache the home-path in a static QString
1260 // (see QDir::homePath() for more details)
1261 static QString homePath
;
1262 if (homePath
.isEmpty()) {
1263 homePath
= QDir::homePath();
1266 path
= item
.localPath();
1267 if (path
.startsWith(homePath
)) {
1268 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1272 const int index
= path
.lastIndexOf(item
.text());
1273 path
= path
.mid(0, index
- 1);
1274 data
.insert("path", path
);
1277 if (m_requestRole
[IsExpandedRole
]) {
1278 data
.insert("isExpanded", false);
1281 if (m_requestRole
[IsExpandableRole
]) {
1282 data
.insert("isExpandable", item
.isDir() && item
.url() == item
.targetUrl());
1285 if (m_requestRole
[ExpandedParentsCountRole
]) {
1286 if (m_expandedParentsCountRoot
== UninitializedExpandedParentsCountRoot
) {
1287 const KUrl rootUrl
= m_dirLister
->url();
1288 const QString protocol
= rootUrl
.protocol();
1289 const bool forceExpandedParentsCountRoot
= (protocol
== QLatin1String("trash") ||
1290 protocol
== QLatin1String("nepomuk") ||
1291 protocol
== QLatin1String("remote") ||
1292 protocol
.contains(QLatin1String("search")));
1293 if (forceExpandedParentsCountRoot
) {
1294 m_expandedParentsCountRoot
= ForceExpandedParentsCountRoot
;
1296 const QString rootDir
= rootUrl
.path(KUrl::AddTrailingSlash
);
1297 m_expandedParentsCountRoot
= rootDir
.count('/');
1301 if (m_expandedParentsCountRoot
== ForceExpandedParentsCountRoot
) {
1302 data
.insert("expandedParentsCount", -1);
1304 const QString dir
= item
.url().directory(KUrl::AppendTrailingSlash
);
1305 const int level
= dir
.count('/') - m_expandedParentsCountRoot
;
1306 data
.insert("expandedParentsCount", level
);
1310 if (item
.isMimeTypeKnown()) {
1311 data
.insert("iconName", item
.iconName());
1313 if (m_requestRole
[TypeRole
]) {
1314 data
.insert("type", item
.mimeComment());
1321 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
) const
1325 if (m_expandedParentsCountRoot
>= 0) {
1326 result
= expandedParentsCountCompare(a
, b
);
1328 // The items have parents with different expansion levels
1329 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1333 if (m_sortDirsFirst
|| m_sortRole
== SizeRole
) {
1334 const bool isDirA
= a
->item
.isDir();
1335 const bool isDirB
= b
->item
.isDir();
1336 if (isDirA
&& !isDirB
) {
1338 } else if (!isDirA
&& isDirB
) {
1343 result
= sortRoleCompare(a
, b
);
1345 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1349 * Helper class for KFileItemModel::sort().
1351 class KFileItemModelLessThan
1354 KFileItemModelLessThan(const KFileItemModel
* model
) :
1359 bool operator()(const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
) const
1361 return m_model
->lessThan(a
, b
);
1365 const KFileItemModel
* m_model
;
1368 void KFileItemModel::sort(QList
<KFileItemModel::ItemData
*>::iterator begin
,
1369 QList
<KFileItemModel::ItemData
*>::iterator end
) const
1371 KFileItemModelLessThan
lessThan(this);
1373 if (m_sortRole
== NameRole
) {
1374 // Sorting by name can be expensive, in particular if natural sorting is
1375 // enabled. Use all CPU cores to speed up the sorting process.
1376 static const int numberOfThreads
= QThread::idealThreadCount();
1377 parallelMergeSort(begin
, end
, lessThan
, numberOfThreads
);
1379 // Sorting by other roles is quite fast. Use only one thread to prevent
1380 // problems caused by non-reentrant comparison functions, see
1381 // https://bugs.kde.org/show_bug.cgi?id=312679
1382 mergeSort(begin
, end
, lessThan
);
1386 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
) const
1388 const KFileItem
& itemA
= a
->item
;
1389 const KFileItem
& itemB
= b
->item
;
1393 switch (m_sortRole
) {
1395 // The name role is handled as default fallback after the switch
1399 if (itemA
.isDir()) {
1400 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1401 Q_ASSERT(itemB
.isDir());
1403 const QVariant valueA
= a
->values
.value("size");
1404 const QVariant valueB
= b
->values
.value("size");
1405 if (valueA
.isNull() && valueB
.isNull()) {
1407 } else if (valueA
.isNull()) {
1409 } else if (valueB
.isNull()) {
1412 result
= valueA
.toInt() - valueB
.toInt();
1415 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1416 Q_ASSERT(!itemB
.isDir());
1417 const KIO::filesize_t sizeA
= itemA
.size();
1418 const KIO::filesize_t sizeB
= itemB
.size();
1419 if (sizeA
> sizeB
) {
1421 } else if (sizeA
< sizeB
) {
1431 const KDateTime dateTimeA
= itemA
.time(KFileItem::ModificationTime
);
1432 const KDateTime dateTimeB
= itemB
.time(KFileItem::ModificationTime
);
1433 if (dateTimeA
< dateTimeB
) {
1435 } else if (dateTimeA
> dateTimeB
) {
1442 result
= a
->values
.value("rating").toInt() - b
->values
.value("rating").toInt();
1446 case ImageSizeRole
: {
1447 // Alway use a natural comparing to interpret the numbers of a string like
1448 // "1600 x 1200" for having a correct sorting.
1449 result
= KStringHandler::naturalCompare(a
->values
.value("imageSize").toString(),
1450 b
->values
.value("imageSize").toString(),
1456 const QByteArray role
= roleForType(m_sortRole
);
1457 result
= QString::compare(a
->values
.value(role
).toString(),
1458 b
->values
.value(role
).toString());
1465 // The current sort role was sufficient to define an order
1469 // Fallback #1: Compare the text of the items
1470 result
= stringCompare(itemA
.text(), itemB
.text());
1475 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1476 result
= stringCompare(itemA
.name(m_caseSensitivity
== Qt::CaseInsensitive
),
1477 itemB
.name(m_caseSensitivity
== Qt::CaseInsensitive
));
1482 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1483 // equal. In this case a comparison of the URL is done which is unique in all cases
1484 // within KDirLister.
1485 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1488 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
) const
1490 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1491 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1492 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1493 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1495 if (m_caseSensitivity
== Qt::CaseInsensitive
) {
1496 const int result
= m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseInsensitive
)
1497 : QString::compare(a
, b
, Qt::CaseInsensitive
);
1499 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1500 // comparison, still a deterministic sort order is required. A case sensitive
1501 // comparison is done as fallback.
1506 return m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseSensitive
)
1507 : QString::compare(a
, b
, Qt::CaseSensitive
);
1510 int KFileItemModel::expandedParentsCountCompare(const ItemData
* a
, const ItemData
* b
) const
1512 const KUrl urlA
= a
->item
.url();
1513 const KUrl urlB
= b
->item
.url();
1514 if (urlA
.directory() == urlB
.directory()) {
1515 // Both items have the same directory as parent
1519 // Check whether one item is the parent of the other item
1520 if (urlA
.isParentOf(urlB
)) {
1521 return (sortOrder() == Qt::AscendingOrder
) ? -1 : +1;
1522 } else if (urlB
.isParentOf(urlA
)) {
1523 return (sortOrder() == Qt::AscendingOrder
) ? +1 : -1;
1526 // Determine the maximum common path of both items and
1527 // remember the index in 'index'
1528 const QString pathA
= urlA
.path();
1529 const QString pathB
= urlB
.path();
1531 const int maxIndex
= qMin(pathA
.length(), pathB
.length()) - 1;
1533 while (index
<= maxIndex
&& pathA
.at(index
) == pathB
.at(index
)) {
1536 if (index
> maxIndex
) {
1539 while (index
> 0 && (pathA
.at(index
) != QLatin1Char('/') || pathB
.at(index
) != QLatin1Char('/'))) {
1543 // Determine the first sub-path after the common path and
1544 // check whether it represents a directory or already a file
1546 const QString subPathA
= subPath(a
->item
, pathA
, index
, &isDirA
);
1548 const QString subPathB
= subPath(b
->item
, pathB
, index
, &isDirB
);
1550 if (m_sortDirsFirst
|| m_sortRole
== SizeRole
) {
1551 if (isDirA
&& !isDirB
) {
1552 return (sortOrder() == Qt::AscendingOrder
) ? -1 : +1;
1553 } else if (!isDirA
&& isDirB
) {
1554 return (sortOrder() == Qt::AscendingOrder
) ? +1 : -1;
1558 // Compare the items of the parents that represent the first
1559 // different path after the common path.
1560 const QString parentPathA
= pathA
.left(index
) + subPathA
;
1561 const QString parentPathB
= pathB
.left(index
) + subPathB
;
1563 const ItemData
* parentA
= a
;
1564 while (parentA
&& parentA
->item
.url().path() != parentPathA
) {
1565 parentA
= parentA
->parent
;
1568 const ItemData
* parentB
= b
;
1569 while (parentB
&& parentB
->item
.url().path() != parentPathB
) {
1570 parentB
= parentB
->parent
;
1573 if (parentA
&& parentB
) {
1574 return sortRoleCompare(parentA
, parentB
);
1577 kWarning() << "Child items without parent detected:" << a
->item
.url() << b
->item
.url();
1578 return QString::compare(urlA
.url(), urlB
.url(), Qt::CaseSensitive
);
1581 QString
KFileItemModel::subPath(const KFileItem
& item
,
1582 const QString
& itemPath
,
1587 const int pathIndex
= itemPath
.indexOf('/', start
+ 1);
1588 *isDir
= (pathIndex
> 0) || item
.isDir();
1589 return itemPath
.mid(start
, pathIndex
- start
);
1592 bool KFileItemModel::useMaximumUpdateInterval() const
1594 return !m_dirLister
->url().isLocalFile();
1597 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1599 Q_ASSERT(!m_itemData
.isEmpty());
1601 const int maxIndex
= count() - 1;
1602 QList
<QPair
<int, QVariant
> > groups
;
1606 bool isLetter
= false;
1607 for (int i
= 0; i
<= maxIndex
; ++i
) {
1608 if (isChildItem(i
)) {
1612 const QString name
= m_itemData
.at(i
)->values
.value("text").toString();
1614 // Use the first character of the name as group indication
1615 QChar newFirstChar
= name
.at(0).toUpper();
1616 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1617 newFirstChar
= name
.at(1).toUpper();
1620 if (firstChar
!= newFirstChar
) {
1621 QString newGroupValue
;
1622 if (newFirstChar
>= QLatin1Char('A') && newFirstChar
<= QLatin1Char('Z')) {
1623 // Apply group 'A' - 'Z'
1624 newGroupValue
= newFirstChar
;
1626 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
1627 // Apply group '0 - 9' for any name that starts with a digit
1628 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
1632 // If the current group is 'A' - 'Z' check whether a locale character
1633 // fits into the existing group.
1634 // TODO: This does not work in the case if e.g. the group 'O' starts with
1635 // an umlaut 'O' -> provide unit-test to document this known issue
1636 const QChar
prevChar(firstChar
.unicode() - ushort(1));
1637 const QChar
nextChar(firstChar
.unicode() + ushort(1));
1638 const QString
currChar(newFirstChar
);
1639 const bool partOfCurrentGroup
= currChar
.localeAwareCompare(prevChar
) > 0 &&
1640 currChar
.localeAwareCompare(nextChar
) < 0;
1641 if (partOfCurrentGroup
) {
1645 newGroupValue
= i18nc("@title:group", "Others");
1649 if (newGroupValue
!= groupValue
) {
1650 groupValue
= newGroupValue
;
1651 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1654 firstChar
= newFirstChar
;
1660 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
1662 Q_ASSERT(!m_itemData
.isEmpty());
1664 const int maxIndex
= count() - 1;
1665 QList
<QPair
<int, QVariant
> > groups
;
1668 for (int i
= 0; i
<= maxIndex
; ++i
) {
1669 if (isChildItem(i
)) {
1673 const KFileItem
& item
= m_itemData
.at(i
)->item
;
1674 const KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
1675 QString newGroupValue
;
1676 if (!item
.isNull() && item
.isDir()) {
1677 newGroupValue
= i18nc("@title:group Size", "Folders");
1678 } else if (fileSize
< 5 * 1024 * 1024) {
1679 newGroupValue
= i18nc("@title:group Size", "Small");
1680 } else if (fileSize
< 10 * 1024 * 1024) {
1681 newGroupValue
= i18nc("@title:group Size", "Medium");
1683 newGroupValue
= i18nc("@title:group Size", "Big");
1686 if (newGroupValue
!= groupValue
) {
1687 groupValue
= newGroupValue
;
1688 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1695 QList
<QPair
<int, QVariant
> > KFileItemModel::dateRoleGroups() const
1697 Q_ASSERT(!m_itemData
.isEmpty());
1699 const int maxIndex
= count() - 1;
1700 QList
<QPair
<int, QVariant
> > groups
;
1702 const QDate currentDate
= KDateTime::currentLocalDateTime().date();
1704 int yearForCurrentWeek
= 0;
1705 int currentWeek
= currentDate
.weekNumber(&yearForCurrentWeek
);
1706 if (yearForCurrentWeek
== currentDate
.year() + 1) {
1710 QDate previousModifiedDate
;
1712 for (int i
= 0; i
<= maxIndex
; ++i
) {
1713 if (isChildItem(i
)) {
1717 const KDateTime modifiedTime
= m_itemData
.at(i
)->item
.time(KFileItem::ModificationTime
);
1718 const QDate modifiedDate
= modifiedTime
.date();
1719 if (modifiedDate
== previousModifiedDate
) {
1720 // The current item is in the same group as the previous item
1723 previousModifiedDate
= modifiedDate
;
1725 const int daysDistance
= modifiedDate
.daysTo(currentDate
);
1727 int yearForModifiedWeek
= 0;
1728 int modifiedWeek
= modifiedDate
.weekNumber(&yearForModifiedWeek
);
1729 if (yearForModifiedWeek
== modifiedDate
.year() + 1) {
1733 QString newGroupValue
;
1734 if (currentDate
.year() == modifiedDate
.year() && currentDate
.month() == modifiedDate
.month()) {
1735 if (modifiedWeek
> currentWeek
) {
1736 // Usecase: modified date = 2010-01-01, current date = 2010-01-22
1737 // modified week = 53, current week = 3
1740 switch (currentWeek
- modifiedWeek
) {
1742 switch (daysDistance
) {
1743 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
1744 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
1745 default: newGroupValue
= modifiedTime
.toString(i18nc("@title:group The week day name: %A", "%A"));
1749 newGroupValue
= i18nc("@title:group Date", "Last Week");
1752 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
1755 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
1759 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
1765 const QDate lastMonthDate
= currentDate
.addMonths(-1);
1766 if (lastMonthDate
.year() == modifiedDate
.year() && lastMonthDate
.month() == modifiedDate
.month()) {
1767 if (daysDistance
== 1) {
1768 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Yesterday (%B, %Y)"));
1769 } else if (daysDistance
<= 7) {
1770 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)"));
1771 } else if (daysDistance
<= 7 * 2) {
1772 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)"));
1773 } else if (daysDistance
<= 7 * 3) {
1774 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)"));
1775 } else if (daysDistance
<= 7 * 4) {
1776 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)"));
1778 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"));
1781 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"));
1785 if (newGroupValue
!= groupValue
) {
1786 groupValue
= newGroupValue
;
1787 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1794 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
1796 Q_ASSERT(!m_itemData
.isEmpty());
1798 const int maxIndex
= count() - 1;
1799 QList
<QPair
<int, QVariant
> > groups
;
1801 QString permissionsString
;
1803 for (int i
= 0; i
<= maxIndex
; ++i
) {
1804 if (isChildItem(i
)) {
1808 const ItemData
* itemData
= m_itemData
.at(i
);
1809 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
1810 if (newPermissionsString
== permissionsString
) {
1813 permissionsString
= newPermissionsString
;
1815 const QFileInfo
info(itemData
->item
.url().pathOrUrl());
1819 if (info
.permission(QFile::ReadUser
)) {
1820 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1822 if (info
.permission(QFile::WriteUser
)) {
1823 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1825 if (info
.permission(QFile::ExeUser
)) {
1826 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1828 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
1832 if (info
.permission(QFile::ReadGroup
)) {
1833 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1835 if (info
.permission(QFile::WriteGroup
)) {
1836 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1838 if (info
.permission(QFile::ExeGroup
)) {
1839 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1841 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
1843 // Set others string
1845 if (info
.permission(QFile::ReadOther
)) {
1846 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1848 if (info
.permission(QFile::WriteOther
)) {
1849 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1851 if (info
.permission(QFile::ExeOther
)) {
1852 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1854 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
1856 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
1857 if (newGroupValue
!= groupValue
) {
1858 groupValue
= newGroupValue
;
1859 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1866 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
1868 Q_ASSERT(!m_itemData
.isEmpty());
1870 const int maxIndex
= count() - 1;
1871 QList
<QPair
<int, QVariant
> > groups
;
1873 int groupValue
= -1;
1874 for (int i
= 0; i
<= maxIndex
; ++i
) {
1875 if (isChildItem(i
)) {
1878 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
1879 if (newGroupValue
!= groupValue
) {
1880 groupValue
= newGroupValue
;
1881 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1888 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
1890 Q_ASSERT(!m_itemData
.isEmpty());
1892 const int maxIndex
= count() - 1;
1893 QList
<QPair
<int, QVariant
> > groups
;
1895 bool isFirstGroupValue
= true;
1897 for (int i
= 0; i
<= maxIndex
; ++i
) {
1898 if (isChildItem(i
)) {
1901 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
1902 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
1903 groupValue
= newGroupValue
;
1904 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1905 isFirstGroupValue
= false;
1912 KFileItemList
KFileItemModel::childItems(const KFileItem
& item
) const
1914 KFileItemList items
;
1916 int index
= m_items
.value(item
.url(), -1);
1918 const int parentLevel
= m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt();
1920 while (index
< m_itemData
.count() && m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt() > parentLevel
) {
1921 items
.append(m_itemData
.at(index
)->item
);
1929 void KFileItemModel::emitSortProgress(int resolvedCount
)
1931 // Be tolerant against a resolvedCount with a wrong range.
1932 // Although there should not be a case where KFileItemModelRolesUpdater
1933 // (= caller) provides a wrong range, it is important to emit
1934 // a useful progress information even if there is an unexpected
1935 // implementation issue.
1937 const int itemCount
= count();
1938 if (resolvedCount
>= itemCount
) {
1939 m_sortingProgressPercent
= -1;
1940 if (m_resortAllItemsTimer
->isActive()) {
1941 m_resortAllItemsTimer
->stop();
1945 emit
directorySortingProgress(100);
1946 } else if (itemCount
> 0) {
1947 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
1949 const int progress
= resolvedCount
* 100 / itemCount
;
1950 if (m_sortingProgressPercent
!= progress
) {
1951 m_sortingProgressPercent
= progress
;
1952 emit
directorySortingProgress(progress
);
1957 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
1959 static const RoleInfoMap rolesInfoMap
[] = {
1960 // | role | roleType | role translation | group translation | requires Nepomuk | requires indexer
1961 { 0, NoRole
, 0, 0, 0, 0, false, false },
1962 { "text", NameRole
, I18N_NOOP2_NOSTRIP("@label", "Name"), 0, 0, false, false },
1963 { "size", SizeRole
, I18N_NOOP2_NOSTRIP("@label", "Size"), 0, 0, false, false },
1964 { "date", DateRole
, I18N_NOOP2_NOSTRIP("@label", "Date"), 0, 0, false, false },
1965 { "type", TypeRole
, I18N_NOOP2_NOSTRIP("@label", "Type"), 0, 0, false, false },
1966 { "rating", RatingRole
, I18N_NOOP2_NOSTRIP("@label", "Rating"), 0, 0, true, false },
1967 { "tags", TagsRole
, I18N_NOOP2_NOSTRIP("@label", "Tags"), 0, 0, true, false },
1968 { "comment", CommentRole
, I18N_NOOP2_NOSTRIP("@label", "Comment"), 0, 0, true, false },
1969 { "wordCount", WordCountRole
, I18N_NOOP2_NOSTRIP("@label", "Word Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
1970 { "lineCount", LineCountRole
, I18N_NOOP2_NOSTRIP("@label", "Line Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
1971 { "imageSize", ImageSizeRole
, I18N_NOOP2_NOSTRIP("@label", "Image Size"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
1972 { "orientation", OrientationRole
, I18N_NOOP2_NOSTRIP("@label", "Orientation"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
1973 { "artist", ArtistRole
, I18N_NOOP2_NOSTRIP("@label", "Artist"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1974 { "album", AlbumRole
, I18N_NOOP2_NOSTRIP("@label", "Album"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1975 { "duration", DurationRole
, I18N_NOOP2_NOSTRIP("@label", "Duration"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1976 { "track", TrackRole
, I18N_NOOP2_NOSTRIP("@label", "Track"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1977 { "path", PathRole
, I18N_NOOP2_NOSTRIP("@label", "Path"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1978 { "destination", DestinationRole
, I18N_NOOP2_NOSTRIP("@label", "Link Destination"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1979 { "copiedFrom", CopiedFromRole
, I18N_NOOP2_NOSTRIP("@label", "Copied From"), I18N_NOOP2_NOSTRIP("@label", "Other"), true, false },
1980 { "permissions", PermissionsRole
, I18N_NOOP2_NOSTRIP("@label", "Permissions"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1981 { "owner", OwnerRole
, I18N_NOOP2_NOSTRIP("@label", "Owner"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1982 { "group", GroupRole
, I18N_NOOP2_NOSTRIP("@label", "User Group"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1985 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
1986 return rolesInfoMap
;
1989 void KFileItemModel::determineMimeTypes(const KFileItemList
& items
, int timeout
)
1991 QElapsedTimer timer
;
1993 foreach (KFileItem item
, items
) { // krazy:exclude=foreach
1994 item
.determineMimeType();
1995 if (timer
.elapsed() > timeout
) {
1996 // Don't block the user interface, let the remaining items
1997 // be resolved asynchronously.
2003 #include "kfileitemmodel.moc"