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>
39 // #define KFILEITEMMODEL_DEBUG
41 KFileItemModel::KFileItemModel(QObject
* parent
) :
42 KItemModelBase("text", parent
),
44 m_naturalSorting(KGlobalSettings::naturalSorting()),
45 m_sortDirsFirst(true),
47 m_sortingProgressPercent(-1),
49 m_caseSensitivity(Qt::CaseInsensitive
),
55 m_maximumUpdateIntervalTimer(0),
56 m_resortAllItemsTimer(0),
57 m_pendingItemsToInsert(),
59 m_expandedParentsCountRoot(UninitializedExpandedParentsCountRoot
),
63 m_dirLister
= new KFileItemModelDirLister(this);
64 m_dirLister
->setAutoUpdate(true);
65 m_dirLister
->setDelayedMimeTypes(true);
67 const QWidget
* parentWidget
= qobject_cast
<QWidget
*>(parent
);
69 m_dirLister
->setMainWindow(parentWidget
->window());
72 connect(m_dirLister
, SIGNAL(started(KUrl
)), this, SIGNAL(directoryLoadingStarted()));
73 connect(m_dirLister
, SIGNAL(canceled()), this, SLOT(slotCanceled()));
74 connect(m_dirLister
, SIGNAL(completed(KUrl
)), this, SLOT(slotCompleted()));
75 connect(m_dirLister
, SIGNAL(newItems(KFileItemList
)), this, SLOT(slotNewItems(KFileItemList
)));
76 connect(m_dirLister
, SIGNAL(itemsDeleted(KFileItemList
)), this, SLOT(slotItemsDeleted(KFileItemList
)));
77 connect(m_dirLister
, SIGNAL(refreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)), this, SLOT(slotRefreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)));
78 connect(m_dirLister
, SIGNAL(clear()), this, SLOT(slotClear()));
79 connect(m_dirLister
, SIGNAL(clear(KUrl
)), this, SLOT(slotClear(KUrl
)));
80 connect(m_dirLister
, SIGNAL(infoMessage(QString
)), this, SIGNAL(infoMessage(QString
)));
81 connect(m_dirLister
, SIGNAL(errorMessage(QString
)), this, SIGNAL(errorMessage(QString
)));
82 connect(m_dirLister
, SIGNAL(redirection(KUrl
,KUrl
)), this, SIGNAL(directoryRedirection(KUrl
,KUrl
)));
83 connect(m_dirLister
, SIGNAL(urlIsFileError(KUrl
)), this, SIGNAL(urlIsFileError(KUrl
)));
85 // Apply default roles that should be determined
87 m_requestRole
[NameRole
] = true;
88 m_requestRole
[IsDirRole
] = true;
89 m_requestRole
[IsLinkRole
] = true;
90 m_roles
.insert("text");
91 m_roles
.insert("isDir");
92 m_roles
.insert("isLink");
94 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
95 // before the completed() or canceled() signal has been emitted.
96 m_maximumUpdateIntervalTimer
= new QTimer(this);
97 m_maximumUpdateIntervalTimer
->setInterval(2000);
98 m_maximumUpdateIntervalTimer
->setSingleShot(true);
99 connect(m_maximumUpdateIntervalTimer
, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
101 // When changing the value of an item which represents the sort-role a resorting must be
102 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
103 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
104 // resorting is postponed until the timer has been exceeded.
105 m_resortAllItemsTimer
= new QTimer(this);
106 m_resortAllItemsTimer
->setInterval(500);
107 m_resortAllItemsTimer
->setSingleShot(true);
108 connect(m_resortAllItemsTimer
, SIGNAL(timeout()), this, SLOT(resortAllItems()));
110 connect(KGlobalSettings::self(), SIGNAL(naturalSortingChanged()), this, SLOT(slotNaturalSortingChanged()));
113 KFileItemModel::~KFileItemModel()
115 qDeleteAll(m_itemData
);
119 void KFileItemModel::loadDirectory(const KUrl
& url
)
121 m_dirLister
->openUrl(url
);
124 void KFileItemModel::refreshDirectory(const KUrl
& url
)
126 // Refresh all expanded directories first (Bug 295300)
127 foreach (const KUrl
& expandedUrl
, m_expandedDirs
) {
128 m_dirLister
->openUrl(expandedUrl
, KDirLister::Reload
);
131 m_dirLister
->openUrl(url
, KDirLister::Reload
);
134 KUrl
KFileItemModel::directory() const
136 return m_dirLister
->url();
139 void KFileItemModel::cancelDirectoryLoading()
144 int KFileItemModel::count() const
146 return m_itemData
.count();
149 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
151 if (index
>= 0 && index
< count()) {
152 return m_itemData
.at(index
)->values
;
154 return QHash
<QByteArray
, QVariant
>();
157 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
159 if (index
< 0 || index
>= count()) {
163 QHash
<QByteArray
, QVariant
> currentValues
= m_itemData
.at(index
)->values
;
165 // Determine which roles have been changed
166 QSet
<QByteArray
> changedRoles
;
167 QHashIterator
<QByteArray
, QVariant
> it(values
);
168 while (it
.hasNext()) {
170 const QByteArray role
= it
.key();
171 const QVariant value
= it
.value();
173 if (currentValues
[role
] != value
) {
174 currentValues
[role
] = value
;
175 changedRoles
.insert(role
);
179 if (changedRoles
.isEmpty()) {
183 m_itemData
[index
]->values
= currentValues
;
184 if (changedRoles
.contains("text")) {
185 KUrl url
= m_itemData
[index
]->item
.url();
186 url
.setFileName(currentValues
["text"].toString());
187 m_itemData
[index
]->item
.setUrl(url
);
190 emit
itemsChanged(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
192 if (changedRoles
.contains(sortRole())) {
193 m_resortAllItemsTimer
->start();
199 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
201 if (dirsFirst
!= m_sortDirsFirst
) {
202 m_sortDirsFirst
= dirsFirst
;
207 bool KFileItemModel::sortDirectoriesFirst() const
209 return m_sortDirsFirst
;
212 void KFileItemModel::setShowHiddenFiles(bool show
)
214 m_dirLister
->setShowingDotFiles(show
);
215 m_dirLister
->emitChanges();
221 bool KFileItemModel::showHiddenFiles() const
223 return m_dirLister
->showingDotFiles();
226 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
228 m_dirLister
->setDirOnlyMode(enabled
);
231 bool KFileItemModel::showDirectoriesOnly() const
233 return m_dirLister
->dirOnlyMode();
236 QMimeData
* KFileItemModel::createMimeData(const QSet
<int>& indexes
) const
238 QMimeData
* data
= new QMimeData();
240 // The following code has been taken from KDirModel::mimeData()
241 // (kdelibs/kio/kio/kdirmodel.cpp)
242 // Copyright (C) 2006 David Faure <faure@kde.org>
244 KUrl::List mostLocalUrls
;
245 bool canUseMostLocalUrls
= true;
247 QSetIterator
<int> it(indexes
);
248 while (it
.hasNext()) {
249 const int index
= it
.next();
250 const KFileItem item
= fileItem(index
);
251 if (!item
.isNull()) {
255 mostLocalUrls
<< item
.mostLocalUrl(isLocal
);
257 canUseMostLocalUrls
= false;
262 const bool different
= canUseMostLocalUrls
&& mostLocalUrls
!= urls
;
263 urls
= KDirModel::simplifiedUrlList(urls
); // TODO: Check if we still need KDirModel for this in KDE 5.0
265 mostLocalUrls
= KDirModel::simplifiedUrlList(mostLocalUrls
);
266 urls
.populateMimeData(mostLocalUrls
, data
);
268 urls
.populateMimeData(data
);
274 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
276 startFromIndex
= qMax(0, startFromIndex
);
277 for (int i
= startFromIndex
; i
< count(); ++i
) {
278 if (data(i
)["text"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
282 for (int i
= 0; i
< startFromIndex
; ++i
) {
283 if (data(i
)["text"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
290 bool KFileItemModel::supportsDropping(int index
) const
292 const KFileItem item
= fileItem(index
);
293 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
296 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
298 static QHash
<QByteArray
, QString
> description
;
299 if (description
.isEmpty()) {
301 const RoleInfoMap
* map
= rolesInfoMap(count
);
302 for (int i
= 0; i
< count
; ++i
) {
303 description
.insert(map
[i
].role
, i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
));
307 return description
.value(role
);
310 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
312 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
313 #ifdef KFILEITEMMODEL_DEBUG
317 switch (typeForRole(sortRole())) {
318 case NameRole
: m_groups
= nameRoleGroups(); break;
319 case SizeRole
: m_groups
= sizeRoleGroups(); break;
320 case DateRole
: m_groups
= dateRoleGroups(); break;
321 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
322 case RatingRole
: m_groups
= ratingRoleGroups(); break;
323 default: m_groups
= genericStringRoleGroups(sortRole()); break;
326 #ifdef KFILEITEMMODEL_DEBUG
327 kDebug() << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
334 KFileItem
KFileItemModel::fileItem(int index
) const
336 if (index
>= 0 && index
< count()) {
337 return m_itemData
.at(index
)->item
;
343 KFileItem
KFileItemModel::fileItem(const KUrl
& url
) const
345 const int index
= m_items
.value(url
, -1);
347 return m_itemData
.at(index
)->item
;
352 int KFileItemModel::index(const KFileItem
& item
) const
358 return m_items
.value(item
.url(), -1);
361 int KFileItemModel::index(const KUrl
& url
) const
363 KUrl urlToFind
= url
;
364 urlToFind
.adjustPath(KUrl::RemoveTrailingSlash
);
365 return m_items
.value(urlToFind
, -1);
368 KFileItem
KFileItemModel::rootItem() const
370 return m_dirLister
->rootItem();
373 void KFileItemModel::clear()
378 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
380 if (m_roles
== roles
) {
386 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
387 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
388 if (supportedExpanding
&& !willSupportExpanding
) {
389 // No expanding is supported anymore. Take care to delete all items that have an expansion level
390 // that is not 0 (and hence are part of an expanded item).
391 removeExpandedItems();
398 QSetIterator
<QByteArray
> it(roles
);
399 while (it
.hasNext()) {
400 const QByteArray
& role
= it
.next();
401 m_requestRole
[typeForRole(role
)] = true;
405 // Update m_data with the changed requested roles
406 const int maxIndex
= count() - 1;
407 for (int i
= 0; i
<= maxIndex
; ++i
) {
408 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
);
411 kWarning() << "TODO: Emitting itemsChanged() with no information what has changed!";
412 emit
itemsChanged(KItemRangeList() << KItemRange(0, count()), QSet
<QByteArray
>());
416 QSet
<QByteArray
> KFileItemModel::roles() const
421 bool KFileItemModel::setExpanded(int index
, bool expanded
)
423 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
427 QHash
<QByteArray
, QVariant
> values
;
428 values
.insert("isExpanded", expanded
);
429 if (!setData(index
, values
)) {
433 const KUrl url
= m_itemData
.at(index
)->item
.url();
435 m_expandedDirs
.insert(url
);
436 m_dirLister
->openUrl(url
, KDirLister::Keep
);
438 m_expandedDirs
.remove(url
);
439 m_dirLister
->stop(url
);
442 KFileItemList itemsToRemove
;
443 const int expandedParentsCount
= data(index
)["expandedParentsCount"].toInt();
445 while (index
< count() && data(index
)["expandedParentsCount"].toInt() > expandedParentsCount
) {
446 itemsToRemove
.append(m_itemData
.at(index
)->item
);
450 QSet
<KUrl
> urlsToRemove
;
451 urlsToRemove
.reserve(itemsToRemove
.count() + 1);
452 urlsToRemove
.insert(url
);
453 foreach (const KFileItem
& item
, itemsToRemove
) {
454 KUrl url
= item
.url();
455 url
.adjustPath(KUrl::RemoveTrailingSlash
);
456 urlsToRemove
.insert(url
);
459 QSet
<KFileItem
>::iterator it
= m_filteredItems
.begin();
460 while (it
!= m_filteredItems
.end()) {
461 const KUrl url
= it
->url();
462 KUrl parentUrl
= url
.upUrl();
463 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
465 if (urlsToRemove
.contains(parentUrl
)) {
466 it
= m_filteredItems
.erase(it
);
472 removeItems(itemsToRemove
);
478 bool KFileItemModel::isExpanded(int index
) const
480 if (index
>= 0 && index
< count()) {
481 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
486 bool KFileItemModel::isExpandable(int index
) const
488 if (index
>= 0 && index
< count()) {
489 return m_itemData
.at(index
)->values
.value("isExpandable").toBool();
494 int KFileItemModel::expandedParentsCount(int index
) const
496 if (index
>= 0 && index
< count()) {
497 const int parentsCount
= m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt();
498 if (parentsCount
> 0) {
505 QSet
<KUrl
> KFileItemModel::expandedDirectories() const
507 return m_expandedDirs
;
510 void KFileItemModel::restoreExpandedDirectories(const QSet
<KUrl
>& urls
)
512 m_urlsToExpand
= urls
;
515 void KFileItemModel::expandParentDirectories(const KUrl
& url
)
517 const int pos
= m_dirLister
->url().path().length();
519 // Assure that each sub-path of the URL that should be
520 // expanded is added to m_urlsToExpand. KDirLister
521 // does not care whether the parent-URL has already been
523 KUrl urlToExpand
= m_dirLister
->url();
524 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator());
525 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
526 urlToExpand
.addPath(subDirs
.at(i
));
527 m_urlsToExpand
.insert(urlToExpand
);
530 // KDirLister::open() must called at least once to trigger an initial
531 // loading. The pending URLs that must be restored are handled
532 // in slotCompleted().
533 QSetIterator
<KUrl
> it2(m_urlsToExpand
);
534 while (it2
.hasNext()) {
535 const int idx
= index(it2
.next());
536 if (idx
>= 0 && !isExpanded(idx
)) {
537 setExpanded(idx
, true);
543 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
545 if (m_filter
.pattern() != nameFilter
) {
546 dispatchPendingItemsToInsert();
547 m_filter
.setPattern(nameFilter
);
552 QString
KFileItemModel::nameFilter() const
554 return m_filter
.pattern();
557 void KFileItemModel::setMimeTypeFilters(const QStringList
& filters
)
559 if (m_filter
.mimeTypes() != filters
) {
560 dispatchPendingItemsToInsert();
561 m_filter
.setMimeTypes(filters
);
566 QStringList
KFileItemModel::mimeTypeFilters() const
568 return m_filter
.mimeTypes();
572 void KFileItemModel::applyFilters()
574 // Check which shown items from m_itemData must get
575 // hidden and hence moved to m_filteredItems.
576 KFileItemList newFilteredItems
;
578 foreach (ItemData
* itemData
, m_itemData
) {
579 // Only filter non-expanded items as child items may never
580 // exist without a parent item
581 if (!itemData
->values
.value("isExpanded").toBool()) {
582 if (!m_filter
.matches(itemData
->item
)) {
583 newFilteredItems
.append(itemData
->item
);
584 m_filteredItems
.insert(itemData
->item
);
589 removeItems(newFilteredItems
);
591 // Check which hidden items from m_filteredItems should
592 // get visible again and hence removed from m_filteredItems.
593 KFileItemList newVisibleItems
;
595 QMutableSetIterator
<KFileItem
> it(m_filteredItems
);
596 while (it
.hasNext()) {
597 const KFileItem item
= it
.next();
598 if (m_filter
.matches(item
)) {
599 newVisibleItems
.append(item
);
604 insertItems(newVisibleItems
);
607 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
609 static QList
<RoleInfo
> rolesInfo
;
610 if (rolesInfo
.isEmpty()) {
612 const RoleInfoMap
* map
= rolesInfoMap(count
);
613 for (int i
= 0; i
< count
; ++i
) {
614 if (map
[i
].roleType
!= NoRole
) {
616 info
.role
= map
[i
].role
;
617 info
.translation
= i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
);
618 if (map
[i
].groupTranslation
) {
619 info
.group
= i18nc(map
[i
].groupTranslationContext
, map
[i
].groupTranslation
);
621 // For top level roles, groupTranslation is 0. We must make sure that
622 // info.group is an empty string then because the code that generates
623 // menus tries to put the actions into sub menus otherwise.
624 info
.group
= QString();
626 info
.requiresNepomuk
= map
[i
].requiresNepomuk
;
627 info
.requiresIndexer
= map
[i
].requiresIndexer
;
628 rolesInfo
.append(info
);
636 void KFileItemModel::onGroupedSortingChanged(bool current
)
642 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
645 m_sortRole
= typeForRole(current
);
647 if (!m_requestRole
[m_sortRole
]) {
648 QSet
<QByteArray
> newRoles
= m_roles
;
656 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
663 void KFileItemModel::resortAllItems()
665 m_resortAllItemsTimer
->stop();
667 const int itemCount
= count();
668 if (itemCount
<= 0) {
672 #ifdef KFILEITEMMODEL_DEBUG
675 kDebug() << "===========================================================";
676 kDebug() << "Resorting" << itemCount
<< "items";
679 // Remember the order of the current URLs so
680 // that it can be determined which indexes have
681 // been moved because of the resorting.
683 oldUrls
.reserve(itemCount
);
684 foreach (const ItemData
* itemData
, m_itemData
) {
685 oldUrls
.append(itemData
->item
.url());
692 KFileItemModelSortAlgorithm::sort(this, m_itemData
.begin(), m_itemData
.end());
693 for (int i
= 0; i
< itemCount
; ++i
) {
694 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
697 // Determine the indexes that have been moved
698 QList
<int> movedToIndexes
;
699 movedToIndexes
.reserve(itemCount
);
700 for (int i
= 0; i
< itemCount
; i
++) {
701 const int newIndex
= m_items
.value(oldUrls
.at(i
).url());
702 movedToIndexes
.append(newIndex
);
705 // Don't check whether items have really been moved and always emit a
706 // itemsMoved() signal after resorting: In case of grouped items
707 // the groups might change even if the items themselves don't change their
708 // position. Let the receiver of the signal decide whether a check for moved
709 // items makes sense.
710 emit
itemsMoved(KItemRange(0, itemCount
), movedToIndexes
);
712 #ifdef KFILEITEMMODEL_DEBUG
713 kDebug() << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
717 void KFileItemModel::slotCompleted()
719 dispatchPendingItemsToInsert();
721 if (!m_urlsToExpand
.isEmpty()) {
722 // Try to find a URL that can be expanded.
723 // Note that the parent folder must be expanded before any of its subfolders become visible.
724 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
725 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
726 foreach (const KUrl
& url
, m_urlsToExpand
) {
727 const int index
= m_items
.value(url
, -1);
729 m_urlsToExpand
.remove(url
);
730 if (setExpanded(index
, true)) {
731 // The dir lister has been triggered. This slot will be called
732 // again after the directory has been expanded.
738 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
739 // if these URLs have been deleted in the meantime.
740 m_urlsToExpand
.clear();
743 emit
directoryLoadingCompleted();
746 void KFileItemModel::slotCanceled()
748 m_maximumUpdateIntervalTimer
->stop();
749 dispatchPendingItemsToInsert();
751 emit
directoryLoadingCanceled();
754 void KFileItemModel::slotNewItems(const KFileItemList
& items
)
756 Q_ASSERT(!items
.isEmpty());
758 if (m_requestRole
[ExpandedParentsCountRole
] && m_expandedParentsCountRoot
>= 0) {
759 // To be able to compare whether the new items may be inserted as children
760 // of a parent item the pending items must be added to the model first.
761 dispatchPendingItemsToInsert();
763 KFileItem item
= items
.first();
765 // If the expanding of items is enabled, the call
766 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
767 // might result in emitting the same items twice due to the Keep-parameter.
768 // This case happens if an item gets expanded, collapsed and expanded again
769 // before the items could be loaded for the first expansion.
770 const int index
= m_items
.value(item
.url(), -1);
772 // The items are already part of the model.
776 // KDirLister keeps the children of items that got expanded once even if
777 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
778 // checked whether the parent for new items is still expanded.
779 KUrl parentUrl
= item
.url().upUrl();
780 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
781 const int parentIndex
= m_items
.value(parentUrl
, -1);
782 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
783 // The parent is not expanded.
788 if (!m_filter
.hasSetFilters()) {
789 m_pendingItemsToInsert
.append(items
);
791 // The name or type filter is active. Hide filtered items
792 // before inserting them into the model and remember
793 // the filtered items in m_filteredItems.
794 KFileItemList filteredItems
;
795 foreach (const KFileItem
& item
, items
) {
796 if (m_filter
.matches(item
)) {
797 filteredItems
.append(item
);
799 m_filteredItems
.insert(item
);
803 m_pendingItemsToInsert
.append(filteredItems
);
806 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer
->isActive()) {
807 // Assure that items get dispatched if no completed() or canceled() signal is
808 // emitted during the maximum update interval.
809 m_maximumUpdateIntervalTimer
->start();
813 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
815 dispatchPendingItemsToInsert();
817 KFileItemList itemsToRemove
= items
;
818 if (m_requestRole
[ExpandedParentsCountRole
] && m_expandedParentsCountRoot
>= 0) {
819 // Assure that removing a parent item also results in removing all children
820 foreach (const KFileItem
& item
, items
) {
821 itemsToRemove
.append(childItems(item
));
825 if (!m_filteredItems
.isEmpty()) {
826 foreach (const KFileItem
& item
, itemsToRemove
) {
827 m_filteredItems
.remove(item
);
830 if (m_requestRole
[ExpandedParentsCountRole
] && m_expandedParentsCountRoot
>= 0) {
831 // Remove all filtered children of deleted items. First, we put the
832 // deleted URLs into a set to provide fast lookup while iterating
833 // over m_filteredItems and prevent quadratic complexity if there
834 // are N removed items and N filtered items.
835 QSet
<KUrl
> urlsToRemove
;
836 urlsToRemove
.reserve(itemsToRemove
.count());
837 foreach (const KFileItem
& item
, itemsToRemove
) {
838 KUrl url
= item
.url();
839 url
.adjustPath(KUrl::RemoveTrailingSlash
);
840 urlsToRemove
.insert(url
);
843 QSet
<KFileItem
>::iterator it
= m_filteredItems
.begin();
844 while (it
!= m_filteredItems
.end()) {
845 const KUrl url
= it
->url();
846 KUrl parentUrl
= url
.upUrl();
847 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
849 if (urlsToRemove
.contains(parentUrl
)) {
850 it
= m_filteredItems
.erase(it
);
858 removeItems(itemsToRemove
);
861 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
863 Q_ASSERT(!items
.isEmpty());
864 #ifdef KFILEITEMMODEL_DEBUG
865 kDebug() << "Refreshing" << items
.count() << "items";
870 // Get the indexes of all items that have been refreshed
872 indexes
.reserve(items
.count());
874 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
875 while (it
.hasNext()) {
876 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
877 const KFileItem
& oldItem
= itemPair
.first
;
878 const KFileItem
& newItem
= itemPair
.second
;
879 const int index
= m_items
.value(oldItem
.url(), -1);
881 m_itemData
[index
]->item
= newItem
;
883 // Keep old values as long as possible if they could not retrieved synchronously yet.
884 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
885 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
));
886 while (it
.hasNext()) {
888 m_itemData
[index
]->values
.insert(it
.key(), it
.value());
891 m_items
.remove(oldItem
.url());
892 m_items
.insert(newItem
.url(), index
);
893 indexes
.append(index
);
897 // If the changed items have been created recently, they might not be in m_items yet.
898 // In that case, the list 'indexes' might be empty.
899 if (indexes
.isEmpty()) {
903 // Extract the item-ranges out of the changed indexes
906 KItemRangeList itemRangeList
;
907 int previousIndex
= indexes
.at(0);
908 int rangeIndex
= previousIndex
;
911 const int maxIndex
= indexes
.count() - 1;
912 for (int i
= 1; i
<= maxIndex
; ++i
) {
913 const int currentIndex
= indexes
.at(i
);
914 if (currentIndex
== previousIndex
+ 1) {
917 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
919 rangeIndex
= currentIndex
;
922 previousIndex
= currentIndex
;
925 if (rangeCount
> 0) {
926 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
929 emit
itemsChanged(itemRangeList
, m_roles
);
934 void KFileItemModel::slotClear()
936 #ifdef KFILEITEMMODEL_DEBUG
937 kDebug() << "Clearing all items";
940 m_filteredItems
.clear();
943 m_maximumUpdateIntervalTimer
->stop();
944 m_resortAllItemsTimer
->stop();
945 m_pendingItemsToInsert
.clear();
947 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
949 const int removedCount
= m_itemData
.count();
950 if (removedCount
> 0) {
951 qDeleteAll(m_itemData
);
954 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
957 m_expandedDirs
.clear();
960 void KFileItemModel::slotClear(const KUrl
& url
)
965 void KFileItemModel::slotNaturalSortingChanged()
967 m_naturalSorting
= KGlobalSettings::naturalSorting();
971 void KFileItemModel::dispatchPendingItemsToInsert()
973 if (!m_pendingItemsToInsert
.isEmpty()) {
974 insertItems(m_pendingItemsToInsert
);
975 m_pendingItemsToInsert
.clear();
979 void KFileItemModel::insertItems(const KFileItemList
& items
)
981 if (items
.isEmpty()) {
985 if (m_sortRole
== TypeRole
) {
986 // Try to resolve the MIME-types synchronously to prevent a reordering of
987 // the items when sorting by type (per default MIME-types are resolved
988 // asynchronously by KFileItemModelRolesUpdater).
989 determineMimeTypes(items
, 200);
992 #ifdef KFILEITEMMODEL_DEBUG
995 kDebug() << "===========================================================";
996 kDebug() << "Inserting" << items
.count() << "items";
1001 QList
<ItemData
*> sortedItems
= createItemDataList(items
);
1002 KFileItemModelSortAlgorithm::sort(this, sortedItems
.begin(), sortedItems
.end());
1004 #ifdef KFILEITEMMODEL_DEBUG
1005 kDebug() << "[TIME] Sorting:" << timer
.elapsed();
1008 KItemRangeList itemRanges
;
1009 int targetIndex
= 0;
1010 int sourceIndex
= 0;
1011 int insertedAtIndex
= -1; // Index for the current item-range
1012 int insertedCount
= 0; // Count for the current item-range
1013 int previouslyInsertedCount
= 0; // Sum of previously inserted items for all ranges
1014 while (sourceIndex
< sortedItems
.count()) {
1015 // Find target index from m_items to insert the current item
1016 // in a sorted order
1017 const int previousTargetIndex
= targetIndex
;
1018 while (targetIndex
< m_itemData
.count()) {
1019 if (!lessThan(m_itemData
.at(targetIndex
), sortedItems
.at(sourceIndex
))) {
1025 if (targetIndex
- previousTargetIndex
> 0 && insertedAtIndex
>= 0) {
1026 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
1027 previouslyInsertedCount
+= insertedCount
;
1028 insertedAtIndex
= targetIndex
- previouslyInsertedCount
;
1032 // Insert item at the position targetIndex by transferring
1033 // the ownership of the item-data from sortedItems to m_itemData.
1034 // m_items will be inserted after the loop (see comment below)
1035 m_itemData
.insert(targetIndex
, sortedItems
.at(sourceIndex
));
1038 if (insertedAtIndex
< 0) {
1039 insertedAtIndex
= targetIndex
;
1040 Q_ASSERT(previouslyInsertedCount
== 0);
1046 // The indexes of all m_items must be adjusted, not only the index
1048 const int itemDataCount
= m_itemData
.count();
1049 for (int i
= 0; i
< itemDataCount
; ++i
) {
1050 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
1053 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
1054 emit
itemsInserted(itemRanges
);
1056 #ifdef KFILEITEMMODEL_DEBUG
1057 kDebug() << "[TIME] Inserting of" << items
.count() << "items:" << timer
.elapsed();
1061 void KFileItemModel::removeItems(const KFileItemList
& items
)
1063 if (items
.isEmpty()) {
1067 #ifdef KFILEITEMMODEL_DEBUG
1068 kDebug() << "Removing " << items
.count() << "items";
1073 QList
<ItemData
*> sortedItems
;
1074 sortedItems
.reserve(items
.count());
1075 foreach (const KFileItem
& item
, items
) {
1076 const int index
= m_items
.value(item
.url(), -1);
1078 sortedItems
.append(m_itemData
.at(index
));
1081 KFileItemModelSortAlgorithm::sort(this, sortedItems
.begin(), sortedItems
.end());
1083 QList
<int> indexesToRemove
;
1084 indexesToRemove
.reserve(items
.count());
1086 // Calculate the item ranges that will get deleted
1087 KItemRangeList itemRanges
;
1088 int removedAtIndex
= -1;
1089 int removedCount
= 0;
1090 int targetIndex
= 0;
1091 foreach (const ItemData
* itemData
, sortedItems
) {
1092 const KFileItem
& itemToRemove
= itemData
->item
;
1094 const int previousTargetIndex
= targetIndex
;
1095 while (targetIndex
< m_itemData
.count()) {
1096 if (m_itemData
.at(targetIndex
)->item
.url() == itemToRemove
.url()) {
1101 if (targetIndex
>= m_itemData
.count()) {
1102 kWarning() << "Item that should be deleted has not been found!";
1106 if (targetIndex
- previousTargetIndex
> 0 && removedAtIndex
>= 0) {
1107 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
1108 removedAtIndex
= targetIndex
;
1112 indexesToRemove
.append(targetIndex
);
1113 if (removedAtIndex
< 0) {
1114 removedAtIndex
= targetIndex
;
1121 for (int i
= indexesToRemove
.count() - 1; i
>= 0; --i
) {
1122 const int indexToRemove
= indexesToRemove
.at(i
);
1123 ItemData
* data
= m_itemData
.at(indexToRemove
);
1125 m_items
.remove(data
->item
.url());
1128 m_itemData
.removeAt(indexToRemove
);
1131 // The indexes of all m_items must be adjusted, not only the index
1132 // of the removed items
1133 const int itemDataCount
= m_itemData
.count();
1134 for (int i
= 0; i
< itemDataCount
; ++i
) {
1135 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
1139 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
1142 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
1143 emit
itemsRemoved(itemRanges
);
1146 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const KFileItemList
& items
) const
1148 QList
<ItemData
*> itemDataList
;
1149 itemDataList
.reserve(items
.count());
1151 foreach (const KFileItem
& item
, items
) {
1152 ItemData
* itemData
= new ItemData();
1153 itemData
->item
= item
;
1154 itemData
->values
= retrieveData(item
);
1155 itemData
->parent
= 0;
1157 const bool determineParent
= m_requestRole
[ExpandedParentsCountRole
]
1158 && itemData
->values
["expandedParentsCount"].toInt() > 0;
1159 if (determineParent
) {
1160 KUrl parentUrl
= item
.url().upUrl();
1161 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
1162 const int parentIndex
= m_items
.value(parentUrl
, -1);
1163 if (parentIndex
>= 0) {
1164 itemData
->parent
= m_itemData
.at(parentIndex
);
1166 kWarning() << "Parent item not found for" << item
.url();
1170 itemDataList
.append(itemData
);
1173 return itemDataList
;
1176 void KFileItemModel::removeExpandedItems()
1178 KFileItemList expandedItems
;
1180 const int maxIndex
= m_itemData
.count() - 1;
1181 for (int i
= 0; i
<= maxIndex
; ++i
) {
1182 const ItemData
* itemData
= m_itemData
.at(i
);
1183 if (itemData
->values
.value("expandedParentsCount").toInt() > 0) {
1184 expandedItems
.append(itemData
->item
);
1188 // The m_expandedParentsCountRoot may not get reset before all items with
1189 // a bigger count have been removed.
1190 removeItems(expandedItems
);
1192 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
1193 m_expandedDirs
.clear();
1196 void KFileItemModel::resetRoles()
1198 for (int i
= 0; i
< RolesCount
; ++i
) {
1199 m_requestRole
[i
] = false;
1203 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1205 static QHash
<QByteArray
, RoleType
> roles
;
1206 if (roles
.isEmpty()) {
1207 // Insert user visible roles that can be accessed with
1208 // KFileItemModel::roleInformation()
1210 const RoleInfoMap
* map
= rolesInfoMap(count
);
1211 for (int i
= 0; i
< count
; ++i
) {
1212 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1215 // Insert internal roles (take care to synchronize the implementation
1216 // with KFileItemModel::roleForType() in case if a change is done).
1217 roles
.insert("isDir", IsDirRole
);
1218 roles
.insert("isLink", IsLinkRole
);
1219 roles
.insert("isExpanded", IsExpandedRole
);
1220 roles
.insert("isExpandable", IsExpandableRole
);
1221 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1223 Q_ASSERT(roles
.count() == RolesCount
);
1226 return roles
.value(role
, NoRole
);
1229 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1231 static QHash
<RoleType
, QByteArray
> roles
;
1232 if (roles
.isEmpty()) {
1233 // Insert user visible roles that can be accessed with
1234 // KFileItemModel::roleInformation()
1236 const RoleInfoMap
* map
= rolesInfoMap(count
);
1237 for (int i
= 0; i
< count
; ++i
) {
1238 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1241 // Insert internal roles (take care to synchronize the implementation
1242 // with KFileItemModel::typeForRole() in case if a change is done).
1243 roles
.insert(IsDirRole
, "isDir");
1244 roles
.insert(IsLinkRole
, "isLink");
1245 roles
.insert(IsExpandedRole
, "isExpanded");
1246 roles
.insert(IsExpandableRole
, "isExpandable");
1247 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1249 Q_ASSERT(roles
.count() == RolesCount
);
1252 return roles
.value(roleType
);
1255 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
) const
1257 // It is important to insert only roles that are fast to retrieve. E.g.
1258 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1259 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1260 QHash
<QByteArray
, QVariant
> data
;
1261 data
.insert("url", item
.url());
1263 const bool isDir
= item
.isDir();
1264 if (m_requestRole
[IsDirRole
]) {
1265 data
.insert("isDir", isDir
);
1268 if (m_requestRole
[IsLinkRole
]) {
1269 const bool isLink
= item
.isLink();
1270 data
.insert("isLink", isLink
);
1273 if (m_requestRole
[NameRole
]) {
1274 data
.insert("text", item
.text());
1277 if (m_requestRole
[SizeRole
]) {
1279 data
.insert("size", QVariant());
1281 data
.insert("size", item
.size());
1285 if (m_requestRole
[DateRole
]) {
1286 // Don't use KFileItem::timeString() as this is too expensive when
1287 // having several thousands of items. Instead the formatting of the
1288 // date-time will be done on-demand by the view when the date will be shown.
1289 const KDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
1290 data
.insert("date", dateTime
.dateTime());
1293 if (m_requestRole
[PermissionsRole
]) {
1294 data
.insert("permissions", item
.permissionsString());
1297 if (m_requestRole
[OwnerRole
]) {
1298 data
.insert("owner", item
.user());
1301 if (m_requestRole
[GroupRole
]) {
1302 data
.insert("group", item
.group());
1305 if (m_requestRole
[DestinationRole
]) {
1306 QString destination
= item
.linkDest();
1307 if (destination
.isEmpty()) {
1308 destination
= QLatin1String("-");
1310 data
.insert("destination", destination
);
1313 if (m_requestRole
[PathRole
]) {
1315 if (item
.url().protocol() == QLatin1String("trash")) {
1316 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1318 // For performance reasons cache the home-path in a static QString
1319 // (see QDir::homePath() for more details)
1320 static QString homePath
;
1321 if (homePath
.isEmpty()) {
1322 homePath
= QDir::homePath();
1325 path
= item
.localPath();
1326 if (path
.startsWith(homePath
)) {
1327 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1331 const int index
= path
.lastIndexOf(item
.text());
1332 path
= path
.mid(0, index
- 1);
1333 data
.insert("path", path
);
1336 if (m_requestRole
[IsExpandableRole
]) {
1337 data
.insert("isExpandable", item
.isDir() && item
.url() == item
.targetUrl());
1340 if (m_requestRole
[ExpandedParentsCountRole
]) {
1341 if (m_expandedParentsCountRoot
== UninitializedExpandedParentsCountRoot
) {
1342 const KUrl rootUrl
= m_dirLister
->url();
1343 const QString protocol
= rootUrl
.protocol();
1344 const bool forceExpandedParentsCountRoot
= (protocol
== QLatin1String("trash") ||
1345 protocol
== QLatin1String("nepomuk") ||
1346 protocol
== QLatin1String("remote") ||
1347 protocol
.contains(QLatin1String("search")));
1348 if (forceExpandedParentsCountRoot
) {
1349 m_expandedParentsCountRoot
= ForceExpandedParentsCountRoot
;
1351 const QString rootDir
= rootUrl
.path(KUrl::AddTrailingSlash
);
1352 m_expandedParentsCountRoot
= rootDir
.count('/');
1356 if (m_expandedParentsCountRoot
== ForceExpandedParentsCountRoot
) {
1357 data
.insert("expandedParentsCount", -1);
1359 const QString dir
= item
.url().directory(KUrl::AppendTrailingSlash
);
1360 const int level
= dir
.count('/') - m_expandedParentsCountRoot
;
1361 data
.insert("expandedParentsCount", level
);
1365 if (item
.isMimeTypeKnown()) {
1366 data
.insert("iconName", item
.iconName());
1368 if (m_requestRole
[TypeRole
]) {
1369 data
.insert("type", item
.mimeComment());
1376 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
) const
1380 if (m_expandedParentsCountRoot
>= 0) {
1381 result
= expandedParentsCountCompare(a
, b
);
1383 // The items have parents with different expansion levels
1384 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1388 if (m_sortDirsFirst
|| m_sortRole
== SizeRole
) {
1389 const bool isDirA
= a
->item
.isDir();
1390 const bool isDirB
= b
->item
.isDir();
1391 if (isDirA
&& !isDirB
) {
1393 } else if (!isDirA
&& isDirB
) {
1398 result
= sortRoleCompare(a
, b
);
1400 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1403 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
) const
1405 const KFileItem
& itemA
= a
->item
;
1406 const KFileItem
& itemB
= b
->item
;
1410 switch (m_sortRole
) {
1412 // The name role is handled as default fallback after the switch
1416 if (itemA
.isDir()) {
1417 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1418 Q_ASSERT(itemB
.isDir());
1420 const QVariant valueA
= a
->values
.value("size");
1421 const QVariant valueB
= b
->values
.value("size");
1422 if (valueA
.isNull() && valueB
.isNull()) {
1424 } else if (valueA
.isNull()) {
1426 } else if (valueB
.isNull()) {
1429 result
= valueA
.toInt() - valueB
.toInt();
1432 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1433 Q_ASSERT(!itemB
.isDir());
1434 const KIO::filesize_t sizeA
= itemA
.size();
1435 const KIO::filesize_t sizeB
= itemB
.size();
1436 if (sizeA
> sizeB
) {
1438 } else if (sizeA
< sizeB
) {
1448 const KDateTime dateTimeA
= itemA
.time(KFileItem::ModificationTime
);
1449 const KDateTime dateTimeB
= itemB
.time(KFileItem::ModificationTime
);
1450 if (dateTimeA
< dateTimeB
) {
1452 } else if (dateTimeA
> dateTimeB
) {
1459 result
= a
->values
.value("rating").toInt() - b
->values
.value("rating").toInt();
1463 case ImageSizeRole
: {
1464 // Alway use a natural comparing to interpret the numbers of a string like
1465 // "1600 x 1200" for having a correct sorting.
1466 result
= KStringHandler::naturalCompare(a
->values
.value("imageSize").toString(),
1467 b
->values
.value("imageSize").toString(),
1473 const QByteArray role
= roleForType(m_sortRole
);
1474 result
= QString::compare(a
->values
.value(role
).toString(),
1475 b
->values
.value(role
).toString());
1482 // The current sort role was sufficient to define an order
1486 // Fallback #1: Compare the text of the items
1487 result
= stringCompare(itemA
.text(), itemB
.text());
1492 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1493 result
= stringCompare(itemA
.name(m_caseSensitivity
== Qt::CaseInsensitive
),
1494 itemB
.name(m_caseSensitivity
== Qt::CaseInsensitive
));
1499 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1500 // equal. In this case a comparison of the URL is done which is unique in all cases
1501 // within KDirLister.
1502 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1505 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
) const
1507 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1508 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1509 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1510 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1512 if (m_caseSensitivity
== Qt::CaseInsensitive
) {
1513 const int result
= m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseInsensitive
)
1514 : QString::compare(a
, b
, Qt::CaseInsensitive
);
1516 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1517 // comparison, still a deterministic sort order is required. A case sensitive
1518 // comparison is done as fallback.
1523 return m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseSensitive
)
1524 : QString::compare(a
, b
, Qt::CaseSensitive
);
1527 int KFileItemModel::expandedParentsCountCompare(const ItemData
* a
, const ItemData
* b
) const
1529 const KUrl urlA
= a
->item
.url();
1530 const KUrl urlB
= b
->item
.url();
1531 if (urlA
.directory() == urlB
.directory()) {
1532 // Both items have the same directory as parent
1536 // Check whether one item is the parent of the other item
1537 if (urlA
.isParentOf(urlB
)) {
1538 return (sortOrder() == Qt::AscendingOrder
) ? -1 : +1;
1539 } else if (urlB
.isParentOf(urlA
)) {
1540 return (sortOrder() == Qt::AscendingOrder
) ? +1 : -1;
1543 // Determine the maximum common path of both items and
1544 // remember the index in 'index'
1545 const QString pathA
= urlA
.path();
1546 const QString pathB
= urlB
.path();
1548 const int maxIndex
= qMin(pathA
.length(), pathB
.length()) - 1;
1550 while (index
<= maxIndex
&& pathA
.at(index
) == pathB
.at(index
)) {
1553 if (index
> maxIndex
) {
1556 while (index
> 0 && (pathA
.at(index
) != QLatin1Char('/') || pathB
.at(index
) != QLatin1Char('/'))) {
1560 // Determine the first sub-path after the common path and
1561 // check whether it represents a directory or already a file
1563 const QString subPathA
= subPath(a
->item
, pathA
, index
, &isDirA
);
1565 const QString subPathB
= subPath(b
->item
, pathB
, index
, &isDirB
);
1567 if (m_sortDirsFirst
|| m_sortRole
== SizeRole
) {
1568 if (isDirA
&& !isDirB
) {
1569 return (sortOrder() == Qt::AscendingOrder
) ? -1 : +1;
1570 } else if (!isDirA
&& isDirB
) {
1571 return (sortOrder() == Qt::AscendingOrder
) ? +1 : -1;
1575 // Compare the items of the parents that represent the first
1576 // different path after the common path.
1577 const QString parentPathA
= pathA
.left(index
) + subPathA
;
1578 const QString parentPathB
= pathB
.left(index
) + subPathB
;
1580 const ItemData
* parentA
= a
;
1581 while (parentA
&& parentA
->item
.url().path() != parentPathA
) {
1582 parentA
= parentA
->parent
;
1585 const ItemData
* parentB
= b
;
1586 while (parentB
&& parentB
->item
.url().path() != parentPathB
) {
1587 parentB
= parentB
->parent
;
1590 if (parentA
&& parentB
) {
1591 return sortRoleCompare(parentA
, parentB
);
1594 kWarning() << "Child items without parent detected:" << a
->item
.url() << b
->item
.url();
1595 return QString::compare(urlA
.url(), urlB
.url(), Qt::CaseSensitive
);
1598 QString
KFileItemModel::subPath(const KFileItem
& item
,
1599 const QString
& itemPath
,
1604 const int pathIndex
= itemPath
.indexOf('/', start
+ 1);
1605 *isDir
= (pathIndex
> 0) || item
.isDir();
1606 return itemPath
.mid(start
, pathIndex
- start
);
1609 bool KFileItemModel::useMaximumUpdateInterval() const
1611 return !m_dirLister
->url().isLocalFile();
1614 static bool localeAwareLessThan(const QChar
& c1
, const QChar
& c2
)
1616 return QString::localeAwareCompare(c1
, c2
) < 0;
1619 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1621 Q_ASSERT(!m_itemData
.isEmpty());
1623 const int maxIndex
= count() - 1;
1624 QList
<QPair
<int, QVariant
> > groups
;
1628 for (int i
= 0; i
<= maxIndex
; ++i
) {
1629 if (isChildItem(i
)) {
1633 const QString name
= m_itemData
.at(i
)->values
.value("text").toString();
1635 // Use the first character of the name as group indication
1636 QChar newFirstChar
= name
.at(0).toUpper();
1637 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1638 newFirstChar
= name
.at(1).toUpper();
1641 if (firstChar
!= newFirstChar
) {
1642 QString newGroupValue
;
1643 if (newFirstChar
.isLetter()) {
1644 // Try to find a matching group in the range 'A' to 'Z'.
1645 static std::vector
<QChar
> lettersAtoZ
;
1646 if (lettersAtoZ
.empty()) {
1647 for (char c
= 'A'; c
<= 'Z'; ++c
) {
1648 lettersAtoZ
.push_back(QLatin1Char(c
));
1652 std::vector
<QChar
>::iterator it
= std::lower_bound(lettersAtoZ
.begin(), lettersAtoZ
.end(), newFirstChar
, localeAwareLessThan
);
1653 if (it
!= lettersAtoZ
.end()) {
1654 if (localeAwareLessThan(newFirstChar
, *it
) && it
!= lettersAtoZ
.begin()) {
1655 // newFirstChar belongs to the group preceding *it.
1656 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
1659 newGroupValue
= *it
;
1661 newGroupValue
= newFirstChar
;
1663 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
1664 // Apply group '0 - 9' for any name that starts with a digit
1665 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
1667 newGroupValue
= i18nc("@title:group", "Others");
1670 if (newGroupValue
!= groupValue
) {
1671 groupValue
= newGroupValue
;
1672 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1675 firstChar
= newFirstChar
;
1681 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
1683 Q_ASSERT(!m_itemData
.isEmpty());
1685 const int maxIndex
= count() - 1;
1686 QList
<QPair
<int, QVariant
> > groups
;
1689 for (int i
= 0; i
<= maxIndex
; ++i
) {
1690 if (isChildItem(i
)) {
1694 const KFileItem
& item
= m_itemData
.at(i
)->item
;
1695 const KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
1696 QString newGroupValue
;
1697 if (!item
.isNull() && item
.isDir()) {
1698 newGroupValue
= i18nc("@title:group Size", "Folders");
1699 } else if (fileSize
< 5 * 1024 * 1024) {
1700 newGroupValue
= i18nc("@title:group Size", "Small");
1701 } else if (fileSize
< 10 * 1024 * 1024) {
1702 newGroupValue
= i18nc("@title:group Size", "Medium");
1704 newGroupValue
= i18nc("@title:group Size", "Big");
1707 if (newGroupValue
!= groupValue
) {
1708 groupValue
= newGroupValue
;
1709 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1716 QList
<QPair
<int, QVariant
> > KFileItemModel::dateRoleGroups() const
1718 Q_ASSERT(!m_itemData
.isEmpty());
1720 const int maxIndex
= count() - 1;
1721 QList
<QPair
<int, QVariant
> > groups
;
1723 const QDate currentDate
= KDateTime::currentLocalDateTime().date();
1725 int yearForCurrentWeek
= 0;
1726 int currentWeek
= currentDate
.weekNumber(&yearForCurrentWeek
);
1727 if (yearForCurrentWeek
== currentDate
.year() + 1) {
1731 QDate previousModifiedDate
;
1733 for (int i
= 0; i
<= maxIndex
; ++i
) {
1734 if (isChildItem(i
)) {
1738 const KDateTime modifiedTime
= m_itemData
.at(i
)->item
.time(KFileItem::ModificationTime
);
1739 const QDate modifiedDate
= modifiedTime
.date();
1740 if (modifiedDate
== previousModifiedDate
) {
1741 // The current item is in the same group as the previous item
1744 previousModifiedDate
= modifiedDate
;
1746 const int daysDistance
= modifiedDate
.daysTo(currentDate
);
1748 int yearForModifiedWeek
= 0;
1749 int modifiedWeek
= modifiedDate
.weekNumber(&yearForModifiedWeek
);
1750 if (yearForModifiedWeek
== modifiedDate
.year() + 1) {
1754 QString newGroupValue
;
1755 if (currentDate
.year() == modifiedDate
.year() && currentDate
.month() == modifiedDate
.month()) {
1756 if (modifiedWeek
> currentWeek
) {
1757 // Usecase: modified date = 2010-01-01, current date = 2010-01-22
1758 // modified week = 53, current week = 3
1761 switch (currentWeek
- modifiedWeek
) {
1763 switch (daysDistance
) {
1764 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
1765 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
1766 default: newGroupValue
= modifiedTime
.toString(i18nc("@title:group The week day name: %A", "%A"));
1770 newGroupValue
= i18nc("@title:group Date", "Last Week");
1773 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
1776 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
1780 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
1786 const QDate lastMonthDate
= currentDate
.addMonths(-1);
1787 if (lastMonthDate
.year() == modifiedDate
.year() && lastMonthDate
.month() == modifiedDate
.month()) {
1788 if (daysDistance
== 1) {
1789 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Yesterday (%B, %Y)"));
1790 } else if (daysDistance
<= 7) {
1791 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)"));
1792 } else if (daysDistance
<= 7 * 2) {
1793 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)"));
1794 } else if (daysDistance
<= 7 * 3) {
1795 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)"));
1796 } else if (daysDistance
<= 7 * 4) {
1797 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)"));
1799 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"));
1802 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"));
1806 if (newGroupValue
!= groupValue
) {
1807 groupValue
= newGroupValue
;
1808 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1815 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
1817 Q_ASSERT(!m_itemData
.isEmpty());
1819 const int maxIndex
= count() - 1;
1820 QList
<QPair
<int, QVariant
> > groups
;
1822 QString permissionsString
;
1824 for (int i
= 0; i
<= maxIndex
; ++i
) {
1825 if (isChildItem(i
)) {
1829 const ItemData
* itemData
= m_itemData
.at(i
);
1830 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
1831 if (newPermissionsString
== permissionsString
) {
1834 permissionsString
= newPermissionsString
;
1836 const QFileInfo
info(itemData
->item
.url().pathOrUrl());
1840 if (info
.permission(QFile::ReadUser
)) {
1841 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1843 if (info
.permission(QFile::WriteUser
)) {
1844 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1846 if (info
.permission(QFile::ExeUser
)) {
1847 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1849 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
1853 if (info
.permission(QFile::ReadGroup
)) {
1854 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1856 if (info
.permission(QFile::WriteGroup
)) {
1857 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1859 if (info
.permission(QFile::ExeGroup
)) {
1860 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1862 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
1864 // Set others string
1866 if (info
.permission(QFile::ReadOther
)) {
1867 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1869 if (info
.permission(QFile::WriteOther
)) {
1870 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1872 if (info
.permission(QFile::ExeOther
)) {
1873 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1875 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
1877 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
1878 if (newGroupValue
!= groupValue
) {
1879 groupValue
= newGroupValue
;
1880 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1887 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
1889 Q_ASSERT(!m_itemData
.isEmpty());
1891 const int maxIndex
= count() - 1;
1892 QList
<QPair
<int, QVariant
> > groups
;
1894 int groupValue
= -1;
1895 for (int i
= 0; i
<= maxIndex
; ++i
) {
1896 if (isChildItem(i
)) {
1899 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
1900 if (newGroupValue
!= groupValue
) {
1901 groupValue
= newGroupValue
;
1902 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1909 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
1911 Q_ASSERT(!m_itemData
.isEmpty());
1913 const int maxIndex
= count() - 1;
1914 QList
<QPair
<int, QVariant
> > groups
;
1916 bool isFirstGroupValue
= true;
1918 for (int i
= 0; i
<= maxIndex
; ++i
) {
1919 if (isChildItem(i
)) {
1922 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
1923 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
1924 groupValue
= newGroupValue
;
1925 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1926 isFirstGroupValue
= false;
1933 KFileItemList
KFileItemModel::childItems(const KFileItem
& item
) const
1935 KFileItemList items
;
1937 int index
= m_items
.value(item
.url(), -1);
1939 const int parentLevel
= m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt();
1941 while (index
< m_itemData
.count() && m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt() > parentLevel
) {
1942 items
.append(m_itemData
.at(index
)->item
);
1950 void KFileItemModel::emitSortProgress(int resolvedCount
)
1952 // Be tolerant against a resolvedCount with a wrong range.
1953 // Although there should not be a case where KFileItemModelRolesUpdater
1954 // (= caller) provides a wrong range, it is important to emit
1955 // a useful progress information even if there is an unexpected
1956 // implementation issue.
1958 const int itemCount
= count();
1959 if (resolvedCount
>= itemCount
) {
1960 m_sortingProgressPercent
= -1;
1961 if (m_resortAllItemsTimer
->isActive()) {
1962 m_resortAllItemsTimer
->stop();
1966 emit
directorySortingProgress(100);
1967 } else if (itemCount
> 0) {
1968 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
1970 const int progress
= resolvedCount
* 100 / itemCount
;
1971 if (m_sortingProgressPercent
!= progress
) {
1972 m_sortingProgressPercent
= progress
;
1973 emit
directorySortingProgress(progress
);
1978 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
1980 static const RoleInfoMap rolesInfoMap
[] = {
1981 // | role | roleType | role translation | group translation | requires Nepomuk | requires indexer
1982 { 0, NoRole
, 0, 0, 0, 0, false, false },
1983 { "text", NameRole
, I18N_NOOP2_NOSTRIP("@label", "Name"), 0, 0, false, false },
1984 { "size", SizeRole
, I18N_NOOP2_NOSTRIP("@label", "Size"), 0, 0, false, false },
1985 { "date", DateRole
, I18N_NOOP2_NOSTRIP("@label", "Date"), 0, 0, false, false },
1986 { "type", TypeRole
, I18N_NOOP2_NOSTRIP("@label", "Type"), 0, 0, false, false },
1987 { "rating", RatingRole
, I18N_NOOP2_NOSTRIP("@label", "Rating"), 0, 0, true, false },
1988 { "tags", TagsRole
, I18N_NOOP2_NOSTRIP("@label", "Tags"), 0, 0, true, false },
1989 { "comment", CommentRole
, I18N_NOOP2_NOSTRIP("@label", "Comment"), 0, 0, true, false },
1990 { "wordCount", WordCountRole
, I18N_NOOP2_NOSTRIP("@label", "Word Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
1991 { "lineCount", LineCountRole
, I18N_NOOP2_NOSTRIP("@label", "Line Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
1992 { "imageSize", ImageSizeRole
, I18N_NOOP2_NOSTRIP("@label", "Image Size"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
1993 { "orientation", OrientationRole
, I18N_NOOP2_NOSTRIP("@label", "Orientation"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
1994 { "artist", ArtistRole
, I18N_NOOP2_NOSTRIP("@label", "Artist"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1995 { "album", AlbumRole
, I18N_NOOP2_NOSTRIP("@label", "Album"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1996 { "duration", DurationRole
, I18N_NOOP2_NOSTRIP("@label", "Duration"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1997 { "track", TrackRole
, I18N_NOOP2_NOSTRIP("@label", "Track"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1998 { "path", PathRole
, I18N_NOOP2_NOSTRIP("@label", "Path"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1999 { "destination", DestinationRole
, I18N_NOOP2_NOSTRIP("@label", "Link Destination"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2000 { "copiedFrom", CopiedFromRole
, I18N_NOOP2_NOSTRIP("@label", "Copied From"), I18N_NOOP2_NOSTRIP("@label", "Other"), true, false },
2001 { "permissions", PermissionsRole
, I18N_NOOP2_NOSTRIP("@label", "Permissions"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2002 { "owner", OwnerRole
, I18N_NOOP2_NOSTRIP("@label", "Owner"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2003 { "group", GroupRole
, I18N_NOOP2_NOSTRIP("@label", "User Group"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2006 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
2007 return rolesInfoMap
;
2010 void KFileItemModel::determineMimeTypes(const KFileItemList
& items
, int timeout
)
2012 QElapsedTimer timer
;
2014 foreach (KFileItem item
, items
) { // krazy:exclude=foreach
2015 item
.determineMimeType();
2016 if (timer
.elapsed() > timeout
) {
2017 // Don't block the user interface, let the remaining items
2018 // be resolved asynchronously.
2024 #include "kfileitemmodel.moc"