1 /***************************************************************************
2 * Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
3 * Copyright (C) 2013 by Frank Reininghaus <frank78ac@googlemail.com> *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
19 ***************************************************************************/
21 #include "kfileitemmodel.h"
24 #include <KGlobalSettings>
26 #include <KStringHandler>
29 #include "private/kfileitemmodelsortalgorithm.h"
30 #include "private/kfileitemmodeldirlister.h"
32 #include <QApplication>
37 // #define KFILEITEMMODEL_DEBUG
39 KFileItemModel::KFileItemModel(QObject
* parent
) :
40 KItemModelBase("text", parent
),
42 m_naturalSorting(KGlobalSettings::naturalSorting()),
43 m_sortDirsFirst(true),
45 m_sortingProgressPercent(-1),
47 m_caseSensitivity(Qt::CaseInsensitive
),
53 m_maximumUpdateIntervalTimer(0),
54 m_resortAllItemsTimer(0),
55 m_pendingItemsToInsert(),
57 m_expandedParentsCountRoot(UninitializedExpandedParentsCountRoot
),
61 m_dirLister
= new KFileItemModelDirLister(this);
62 m_dirLister
->setDelayedMimeTypes(true);
64 const QWidget
* parentWidget
= qobject_cast
<QWidget
*>(parent
);
66 m_dirLister
->setMainWindow(parentWidget
->window());
69 connect(m_dirLister
, SIGNAL(started(KUrl
)), this, SIGNAL(directoryLoadingStarted()));
70 connect(m_dirLister
, SIGNAL(canceled()), this, SLOT(slotCanceled()));
71 connect(m_dirLister
, SIGNAL(completed(KUrl
)), this, SLOT(slotCompleted()));
72 connect(m_dirLister
, SIGNAL(newItems(KFileItemList
)), this, SLOT(slotNewItems(KFileItemList
)));
73 connect(m_dirLister
, SIGNAL(itemsDeleted(KFileItemList
)), this, SLOT(slotItemsDeleted(KFileItemList
)));
74 connect(m_dirLister
, SIGNAL(refreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)), this, SLOT(slotRefreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)));
75 connect(m_dirLister
, SIGNAL(clear()), this, SLOT(slotClear()));
76 connect(m_dirLister
, SIGNAL(clear(KUrl
)), this, SLOT(slotClear(KUrl
)));
77 connect(m_dirLister
, SIGNAL(infoMessage(QString
)), this, SIGNAL(infoMessage(QString
)));
78 connect(m_dirLister
, SIGNAL(errorMessage(QString
)), this, SIGNAL(errorMessage(QString
)));
79 connect(m_dirLister
, SIGNAL(redirection(KUrl
,KUrl
)), this, SIGNAL(directoryRedirection(KUrl
,KUrl
)));
80 connect(m_dirLister
, SIGNAL(urlIsFileError(KUrl
)), this, SIGNAL(urlIsFileError(KUrl
)));
82 // Apply default roles that should be determined
84 m_requestRole
[NameRole
] = true;
85 m_requestRole
[IsDirRole
] = true;
86 m_requestRole
[IsLinkRole
] = true;
87 m_roles
.insert("text");
88 m_roles
.insert("isDir");
89 m_roles
.insert("isLink");
91 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
92 // before the completed() or canceled() signal has been emitted.
93 m_maximumUpdateIntervalTimer
= new QTimer(this);
94 m_maximumUpdateIntervalTimer
->setInterval(2000);
95 m_maximumUpdateIntervalTimer
->setSingleShot(true);
96 connect(m_maximumUpdateIntervalTimer
, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
98 // When changing the value of an item which represents the sort-role a resorting must be
99 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
100 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
101 // resorting is postponed until the timer has been exceeded.
102 m_resortAllItemsTimer
= new QTimer(this);
103 m_resortAllItemsTimer
->setInterval(500);
104 m_resortAllItemsTimer
->setSingleShot(true);
105 connect(m_resortAllItemsTimer
, SIGNAL(timeout()), this, SLOT(resortAllItems()));
107 connect(KGlobalSettings::self(), SIGNAL(naturalSortingChanged()), this, SLOT(slotNaturalSortingChanged()));
110 KFileItemModel::~KFileItemModel()
112 qDeleteAll(m_itemData
);
116 void KFileItemModel::loadDirectory(const KUrl
& url
)
118 m_dirLister
->openUrl(url
);
121 void KFileItemModel::refreshDirectory(const KUrl
& url
)
123 m_dirLister
->openUrl(url
, KDirLister::Reload
);
126 KUrl
KFileItemModel::directory() const
128 return m_dirLister
->url();
131 void KFileItemModel::cancelDirectoryLoading()
136 int KFileItemModel::count() const
138 return m_itemData
.count();
141 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
143 if (index
>= 0 && index
< count()) {
144 return m_itemData
.at(index
)->values
;
146 return QHash
<QByteArray
, QVariant
>();
149 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
151 if (index
< 0 || index
>= count()) {
155 QHash
<QByteArray
, QVariant
> currentValues
= m_itemData
.at(index
)->values
;
157 // Determine which roles have been changed
158 QSet
<QByteArray
> changedRoles
;
159 QHashIterator
<QByteArray
, QVariant
> it(values
);
160 while (it
.hasNext()) {
162 const QByteArray role
= it
.key();
163 const QVariant value
= it
.value();
165 if (currentValues
[role
] != value
) {
166 currentValues
[role
] = value
;
167 changedRoles
.insert(role
);
171 if (changedRoles
.isEmpty()) {
175 m_itemData
[index
]->values
= currentValues
;
176 if (changedRoles
.contains("text")) {
177 KUrl url
= m_itemData
[index
]->item
.url();
178 url
.setFileName(currentValues
["text"].toString());
179 m_itemData
[index
]->item
.setUrl(url
);
182 emit
itemsChanged(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
184 if (changedRoles
.contains(sortRole())) {
185 m_resortAllItemsTimer
->start();
191 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
193 if (dirsFirst
!= m_sortDirsFirst
) {
194 m_sortDirsFirst
= dirsFirst
;
199 bool KFileItemModel::sortDirectoriesFirst() const
201 return m_sortDirsFirst
;
204 void KFileItemModel::setShowHiddenFiles(bool show
)
206 m_dirLister
->setShowingDotFiles(show
);
207 m_dirLister
->emitChanges();
213 bool KFileItemModel::showHiddenFiles() const
215 return m_dirLister
->showingDotFiles();
218 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
220 m_dirLister
->setDirOnlyMode(enabled
);
223 bool KFileItemModel::showDirectoriesOnly() const
225 return m_dirLister
->dirOnlyMode();
228 QMimeData
* KFileItemModel::createMimeData(const QSet
<int>& indexes
) const
230 QMimeData
* data
= new QMimeData();
232 // The following code has been taken from KDirModel::mimeData()
233 // (kdelibs/kio/kio/kdirmodel.cpp)
234 // Copyright (C) 2006 David Faure <faure@kde.org>
236 KUrl::List mostLocalUrls
;
237 bool canUseMostLocalUrls
= true;
239 QSetIterator
<int> it(indexes
);
240 while (it
.hasNext()) {
241 const int index
= it
.next();
242 const KFileItem item
= fileItem(index
);
243 if (!item
.isNull()) {
247 mostLocalUrls
<< item
.mostLocalUrl(isLocal
);
249 canUseMostLocalUrls
= false;
254 const bool different
= canUseMostLocalUrls
&& mostLocalUrls
!= urls
;
255 urls
= KDirModel::simplifiedUrlList(urls
); // TODO: Check if we still need KDirModel for this in KDE 5.0
257 mostLocalUrls
= KDirModel::simplifiedUrlList(mostLocalUrls
);
258 urls
.populateMimeData(mostLocalUrls
, data
);
260 urls
.populateMimeData(data
);
266 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
268 startFromIndex
= qMax(0, startFromIndex
);
269 for (int i
= startFromIndex
; i
< count(); ++i
) {
270 if (data(i
)["text"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
274 for (int i
= 0; i
< startFromIndex
; ++i
) {
275 if (data(i
)["text"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
282 bool KFileItemModel::supportsDropping(int index
) const
284 const KFileItem item
= fileItem(index
);
285 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
288 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
290 static QHash
<QByteArray
, QString
> description
;
291 if (description
.isEmpty()) {
293 const RoleInfoMap
* map
= rolesInfoMap(count
);
294 for (int i
= 0; i
< count
; ++i
) {
295 description
.insert(map
[i
].role
, i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
));
299 return description
.value(role
);
302 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
304 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
305 #ifdef KFILEITEMMODEL_DEBUG
309 switch (typeForRole(sortRole())) {
310 case NameRole
: m_groups
= nameRoleGroups(); break;
311 case SizeRole
: m_groups
= sizeRoleGroups(); break;
312 case DateRole
: m_groups
= dateRoleGroups(); break;
313 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
314 case RatingRole
: m_groups
= ratingRoleGroups(); break;
315 default: m_groups
= genericStringRoleGroups(sortRole()); break;
318 #ifdef KFILEITEMMODEL_DEBUG
319 kDebug() << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
326 KFileItem
KFileItemModel::fileItem(int index
) const
328 if (index
>= 0 && index
< count()) {
329 return m_itemData
.at(index
)->item
;
335 KFileItem
KFileItemModel::fileItem(const KUrl
& url
) const
337 const int index
= m_items
.value(url
, -1);
339 return m_itemData
.at(index
)->item
;
344 int KFileItemModel::index(const KFileItem
& item
) const
350 return m_items
.value(item
.url(), -1);
353 int KFileItemModel::index(const KUrl
& url
) const
355 KUrl urlToFind
= url
;
356 urlToFind
.adjustPath(KUrl::RemoveTrailingSlash
);
357 return m_items
.value(urlToFind
, -1);
360 KFileItem
KFileItemModel::rootItem() const
362 return m_dirLister
->rootItem();
365 void KFileItemModel::clear()
370 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
372 if (m_roles
== roles
) {
378 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
379 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
380 if (supportedExpanding
&& !willSupportExpanding
) {
381 // No expanding is supported anymore. Take care to delete all items that have an expansion level
382 // that is not 0 (and hence are part of an expanded item).
383 removeExpandedItems();
390 QSetIterator
<QByteArray
> it(roles
);
391 while (it
.hasNext()) {
392 const QByteArray
& role
= it
.next();
393 m_requestRole
[typeForRole(role
)] = true;
397 // Update m_data with the changed requested roles
398 const int maxIndex
= count() - 1;
399 for (int i
= 0; i
<= maxIndex
; ++i
) {
400 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
);
403 kWarning() << "TODO: Emitting itemsChanged() with no information what has changed!";
404 emit
itemsChanged(KItemRangeList() << KItemRange(0, count()), QSet
<QByteArray
>());
408 QSet
<QByteArray
> KFileItemModel::roles() const
413 bool KFileItemModel::setExpanded(int index
, bool expanded
)
415 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
419 QHash
<QByteArray
, QVariant
> values
;
420 values
.insert("isExpanded", expanded
);
421 if (!setData(index
, values
)) {
425 const KUrl url
= m_itemData
.at(index
)->item
.url();
427 m_expandedDirs
.insert(url
);
428 m_dirLister
->openUrl(url
, KDirLister::Keep
);
430 m_expandedDirs
.remove(url
);
431 m_dirLister
->stop(url
);
434 KFileItemList itemsToRemove
;
435 const int expandedParentsCount
= data(index
)["expandedParentsCount"].toInt();
437 while (index
< count() && data(index
)["expandedParentsCount"].toInt() > expandedParentsCount
) {
438 itemsToRemove
.append(m_itemData
.at(index
)->item
);
441 removeItems(itemsToRemove
);
447 bool KFileItemModel::isExpanded(int index
) const
449 if (index
>= 0 && index
< count()) {
450 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
455 bool KFileItemModel::isExpandable(int index
) const
457 if (index
>= 0 && index
< count()) {
458 return m_itemData
.at(index
)->values
.value("isExpandable").toBool();
463 int KFileItemModel::expandedParentsCount(int index
) const
465 if (index
>= 0 && index
< count()) {
466 const int parentsCount
= m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt();
467 if (parentsCount
> 0) {
474 QSet
<KUrl
> KFileItemModel::expandedDirectories() const
476 return m_expandedDirs
;
479 void KFileItemModel::restoreExpandedDirectories(const QSet
<KUrl
>& urls
)
481 m_urlsToExpand
= urls
;
484 void KFileItemModel::expandParentDirectories(const KUrl
& url
)
486 const int pos
= m_dirLister
->url().path().length();
488 // Assure that each sub-path of the URL that should be
489 // expanded is added to m_urlsToExpand. KDirLister
490 // does not care whether the parent-URL has already been
492 KUrl urlToExpand
= m_dirLister
->url();
493 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator());
494 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
495 urlToExpand
.addPath(subDirs
.at(i
));
496 m_urlsToExpand
.insert(urlToExpand
);
499 // KDirLister::open() must called at least once to trigger an initial
500 // loading. The pending URLs that must be restored are handled
501 // in slotCompleted().
502 QSetIterator
<KUrl
> it2(m_urlsToExpand
);
503 while (it2
.hasNext()) {
504 const int idx
= index(it2
.next());
505 if (idx
>= 0 && !isExpanded(idx
)) {
506 setExpanded(idx
, true);
512 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
514 if (m_filter
.pattern() != nameFilter
) {
515 dispatchPendingItemsToInsert();
516 m_filter
.setPattern(nameFilter
);
521 QString
KFileItemModel::nameFilter() const
523 return m_filter
.pattern();
526 void KFileItemModel::setMimeTypeFilters(const QStringList
& filters
)
528 if (m_filter
.mimeTypes() != filters
) {
529 dispatchPendingItemsToInsert();
530 m_filter
.setMimeTypes(filters
);
535 QStringList
KFileItemModel::mimeTypeFilters() const
537 return m_filter
.mimeTypes();
541 void KFileItemModel::applyFilters()
543 // Check which shown items from m_itemData must get
544 // hidden and hence moved to m_filteredItems.
545 KFileItemList newFilteredItems
;
547 foreach (ItemData
* itemData
, m_itemData
) {
548 // Only filter non-expanded items as child items may never
549 // exist without a parent item
550 if (!itemData
->values
.value("isExpanded").toBool()) {
551 if (!m_filter
.matches(itemData
->item
)) {
552 newFilteredItems
.append(itemData
->item
);
553 m_filteredItems
.insert(itemData
->item
);
558 removeItems(newFilteredItems
);
560 // Check which hidden items from m_filteredItems should
561 // get visible again and hence removed from m_filteredItems.
562 KFileItemList newVisibleItems
;
564 QMutableSetIterator
<KFileItem
> it(m_filteredItems
);
565 while (it
.hasNext()) {
566 const KFileItem item
= it
.next();
567 if (m_filter
.matches(item
)) {
568 newVisibleItems
.append(item
);
573 insertItems(newVisibleItems
);
576 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
578 static QList
<RoleInfo
> rolesInfo
;
579 if (rolesInfo
.isEmpty()) {
581 const RoleInfoMap
* map
= rolesInfoMap(count
);
582 for (int i
= 0; i
< count
; ++i
) {
583 if (map
[i
].roleType
!= NoRole
) {
585 info
.role
= map
[i
].role
;
586 info
.translation
= i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
);
587 if (map
[i
].groupTranslation
) {
588 info
.group
= i18nc(map
[i
].groupTranslationContext
, map
[i
].groupTranslation
);
590 // For top level roles, groupTranslation is 0. We must make sure that
591 // info.group is an empty string then because the code that generates
592 // menus tries to put the actions into sub menus otherwise.
593 info
.group
= QString();
595 info
.requiresNepomuk
= map
[i
].requiresNepomuk
;
596 info
.requiresIndexer
= map
[i
].requiresIndexer
;
597 rolesInfo
.append(info
);
605 void KFileItemModel::onGroupedSortingChanged(bool current
)
611 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
614 m_sortRole
= typeForRole(current
);
616 #ifdef KFILEITEMMODEL_DEBUG
617 if (!m_requestRole
[m_sortRole
]) {
618 kWarning() << "The sort-role has been changed to a role that has not been received yet";
625 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
632 void KFileItemModel::resortAllItems()
634 m_resortAllItemsTimer
->stop();
636 const int itemCount
= count();
637 if (itemCount
<= 0) {
641 #ifdef KFILEITEMMODEL_DEBUG
644 kDebug() << "===========================================================";
645 kDebug() << "Resorting" << itemCount
<< "items";
648 // Remember the order of the current URLs so
649 // that it can be determined which indexes have
650 // been moved because of the resorting.
652 oldUrls
.reserve(itemCount
);
653 foreach (const ItemData
* itemData
, m_itemData
) {
654 oldUrls
.append(itemData
->item
.url());
661 sort(m_itemData
.begin(), m_itemData
.end());
662 for (int i
= 0; i
< itemCount
; ++i
) {
663 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
666 // Determine the indexes that have been moved
667 QList
<int> movedToIndexes
;
668 movedToIndexes
.reserve(itemCount
);
669 for (int i
= 0; i
< itemCount
; i
++) {
670 const int newIndex
= m_items
.value(oldUrls
.at(i
).url());
671 movedToIndexes
.append(newIndex
);
674 // Don't check whether items have really been moved and always emit a
675 // itemsMoved() signal after resorting: In case of grouped items
676 // the groups might change even if the items themselves don't change their
677 // position. Let the receiver of the signal decide whether a check for moved
678 // items makes sense.
679 emit
itemsMoved(KItemRange(0, itemCount
), movedToIndexes
);
681 #ifdef KFILEITEMMODEL_DEBUG
682 kDebug() << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
686 void KFileItemModel::slotCompleted()
688 dispatchPendingItemsToInsert();
690 if (!m_urlsToExpand
.isEmpty()) {
691 // Try to find a URL that can be expanded.
692 // Note that the parent folder must be expanded before any of its subfolders become visible.
693 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
694 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
695 foreach (const KUrl
& url
, m_urlsToExpand
) {
696 const int index
= m_items
.value(url
, -1);
698 m_urlsToExpand
.remove(url
);
699 if (setExpanded(index
, true)) {
700 // The dir lister has been triggered. This slot will be called
701 // again after the directory has been expanded.
707 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
708 // if these URLs have been deleted in the meantime.
709 m_urlsToExpand
.clear();
712 emit
directoryLoadingCompleted();
715 void KFileItemModel::slotCanceled()
717 m_maximumUpdateIntervalTimer
->stop();
718 dispatchPendingItemsToInsert();
720 emit
directoryLoadingCanceled();
723 void KFileItemModel::slotNewItems(const KFileItemList
& items
)
725 Q_ASSERT(!items
.isEmpty());
727 if (m_requestRole
[ExpandedParentsCountRole
] && m_expandedParentsCountRoot
>= 0) {
728 // To be able to compare whether the new items may be inserted as children
729 // of a parent item the pending items must be added to the model first.
730 dispatchPendingItemsToInsert();
732 KFileItem item
= items
.first();
734 // If the expanding of items is enabled, the call
735 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
736 // might result in emitting the same items twice due to the Keep-parameter.
737 // This case happens if an item gets expanded, collapsed and expanded again
738 // before the items could be loaded for the first expansion.
739 const int index
= m_items
.value(item
.url(), -1);
741 // The items are already part of the model.
745 // KDirLister keeps the children of items that got expanded once even if
746 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
747 // checked whether the parent for new items is still expanded.
748 KUrl parentUrl
= item
.url().upUrl();
749 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
750 const int parentIndex
= m_items
.value(parentUrl
, -1);
751 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
752 // The parent is not expanded.
757 if (!m_filter
.hasSetFilters()) {
758 m_pendingItemsToInsert
.append(items
);
760 // The name or type filter is active. Hide filtered items
761 // before inserting them into the model and remember
762 // the filtered items in m_filteredItems.
763 KFileItemList filteredItems
;
764 foreach (const KFileItem
& item
, items
) {
765 if (m_filter
.matches(item
)) {
766 filteredItems
.append(item
);
768 m_filteredItems
.insert(item
);
772 m_pendingItemsToInsert
.append(filteredItems
);
775 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer
->isActive()) {
776 // Assure that items get dispatched if no completed() or canceled() signal is
777 // emitted during the maximum update interval.
778 m_maximumUpdateIntervalTimer
->start();
782 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
784 dispatchPendingItemsToInsert();
786 KFileItemList itemsToRemove
= items
;
787 if (m_requestRole
[ExpandedParentsCountRole
] && m_expandedParentsCountRoot
>= 0) {
788 // Assure that removing a parent item also results in removing all children
789 foreach (const KFileItem
& item
, items
) {
790 itemsToRemove
.append(childItems(item
));
794 if (!m_filteredItems
.isEmpty()) {
795 foreach (const KFileItem
& item
, itemsToRemove
) {
796 m_filteredItems
.remove(item
);
800 removeItems(itemsToRemove
);
803 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
805 Q_ASSERT(!items
.isEmpty());
806 #ifdef KFILEITEMMODEL_DEBUG
807 kDebug() << "Refreshing" << items
.count() << "items";
812 // Get the indexes of all items that have been refreshed
814 indexes
.reserve(items
.count());
816 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
817 while (it
.hasNext()) {
818 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
819 const KFileItem
& oldItem
= itemPair
.first
;
820 const KFileItem
& newItem
= itemPair
.second
;
821 const int index
= m_items
.value(oldItem
.url(), -1);
823 m_itemData
[index
]->item
= newItem
;
825 // Keep old values as long as possible if they could not retrieved synchronously yet.
826 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
827 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
));
828 while (it
.hasNext()) {
830 m_itemData
[index
]->values
.insert(it
.key(), it
.value());
833 m_items
.remove(oldItem
.url());
834 m_items
.insert(newItem
.url(), index
);
835 indexes
.append(index
);
839 // If the changed items have been created recently, they might not be in m_items yet.
840 // In that case, the list 'indexes' might be empty.
841 if (indexes
.isEmpty()) {
845 // Extract the item-ranges out of the changed indexes
848 KItemRangeList itemRangeList
;
849 int previousIndex
= indexes
.at(0);
850 int rangeIndex
= previousIndex
;
853 const int maxIndex
= indexes
.count() - 1;
854 for (int i
= 1; i
<= maxIndex
; ++i
) {
855 const int currentIndex
= indexes
.at(i
);
856 if (currentIndex
== previousIndex
+ 1) {
859 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
861 rangeIndex
= currentIndex
;
864 previousIndex
= currentIndex
;
867 if (rangeCount
> 0) {
868 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
871 emit
itemsChanged(itemRangeList
, m_roles
);
876 void KFileItemModel::slotClear()
878 #ifdef KFILEITEMMODEL_DEBUG
879 kDebug() << "Clearing all items";
882 m_filteredItems
.clear();
885 m_maximumUpdateIntervalTimer
->stop();
886 m_resortAllItemsTimer
->stop();
887 m_pendingItemsToInsert
.clear();
889 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
891 const int removedCount
= m_itemData
.count();
892 if (removedCount
> 0) {
893 qDeleteAll(m_itemData
);
896 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
899 m_expandedDirs
.clear();
902 void KFileItemModel::slotClear(const KUrl
& url
)
907 void KFileItemModel::slotNaturalSortingChanged()
909 m_naturalSorting
= KGlobalSettings::naturalSorting();
913 void KFileItemModel::dispatchPendingItemsToInsert()
915 if (!m_pendingItemsToInsert
.isEmpty()) {
916 insertItems(m_pendingItemsToInsert
);
917 m_pendingItemsToInsert
.clear();
921 void KFileItemModel::insertItems(const KFileItemList
& items
)
923 if (items
.isEmpty()) {
927 if (m_sortRole
== TypeRole
) {
928 // Try to resolve the MIME-types synchronously to prevent a reordering of
929 // the items when sorting by type (per default MIME-types are resolved
930 // asynchronously by KFileItemModelRolesUpdater).
931 determineMimeTypes(items
, 200);
934 #ifdef KFILEITEMMODEL_DEBUG
937 kDebug() << "===========================================================";
938 kDebug() << "Inserting" << items
.count() << "items";
943 QList
<ItemData
*> sortedItems
= createItemDataList(items
);
944 sort(sortedItems
.begin(), sortedItems
.end());
946 #ifdef KFILEITEMMODEL_DEBUG
947 kDebug() << "[TIME] Sorting:" << timer
.elapsed();
950 KItemRangeList itemRanges
;
953 int insertedAtIndex
= -1; // Index for the current item-range
954 int insertedCount
= 0; // Count for the current item-range
955 int previouslyInsertedCount
= 0; // Sum of previously inserted items for all ranges
956 while (sourceIndex
< sortedItems
.count()) {
957 // Find target index from m_items to insert the current item
959 const int previousTargetIndex
= targetIndex
;
960 while (targetIndex
< m_itemData
.count()) {
961 if (!lessThan(m_itemData
.at(targetIndex
), sortedItems
.at(sourceIndex
))) {
967 if (targetIndex
- previousTargetIndex
> 0 && insertedAtIndex
>= 0) {
968 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
969 previouslyInsertedCount
+= insertedCount
;
970 insertedAtIndex
= targetIndex
- previouslyInsertedCount
;
974 // Insert item at the position targetIndex by transferring
975 // the ownership of the item-data from sortedItems to m_itemData.
976 // m_items will be inserted after the loop (see comment below)
977 m_itemData
.insert(targetIndex
, sortedItems
.at(sourceIndex
));
980 if (insertedAtIndex
< 0) {
981 insertedAtIndex
= targetIndex
;
982 Q_ASSERT(previouslyInsertedCount
== 0);
988 // The indexes of all m_items must be adjusted, not only the index
990 const int itemDataCount
= m_itemData
.count();
991 m_items
.reserve(itemDataCount
);
992 for (int i
= 0; i
< itemDataCount
; ++i
) {
993 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
996 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
997 emit
itemsInserted(itemRanges
);
999 #ifdef KFILEITEMMODEL_DEBUG
1000 kDebug() << "[TIME] Inserting of" << items
.count() << "items:" << timer
.elapsed();
1004 static KItemRangeList
sortedIndexesToKItemRangeList(const QList
<int>& sortedNumbers
)
1006 if (sortedNumbers
.empty()) {
1007 return KItemRangeList();
1010 KItemRangeList result
;
1012 QList
<int>::const_iterator it
= sortedNumbers
.begin();
1018 QList
<int>::const_iterator end
= sortedNumbers
.end();
1020 if (*it
== index
+ count
) {
1023 result
<< KItemRange(index
, count
);
1030 result
<< KItemRange(index
, count
);
1034 void KFileItemModel::removeItems(const KFileItemList
& items
)
1036 #ifdef KFILEITEMMODEL_DEBUG
1037 kDebug() << "Removing " << items
.count() << "items";
1042 // Step 1: Determine the indexes of the removed items, remove them from
1043 // the hash m_items, and free the ItemData.
1044 QList
<int> indexesToRemove
;
1045 indexesToRemove
.reserve(items
.count());
1046 foreach (const KFileItem
& item
, items
) {
1047 const KUrl url
= item
.url();
1048 const int index
= m_items
.value(url
, -1);
1050 indexesToRemove
.append(index
);
1052 // Prevent repeated expensive rehashing by using QHash::erase(),
1053 // rather than QHash::remove().
1054 QHash
<KUrl
, int>::iterator it
= m_items
.find(url
);
1057 ItemData
* data
= m_itemData
.at(index
);
1059 m_itemData
[index
] = 0;
1063 if (indexesToRemove
.isEmpty()) {
1067 std::sort(indexesToRemove
.begin(), indexesToRemove
.end());
1069 // Step 2: Remove the ItemData pointers from the list m_itemData.
1070 const KItemRangeList itemRanges
= sortedIndexesToKItemRangeList(indexesToRemove
);
1071 int target
= itemRanges
.at(0).index
;
1072 int source
= itemRanges
.at(0).index
+ itemRanges
.at(0).count
;
1075 const int oldItemDataCount
= m_itemData
.count();
1076 while (source
< oldItemDataCount
) {
1077 m_itemData
[target
] = m_itemData
[source
];
1081 if (nextRange
< itemRanges
.count() && source
== itemRanges
.at(nextRange
).index
) {
1082 // Skip the items in the next removed range.
1083 source
+= itemRanges
.at(nextRange
).count
;
1088 m_itemData
.erase(m_itemData
.end() - indexesToRemove
.count(), m_itemData
.end());
1090 // Step 3: Adjust indexes in the hash m_items. Note that all indexes
1091 // might have been changed by the removal of the items.
1092 const int newItemDataCount
= m_itemData
.count();
1093 for (int i
= 0; i
< newItemDataCount
; ++i
) {
1094 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
1098 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
1101 emit
itemsRemoved(itemRanges
);
1104 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const KFileItemList
& items
) const
1106 QList
<ItemData
*> itemDataList
;
1107 itemDataList
.reserve(items
.count());
1109 foreach (const KFileItem
& item
, items
) {
1110 ItemData
* itemData
= new ItemData();
1111 itemData
->item
= item
;
1112 itemData
->values
= retrieveData(item
);
1113 itemData
->parent
= 0;
1115 const bool determineParent
= m_requestRole
[ExpandedParentsCountRole
]
1116 && itemData
->values
["expandedParentsCount"].toInt() > 0;
1117 if (determineParent
) {
1118 KUrl parentUrl
= item
.url().upUrl();
1119 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
1120 const int parentIndex
= m_items
.value(parentUrl
, -1);
1121 if (parentIndex
>= 0) {
1122 itemData
->parent
= m_itemData
.at(parentIndex
);
1124 kWarning() << "Parent item not found for" << item
.url();
1128 itemDataList
.append(itemData
);
1131 return itemDataList
;
1134 void KFileItemModel::removeExpandedItems()
1136 KFileItemList expandedItems
;
1138 const int maxIndex
= m_itemData
.count() - 1;
1139 for (int i
= 0; i
<= maxIndex
; ++i
) {
1140 const ItemData
* itemData
= m_itemData
.at(i
);
1141 if (itemData
->values
.value("expandedParentsCount").toInt() > 0) {
1142 expandedItems
.append(itemData
->item
);
1146 // The m_expandedParentsCountRoot may not get reset before all items with
1147 // a bigger count have been removed.
1148 removeItems(expandedItems
);
1150 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
1151 m_expandedDirs
.clear();
1154 void KFileItemModel::resetRoles()
1156 for (int i
= 0; i
< RolesCount
; ++i
) {
1157 m_requestRole
[i
] = false;
1161 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1163 static QHash
<QByteArray
, RoleType
> roles
;
1164 if (roles
.isEmpty()) {
1165 // Insert user visible roles that can be accessed with
1166 // KFileItemModel::roleInformation()
1168 const RoleInfoMap
* map
= rolesInfoMap(count
);
1169 for (int i
= 0; i
< count
; ++i
) {
1170 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1173 // Insert internal roles (take care to synchronize the implementation
1174 // with KFileItemModel::roleForType() in case if a change is done).
1175 roles
.insert("isDir", IsDirRole
);
1176 roles
.insert("isLink", IsLinkRole
);
1177 roles
.insert("isExpanded", IsExpandedRole
);
1178 roles
.insert("isExpandable", IsExpandableRole
);
1179 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1181 Q_ASSERT(roles
.count() == RolesCount
);
1184 return roles
.value(role
, NoRole
);
1187 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1189 static QHash
<RoleType
, QByteArray
> roles
;
1190 if (roles
.isEmpty()) {
1191 // Insert user visible roles that can be accessed with
1192 // KFileItemModel::roleInformation()
1194 const RoleInfoMap
* map
= rolesInfoMap(count
);
1195 for (int i
= 0; i
< count
; ++i
) {
1196 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1199 // Insert internal roles (take care to synchronize the implementation
1200 // with KFileItemModel::typeForRole() in case if a change is done).
1201 roles
.insert(IsDirRole
, "isDir");
1202 roles
.insert(IsLinkRole
, "isLink");
1203 roles
.insert(IsExpandedRole
, "isExpanded");
1204 roles
.insert(IsExpandableRole
, "isExpandable");
1205 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1207 Q_ASSERT(roles
.count() == RolesCount
);
1210 return roles
.value(roleType
);
1213 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
) const
1215 // It is important to insert only roles that are fast to retrieve. E.g.
1216 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1217 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1218 QHash
<QByteArray
, QVariant
> data
;
1219 data
.insert("url", item
.url());
1221 const bool isDir
= item
.isDir();
1222 if (m_requestRole
[IsDirRole
]) {
1223 data
.insert("isDir", isDir
);
1226 if (m_requestRole
[IsLinkRole
]) {
1227 const bool isLink
= item
.isLink();
1228 data
.insert("isLink", isLink
);
1231 if (m_requestRole
[NameRole
]) {
1232 data
.insert("text", item
.text());
1235 if (m_requestRole
[SizeRole
]) {
1237 data
.insert("size", QVariant());
1239 data
.insert("size", item
.size());
1243 if (m_requestRole
[DateRole
]) {
1244 // Don't use KFileItem::timeString() as this is too expensive when
1245 // having several thousands of items. Instead the formatting of the
1246 // date-time will be done on-demand by the view when the date will be shown.
1247 const KDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
1248 data
.insert("date", dateTime
.dateTime());
1251 if (m_requestRole
[PermissionsRole
]) {
1252 data
.insert("permissions", item
.permissionsString());
1255 if (m_requestRole
[OwnerRole
]) {
1256 data
.insert("owner", item
.user());
1259 if (m_requestRole
[GroupRole
]) {
1260 data
.insert("group", item
.group());
1263 if (m_requestRole
[DestinationRole
]) {
1264 QString destination
= item
.linkDest();
1265 if (destination
.isEmpty()) {
1266 destination
= QLatin1String("-");
1268 data
.insert("destination", destination
);
1271 if (m_requestRole
[PathRole
]) {
1273 if (item
.url().protocol() == QLatin1String("trash")) {
1274 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1276 // For performance reasons cache the home-path in a static QString
1277 // (see QDir::homePath() for more details)
1278 static QString homePath
;
1279 if (homePath
.isEmpty()) {
1280 homePath
= QDir::homePath();
1283 path
= item
.localPath();
1284 if (path
.startsWith(homePath
)) {
1285 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1289 const int index
= path
.lastIndexOf(item
.text());
1290 path
= path
.mid(0, index
- 1);
1291 data
.insert("path", path
);
1294 if (m_requestRole
[IsExpandedRole
]) {
1295 data
.insert("isExpanded", false);
1298 if (m_requestRole
[IsExpandableRole
]) {
1299 data
.insert("isExpandable", item
.isDir() && item
.url() == item
.targetUrl());
1302 if (m_requestRole
[ExpandedParentsCountRole
]) {
1303 if (m_expandedParentsCountRoot
== UninitializedExpandedParentsCountRoot
) {
1304 const KUrl rootUrl
= m_dirLister
->url();
1305 const QString protocol
= rootUrl
.protocol();
1306 const bool forceExpandedParentsCountRoot
= (protocol
== QLatin1String("trash") ||
1307 protocol
== QLatin1String("nepomuk") ||
1308 protocol
== QLatin1String("remote") ||
1309 protocol
.contains(QLatin1String("search")));
1310 if (forceExpandedParentsCountRoot
) {
1311 m_expandedParentsCountRoot
= ForceExpandedParentsCountRoot
;
1313 const QString rootDir
= rootUrl
.path(KUrl::AddTrailingSlash
);
1314 m_expandedParentsCountRoot
= rootDir
.count('/');
1318 if (m_expandedParentsCountRoot
== ForceExpandedParentsCountRoot
) {
1319 data
.insert("expandedParentsCount", -1);
1321 const QString dir
= item
.url().directory(KUrl::AppendTrailingSlash
);
1322 const int level
= dir
.count('/') - m_expandedParentsCountRoot
;
1323 data
.insert("expandedParentsCount", level
);
1327 if (item
.isMimeTypeKnown()) {
1328 data
.insert("iconName", item
.iconName());
1330 if (m_requestRole
[TypeRole
]) {
1331 data
.insert("type", item
.mimeComment());
1338 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
) const
1342 if (m_expandedParentsCountRoot
>= 0 && a
->parent
!= b
->parent
) {
1343 const int expansionLevelA
= a
->values
.value("expandedParentsCount").toInt();
1344 const int expansionLevelB
= b
->values
.value("expandedParentsCount").toInt();
1346 // If b has a higher expansion level than a, check if a is a parent
1347 // of b, and make sure that both expansion levels are equal otherwise.
1348 for (int i
= expansionLevelB
; i
> expansionLevelA
; --i
) {
1349 if (b
->parent
== a
) {
1355 // If a has a higher expansion level than a, check if b is a parent
1356 // of a, and make sure that both expansion levels are equal otherwise.
1357 for (int i
= expansionLevelA
; i
> expansionLevelB
; --i
) {
1358 if (a
->parent
== b
) {
1364 Q_ASSERT(a
->values
.value("expandedParentsCount").toInt() == b
->values
.value("expandedParentsCount").toInt());
1366 // Compare the last parents of a and b which are different.
1367 while (a
->parent
!= b
->parent
) {
1373 if (m_sortDirsFirst
|| m_sortRole
== SizeRole
) {
1374 const bool isDirA
= a
->item
.isDir();
1375 const bool isDirB
= b
->item
.isDir();
1376 if (isDirA
&& !isDirB
) {
1378 } else if (!isDirA
&& isDirB
) {
1383 result
= sortRoleCompare(a
, b
);
1385 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1389 * Helper class for KFileItemModel::sort().
1391 class KFileItemModelLessThan
1394 KFileItemModelLessThan(const KFileItemModel
* model
) :
1399 bool operator()(const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
) const
1401 return m_model
->lessThan(a
, b
);
1405 const KFileItemModel
* m_model
;
1408 void KFileItemModel::sort(QList
<KFileItemModel::ItemData
*>::iterator begin
,
1409 QList
<KFileItemModel::ItemData
*>::iterator end
) const
1411 KFileItemModelLessThan
lessThan(this);
1413 if (m_sortRole
== NameRole
) {
1414 // Sorting by name can be expensive, in particular if natural sorting is
1415 // enabled. Use all CPU cores to speed up the sorting process.
1416 static const int numberOfThreads
= QThread::idealThreadCount();
1417 parallelMergeSort(begin
, end
, lessThan
, numberOfThreads
);
1419 // Sorting by other roles is quite fast. Use only one thread to prevent
1420 // problems caused by non-reentrant comparison functions, see
1421 // https://bugs.kde.org/show_bug.cgi?id=312679
1422 mergeSort(begin
, end
, lessThan
);
1426 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
) const
1428 const KFileItem
& itemA
= a
->item
;
1429 const KFileItem
& itemB
= b
->item
;
1433 switch (m_sortRole
) {
1435 // The name role is handled as default fallback after the switch
1439 if (itemA
.isDir()) {
1440 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1441 Q_ASSERT(itemB
.isDir());
1443 const QVariant valueA
= a
->values
.value("size");
1444 const QVariant valueB
= b
->values
.value("size");
1445 if (valueA
.isNull() && valueB
.isNull()) {
1447 } else if (valueA
.isNull()) {
1449 } else if (valueB
.isNull()) {
1452 result
= valueA
.toInt() - valueB
.toInt();
1455 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1456 Q_ASSERT(!itemB
.isDir());
1457 const KIO::filesize_t sizeA
= itemA
.size();
1458 const KIO::filesize_t sizeB
= itemB
.size();
1459 if (sizeA
> sizeB
) {
1461 } else if (sizeA
< sizeB
) {
1471 const KDateTime dateTimeA
= itemA
.time(KFileItem::ModificationTime
);
1472 const KDateTime dateTimeB
= itemB
.time(KFileItem::ModificationTime
);
1473 if (dateTimeA
< dateTimeB
) {
1475 } else if (dateTimeA
> dateTimeB
) {
1482 result
= a
->values
.value("rating").toInt() - b
->values
.value("rating").toInt();
1486 case ImageSizeRole
: {
1487 // Alway use a natural comparing to interpret the numbers of a string like
1488 // "1600 x 1200" for having a correct sorting.
1489 result
= KStringHandler::naturalCompare(a
->values
.value("imageSize").toString(),
1490 b
->values
.value("imageSize").toString(),
1496 const QByteArray role
= roleForType(m_sortRole
);
1497 result
= QString::compare(a
->values
.value(role
).toString(),
1498 b
->values
.value(role
).toString());
1505 // The current sort role was sufficient to define an order
1509 // Fallback #1: Compare the text of the items
1510 result
= stringCompare(itemA
.text(), itemB
.text());
1515 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1516 result
= stringCompare(itemA
.name(m_caseSensitivity
== Qt::CaseInsensitive
),
1517 itemB
.name(m_caseSensitivity
== Qt::CaseInsensitive
));
1522 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1523 // equal. In this case a comparison of the URL is done which is unique in all cases
1524 // within KDirLister.
1525 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1528 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
) const
1530 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1531 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1532 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1533 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1535 if (m_caseSensitivity
== Qt::CaseInsensitive
) {
1536 const int result
= m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseInsensitive
)
1537 : QString::compare(a
, b
, Qt::CaseInsensitive
);
1539 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1540 // comparison, still a deterministic sort order is required. A case sensitive
1541 // comparison is done as fallback.
1546 return m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseSensitive
)
1547 : QString::compare(a
, b
, Qt::CaseSensitive
);
1550 bool KFileItemModel::useMaximumUpdateInterval() const
1552 return !m_dirLister
->url().isLocalFile();
1555 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1557 Q_ASSERT(!m_itemData
.isEmpty());
1559 const int maxIndex
= count() - 1;
1560 QList
<QPair
<int, QVariant
> > groups
;
1564 bool isLetter
= false;
1565 for (int i
= 0; i
<= maxIndex
; ++i
) {
1566 if (isChildItem(i
)) {
1570 const QString name
= m_itemData
.at(i
)->values
.value("text").toString();
1572 // Use the first character of the name as group indication
1573 QChar newFirstChar
= name
.at(0).toUpper();
1574 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1575 newFirstChar
= name
.at(1).toUpper();
1578 if (firstChar
!= newFirstChar
) {
1579 QString newGroupValue
;
1580 if (newFirstChar
>= QLatin1Char('A') && newFirstChar
<= QLatin1Char('Z')) {
1581 // Apply group 'A' - 'Z'
1582 newGroupValue
= newFirstChar
;
1584 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
1585 // Apply group '0 - 9' for any name that starts with a digit
1586 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
1590 // If the current group is 'A' - 'Z' check whether a locale character
1591 // fits into the existing group.
1592 // TODO: This does not work in the case if e.g. the group 'O' starts with
1593 // an umlaut 'O' -> provide unit-test to document this known issue
1594 const QChar
prevChar(firstChar
.unicode() - ushort(1));
1595 const QChar
nextChar(firstChar
.unicode() + ushort(1));
1596 const QString
currChar(newFirstChar
);
1597 const bool partOfCurrentGroup
= currChar
.localeAwareCompare(prevChar
) > 0 &&
1598 currChar
.localeAwareCompare(nextChar
) < 0;
1599 if (partOfCurrentGroup
) {
1603 newGroupValue
= i18nc("@title:group", "Others");
1607 if (newGroupValue
!= groupValue
) {
1608 groupValue
= newGroupValue
;
1609 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1612 firstChar
= newFirstChar
;
1618 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
1620 Q_ASSERT(!m_itemData
.isEmpty());
1622 const int maxIndex
= count() - 1;
1623 QList
<QPair
<int, QVariant
> > groups
;
1626 for (int i
= 0; i
<= maxIndex
; ++i
) {
1627 if (isChildItem(i
)) {
1631 const KFileItem
& item
= m_itemData
.at(i
)->item
;
1632 const KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
1633 QString newGroupValue
;
1634 if (!item
.isNull() && item
.isDir()) {
1635 newGroupValue
= i18nc("@title:group Size", "Folders");
1636 } else if (fileSize
< 5 * 1024 * 1024) {
1637 newGroupValue
= i18nc("@title:group Size", "Small");
1638 } else if (fileSize
< 10 * 1024 * 1024) {
1639 newGroupValue
= i18nc("@title:group Size", "Medium");
1641 newGroupValue
= i18nc("@title:group Size", "Big");
1644 if (newGroupValue
!= groupValue
) {
1645 groupValue
= newGroupValue
;
1646 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1653 QList
<QPair
<int, QVariant
> > KFileItemModel::dateRoleGroups() const
1655 Q_ASSERT(!m_itemData
.isEmpty());
1657 const int maxIndex
= count() - 1;
1658 QList
<QPair
<int, QVariant
> > groups
;
1660 const QDate currentDate
= KDateTime::currentLocalDateTime().date();
1662 int yearForCurrentWeek
= 0;
1663 int currentWeek
= currentDate
.weekNumber(&yearForCurrentWeek
);
1664 if (yearForCurrentWeek
== currentDate
.year() + 1) {
1668 QDate previousModifiedDate
;
1670 for (int i
= 0; i
<= maxIndex
; ++i
) {
1671 if (isChildItem(i
)) {
1675 const KDateTime modifiedTime
= m_itemData
.at(i
)->item
.time(KFileItem::ModificationTime
);
1676 const QDate modifiedDate
= modifiedTime
.date();
1677 if (modifiedDate
== previousModifiedDate
) {
1678 // The current item is in the same group as the previous item
1681 previousModifiedDate
= modifiedDate
;
1683 const int daysDistance
= modifiedDate
.daysTo(currentDate
);
1685 int yearForModifiedWeek
= 0;
1686 int modifiedWeek
= modifiedDate
.weekNumber(&yearForModifiedWeek
);
1687 if (yearForModifiedWeek
== modifiedDate
.year() + 1) {
1691 QString newGroupValue
;
1692 if (currentDate
.year() == modifiedDate
.year() && currentDate
.month() == modifiedDate
.month()) {
1693 if (modifiedWeek
> currentWeek
) {
1694 // Usecase: modified date = 2010-01-01, current date = 2010-01-22
1695 // modified week = 53, current week = 3
1698 switch (currentWeek
- modifiedWeek
) {
1700 switch (daysDistance
) {
1701 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
1702 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
1703 default: newGroupValue
= modifiedTime
.toString(i18nc("@title:group The week day name: %A", "%A"));
1707 newGroupValue
= i18nc("@title:group Date", "Last Week");
1710 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
1713 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
1717 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
1723 const QDate lastMonthDate
= currentDate
.addMonths(-1);
1724 if (lastMonthDate
.year() == modifiedDate
.year() && lastMonthDate
.month() == modifiedDate
.month()) {
1725 if (daysDistance
== 1) {
1726 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Yesterday (%B, %Y)"));
1727 } else if (daysDistance
<= 7) {
1728 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)"));
1729 } else if (daysDistance
<= 7 * 2) {
1730 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)"));
1731 } else if (daysDistance
<= 7 * 3) {
1732 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)"));
1733 } else if (daysDistance
<= 7 * 4) {
1734 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)"));
1736 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"));
1739 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"));
1743 if (newGroupValue
!= groupValue
) {
1744 groupValue
= newGroupValue
;
1745 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1752 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
1754 Q_ASSERT(!m_itemData
.isEmpty());
1756 const int maxIndex
= count() - 1;
1757 QList
<QPair
<int, QVariant
> > groups
;
1759 QString permissionsString
;
1761 for (int i
= 0; i
<= maxIndex
; ++i
) {
1762 if (isChildItem(i
)) {
1766 const ItemData
* itemData
= m_itemData
.at(i
);
1767 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
1768 if (newPermissionsString
== permissionsString
) {
1771 permissionsString
= newPermissionsString
;
1773 const QFileInfo
info(itemData
->item
.url().pathOrUrl());
1777 if (info
.permission(QFile::ReadUser
)) {
1778 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1780 if (info
.permission(QFile::WriteUser
)) {
1781 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1783 if (info
.permission(QFile::ExeUser
)) {
1784 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1786 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
1790 if (info
.permission(QFile::ReadGroup
)) {
1791 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1793 if (info
.permission(QFile::WriteGroup
)) {
1794 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1796 if (info
.permission(QFile::ExeGroup
)) {
1797 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1799 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
1801 // Set others string
1803 if (info
.permission(QFile::ReadOther
)) {
1804 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1806 if (info
.permission(QFile::WriteOther
)) {
1807 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1809 if (info
.permission(QFile::ExeOther
)) {
1810 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1812 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
1814 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
1815 if (newGroupValue
!= groupValue
) {
1816 groupValue
= newGroupValue
;
1817 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1824 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
1826 Q_ASSERT(!m_itemData
.isEmpty());
1828 const int maxIndex
= count() - 1;
1829 QList
<QPair
<int, QVariant
> > groups
;
1831 int groupValue
= -1;
1832 for (int i
= 0; i
<= maxIndex
; ++i
) {
1833 if (isChildItem(i
)) {
1836 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
1837 if (newGroupValue
!= groupValue
) {
1838 groupValue
= newGroupValue
;
1839 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1846 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
1848 Q_ASSERT(!m_itemData
.isEmpty());
1850 const int maxIndex
= count() - 1;
1851 QList
<QPair
<int, QVariant
> > groups
;
1853 bool isFirstGroupValue
= true;
1855 for (int i
= 0; i
<= maxIndex
; ++i
) {
1856 if (isChildItem(i
)) {
1859 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
1860 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
1861 groupValue
= newGroupValue
;
1862 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1863 isFirstGroupValue
= false;
1870 KFileItemList
KFileItemModel::childItems(const KFileItem
& item
) const
1872 KFileItemList items
;
1874 int index
= m_items
.value(item
.url(), -1);
1876 const int parentLevel
= m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt();
1878 while (index
< m_itemData
.count() && m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt() > parentLevel
) {
1879 items
.append(m_itemData
.at(index
)->item
);
1887 void KFileItemModel::emitSortProgress(int resolvedCount
)
1889 // Be tolerant against a resolvedCount with a wrong range.
1890 // Although there should not be a case where KFileItemModelRolesUpdater
1891 // (= caller) provides a wrong range, it is important to emit
1892 // a useful progress information even if there is an unexpected
1893 // implementation issue.
1895 const int itemCount
= count();
1896 if (resolvedCount
>= itemCount
) {
1897 m_sortingProgressPercent
= -1;
1898 if (m_resortAllItemsTimer
->isActive()) {
1899 m_resortAllItemsTimer
->stop();
1903 emit
directorySortingProgress(100);
1904 } else if (itemCount
> 0) {
1905 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
1907 const int progress
= resolvedCount
* 100 / itemCount
;
1908 if (m_sortingProgressPercent
!= progress
) {
1909 m_sortingProgressPercent
= progress
;
1910 emit
directorySortingProgress(progress
);
1915 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
1917 static const RoleInfoMap rolesInfoMap
[] = {
1918 // | role | roleType | role translation | group translation | requires Nepomuk | requires indexer
1919 { 0, NoRole
, 0, 0, 0, 0, false, false },
1920 { "text", NameRole
, I18N_NOOP2_NOSTRIP("@label", "Name"), 0, 0, false, false },
1921 { "size", SizeRole
, I18N_NOOP2_NOSTRIP("@label", "Size"), 0, 0, false, false },
1922 { "date", DateRole
, I18N_NOOP2_NOSTRIP("@label", "Date"), 0, 0, false, false },
1923 { "type", TypeRole
, I18N_NOOP2_NOSTRIP("@label", "Type"), 0, 0, false, false },
1924 { "rating", RatingRole
, I18N_NOOP2_NOSTRIP("@label", "Rating"), 0, 0, true, false },
1925 { "tags", TagsRole
, I18N_NOOP2_NOSTRIP("@label", "Tags"), 0, 0, true, false },
1926 { "comment", CommentRole
, I18N_NOOP2_NOSTRIP("@label", "Comment"), 0, 0, true, false },
1927 { "wordCount", WordCountRole
, I18N_NOOP2_NOSTRIP("@label", "Word Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
1928 { "lineCount", LineCountRole
, I18N_NOOP2_NOSTRIP("@label", "Line Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
1929 { "imageSize", ImageSizeRole
, I18N_NOOP2_NOSTRIP("@label", "Image Size"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
1930 { "orientation", OrientationRole
, I18N_NOOP2_NOSTRIP("@label", "Orientation"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
1931 { "artist", ArtistRole
, I18N_NOOP2_NOSTRIP("@label", "Artist"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1932 { "album", AlbumRole
, I18N_NOOP2_NOSTRIP("@label", "Album"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1933 { "duration", DurationRole
, I18N_NOOP2_NOSTRIP("@label", "Duration"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1934 { "track", TrackRole
, I18N_NOOP2_NOSTRIP("@label", "Track"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1935 { "path", PathRole
, I18N_NOOP2_NOSTRIP("@label", "Path"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1936 { "destination", DestinationRole
, I18N_NOOP2_NOSTRIP("@label", "Link Destination"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1937 { "copiedFrom", CopiedFromRole
, I18N_NOOP2_NOSTRIP("@label", "Copied From"), I18N_NOOP2_NOSTRIP("@label", "Other"), true, false },
1938 { "permissions", PermissionsRole
, I18N_NOOP2_NOSTRIP("@label", "Permissions"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1939 { "owner", OwnerRole
, I18N_NOOP2_NOSTRIP("@label", "Owner"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1940 { "group", GroupRole
, I18N_NOOP2_NOSTRIP("@label", "User Group"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1943 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
1944 return rolesInfoMap
;
1947 void KFileItemModel::determineMimeTypes(const KFileItemList
& items
, int timeout
)
1949 QElapsedTimer timer
;
1951 foreach (KFileItem item
, items
) { // krazy:exclude=foreach
1952 item
.determineMimeType();
1953 if (timer
.elapsed() > timeout
) {
1954 // Don't block the user interface, let the remaining items
1955 // be resolved asynchronously.
1961 bool KFileItemModel::isConsistent() const
1963 if (m_items
.count() != m_itemData
.count()) {
1967 for (int i
= 0; i
< count(); ++i
) {
1968 // Check if m_items and m_itemData are consistent.
1969 const KFileItem item
= fileItem(i
);
1970 if (item
.isNull()) {
1971 qWarning() << "Item" << i
<< "is null";
1975 const int itemIndex
= index(item
);
1976 if (itemIndex
!= i
) {
1977 qWarning() << "Item" << i
<< "has a wrong index:" << itemIndex
;
1981 // Check if the items are sorted correctly.
1982 if (i
> 0 && !lessThan(m_itemData
.at(i
- 1), m_itemData
.at(i
))) {
1983 qWarning() << "The order of items" << i
- 1 << "and" << i
<< "is wrong:"
1984 << fileItem(i
- 1) << fileItem(i
);
1988 // Check if all parent-child relationships are consistent.
1989 const ItemData
* data
= m_itemData
.at(i
);
1990 const ItemData
* parent
= data
->parent
;
1992 if (data
->values
.value("expandedParentsCount").toInt() != parent
->values
.value("expandedParentsCount").toInt() + 1) {
1993 qWarning() << "expandedParentsCount is inconsistent for parent" << parent
->item
<< "and child" << data
->item
;
1997 const int parentIndex
= index(parent
->item
);
1998 if (parentIndex
>= i
) {
1999 qWarning() << "Index" << parentIndex
<< "of parent" << parent
->item
<< "is not smaller than index" << i
<< "of child" << data
->item
;
2008 #include "kfileitemmodel.moc"