1 /***************************************************************************
2 * Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
4 * This program is free software; you can redistribute it and/or modify *
5 * it under the terms of the GNU General Public License as published by *
6 * the Free Software Foundation; either version 2 of the License, or *
7 * (at your option) any later version. *
9 * This program is distributed in the hope that it will be useful, *
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
12 * GNU General Public License for more details. *
14 * You should have received a copy of the GNU General Public License *
15 * along with this program; if not, write to the *
16 * Free Software Foundation, Inc., *
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
18 ***************************************************************************/
20 #include "kfileitemmodel.h"
23 #include <KGlobalSettings>
25 #include <KStringHandler>
28 #include "private/kfileitemmodelsortalgorithm.h"
29 #include "private/kfileitemmodeldirlister.h"
31 #include <QApplication>
35 // #define KFILEITEMMODEL_DEBUG
37 KFileItemModel::KFileItemModel(QObject
* parent
) :
38 KItemModelBase("text", parent
),
40 m_naturalSorting(KGlobalSettings::naturalSorting()),
41 m_sortDirsFirst(true),
43 m_sortingProgressPercent(-1),
45 m_caseSensitivity(Qt::CaseInsensitive
),
51 m_maximumUpdateIntervalTimer(0),
52 m_resortAllItemsTimer(0),
53 m_pendingItemsToInsert(),
55 m_expandedParentsCountRoot(UninitializedExpandedParentsCountRoot
),
59 m_dirLister
= new KFileItemModelDirLister(this);
60 m_dirLister
->setAutoUpdate(true);
61 m_dirLister
->setDelayedMimeTypes(true);
62 m_dirLister
->setMainWindow(qApp
->activeWindow());
64 connect(m_dirLister
, SIGNAL(started(KUrl
)), this, SIGNAL(directoryLoadingStarted()));
65 connect(m_dirLister
, SIGNAL(canceled()), this, SLOT(slotCanceled()));
66 connect(m_dirLister
, SIGNAL(completed(KUrl
)), this, SLOT(slotCompleted()));
67 connect(m_dirLister
, SIGNAL(newItems(KFileItemList
)), this, SLOT(slotNewItems(KFileItemList
)));
68 connect(m_dirLister
, SIGNAL(itemsDeleted(KFileItemList
)), this, SLOT(slotItemsDeleted(KFileItemList
)));
69 connect(m_dirLister
, SIGNAL(refreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)), this, SLOT(slotRefreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)));
70 connect(m_dirLister
, SIGNAL(clear()), this, SLOT(slotClear()));
71 connect(m_dirLister
, SIGNAL(clear(KUrl
)), this, SLOT(slotClear(KUrl
)));
72 connect(m_dirLister
, SIGNAL(infoMessage(QString
)), this, SIGNAL(infoMessage(QString
)));
73 connect(m_dirLister
, SIGNAL(errorMessage(QString
)), this, SIGNAL(errorMessage(QString
)));
74 connect(m_dirLister
, SIGNAL(redirection(KUrl
,KUrl
)), this, SIGNAL(directoryRedirection(KUrl
,KUrl
)));
76 // Apply default roles that should be determined
78 m_requestRole
[NameRole
] = true;
79 m_requestRole
[IsDirRole
] = true;
80 m_roles
.insert("text");
81 m_roles
.insert("isDir");
83 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
84 // before the completed() or canceled() signal has been emitted.
85 m_maximumUpdateIntervalTimer
= new QTimer(this);
86 m_maximumUpdateIntervalTimer
->setInterval(2000);
87 m_maximumUpdateIntervalTimer
->setSingleShot(true);
88 connect(m_maximumUpdateIntervalTimer
, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
90 // When changing the value of an item which represents the sort-role a resorting must be
91 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
92 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
93 // resorting is postponed until the timer has been exceeded.
94 m_resortAllItemsTimer
= new QTimer(this);
95 m_resortAllItemsTimer
->setInterval(500);
96 m_resortAllItemsTimer
->setSingleShot(true);
97 connect(m_resortAllItemsTimer
, SIGNAL(timeout()), this, SLOT(resortAllItems()));
99 connect(KGlobalSettings::self(), SIGNAL(naturalSortingChanged()), this, SLOT(slotNaturalSortingChanged()));
102 KFileItemModel::~KFileItemModel()
104 qDeleteAll(m_itemData
);
108 void KFileItemModel::loadDirectory(const KUrl
& url
)
110 m_dirLister
->openUrl(url
);
113 void KFileItemModel::refreshDirectory(const KUrl
& url
)
115 m_dirLister
->openUrl(url
, KDirLister::Reload
);
118 KUrl
KFileItemModel::directory() const
120 return m_dirLister
->url();
123 void KFileItemModel::cancelDirectoryLoading()
128 int KFileItemModel::count() const
130 return m_itemData
.count();
133 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
135 if (index
>= 0 && index
< count()) {
136 return m_itemData
.at(index
)->values
;
138 return QHash
<QByteArray
, QVariant
>();
141 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
143 if (index
< 0 || index
>= count()) {
147 QHash
<QByteArray
, QVariant
> currentValues
= m_itemData
.at(index
)->values
;
149 // Determine which roles have been changed
150 QSet
<QByteArray
> changedRoles
;
151 QHashIterator
<QByteArray
, QVariant
> it(values
);
152 while (it
.hasNext()) {
154 const QByteArray role
= it
.key();
155 const QVariant value
= it
.value();
157 if (currentValues
[role
] != value
) {
158 currentValues
[role
] = value
;
159 changedRoles
.insert(role
);
163 if (changedRoles
.isEmpty()) {
167 m_itemData
[index
]->values
= currentValues
;
168 emit
itemsChanged(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
170 if (changedRoles
.contains(sortRole())) {
171 m_resortAllItemsTimer
->start();
177 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
179 if (dirsFirst
!= m_sortDirsFirst
) {
180 m_sortDirsFirst
= dirsFirst
;
185 bool KFileItemModel::sortDirectoriesFirst() const
187 return m_sortDirsFirst
;
190 void KFileItemModel::setShowHiddenFiles(bool show
)
192 m_dirLister
->setShowingDotFiles(show
);
193 m_dirLister
->emitChanges();
199 bool KFileItemModel::showHiddenFiles() const
201 return m_dirLister
->showingDotFiles();
204 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
206 m_dirLister
->setDirOnlyMode(enabled
);
209 bool KFileItemModel::showDirectoriesOnly() const
211 return m_dirLister
->dirOnlyMode();
214 QMimeData
* KFileItemModel::createMimeData(const QSet
<int>& indexes
) const
216 QMimeData
* data
= new QMimeData();
218 // The following code has been taken from KDirModel::mimeData()
219 // (kdelibs/kio/kio/kdirmodel.cpp)
220 // Copyright (C) 2006 David Faure <faure@kde.org>
222 KUrl::List mostLocalUrls
;
223 bool canUseMostLocalUrls
= true;
225 QSetIterator
<int> it(indexes
);
226 while (it
.hasNext()) {
227 const int index
= it
.next();
228 const KFileItem item
= fileItem(index
);
229 if (!item
.isNull()) {
233 mostLocalUrls
<< item
.mostLocalUrl(isLocal
);
235 canUseMostLocalUrls
= false;
240 const bool different
= canUseMostLocalUrls
&& mostLocalUrls
!= urls
;
241 urls
= KDirModel::simplifiedUrlList(urls
); // TODO: Check if we still need KDirModel for this in KDE 5.0
243 mostLocalUrls
= KDirModel::simplifiedUrlList(mostLocalUrls
);
244 urls
.populateMimeData(mostLocalUrls
, data
);
246 urls
.populateMimeData(data
);
252 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
254 startFromIndex
= qMax(0, startFromIndex
);
255 for (int i
= startFromIndex
; i
< count(); ++i
) {
256 if (data(i
)["text"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
260 for (int i
= 0; i
< startFromIndex
; ++i
) {
261 if (data(i
)["text"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
268 bool KFileItemModel::supportsDropping(int index
) const
270 const KFileItem item
= fileItem(index
);
271 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
274 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
276 static QHash
<QByteArray
, QString
> description
;
277 if (description
.isEmpty()) {
279 const RoleInfoMap
* map
= rolesInfoMap(count
);
280 for (int i
= 0; i
< count
; ++i
) {
281 description
.insert(map
[i
].role
, map
[i
].roleTranslation
);
285 return description
.value(role
);
288 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
290 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
291 #ifdef KFILEITEMMODEL_DEBUG
295 switch (typeForRole(sortRole())) {
296 case NameRole
: m_groups
= nameRoleGroups(); break;
297 case SizeRole
: m_groups
= sizeRoleGroups(); break;
298 case DateRole
: m_groups
= dateRoleGroups(); break;
299 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
300 case RatingRole
: m_groups
= ratingRoleGroups(); break;
301 default: m_groups
= genericStringRoleGroups(sortRole()); break;
304 #ifdef KFILEITEMMODEL_DEBUG
305 kDebug() << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
312 KFileItem
KFileItemModel::fileItem(int index
) const
314 if (index
>= 0 && index
< count()) {
315 return m_itemData
.at(index
)->item
;
321 KFileItem
KFileItemModel::fileItem(const KUrl
& url
) const
323 const int index
= m_items
.value(url
, -1);
325 return m_itemData
.at(index
)->item
;
330 int KFileItemModel::index(const KFileItem
& item
) const
336 return m_items
.value(item
.url(), -1);
339 int KFileItemModel::index(const KUrl
& url
) const
341 KUrl urlToFind
= url
;
342 urlToFind
.adjustPath(KUrl::RemoveTrailingSlash
);
343 return m_items
.value(urlToFind
, -1);
346 KFileItem
KFileItemModel::rootItem() const
348 return m_dirLister
->rootItem();
351 void KFileItemModel::clear()
356 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
358 if (m_roles
== roles
) {
364 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
365 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
366 if (supportedExpanding
&& !willSupportExpanding
) {
367 // No expanding is supported anymore. Take care to delete all items that have an expansion level
368 // that is not 0 (and hence are part of an expanded item).
369 removeExpandedItems();
376 QSetIterator
<QByteArray
> it(roles
);
377 while (it
.hasNext()) {
378 const QByteArray
& role
= it
.next();
379 m_requestRole
[typeForRole(role
)] = true;
383 // Update m_data with the changed requested roles
384 const int maxIndex
= count() - 1;
385 for (int i
= 0; i
<= maxIndex
; ++i
) {
386 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
);
389 kWarning() << "TODO: Emitting itemsChanged() with no information what has changed!";
390 emit
itemsChanged(KItemRangeList() << KItemRange(0, count()), QSet
<QByteArray
>());
394 QSet
<QByteArray
> KFileItemModel::roles() const
399 bool KFileItemModel::setExpanded(int index
, bool expanded
)
401 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
405 QHash
<QByteArray
, QVariant
> values
;
406 values
.insert("isExpanded", expanded
);
407 if (!setData(index
, values
)) {
411 const KUrl url
= m_itemData
.at(index
)->item
.url();
413 m_expandedDirs
.insert(url
);
414 m_dirLister
->openUrl(url
, KDirLister::Keep
);
416 m_expandedDirs
.remove(url
);
417 m_dirLister
->stop(url
);
420 KFileItemList itemsToRemove
;
421 const int expandedParentsCount
= data(index
)["expandedParentsCount"].toInt();
423 while (index
< count() && data(index
)["expandedParentsCount"].toInt() > expandedParentsCount
) {
424 itemsToRemove
.append(m_itemData
.at(index
)->item
);
427 removeItems(itemsToRemove
);
433 bool KFileItemModel::isExpanded(int index
) const
435 if (index
>= 0 && index
< count()) {
436 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
441 bool KFileItemModel::isExpandable(int index
) const
443 if (index
>= 0 && index
< count()) {
444 return m_itemData
.at(index
)->values
.value("isExpandable").toBool();
449 int KFileItemModel::expandedParentsCount(int index
) const
451 if (index
>= 0 && index
< count()) {
452 const int parentsCount
= m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt();
453 if (parentsCount
> 0) {
460 QSet
<KUrl
> KFileItemModel::expandedDirectories() const
462 return m_expandedDirs
;
465 void KFileItemModel::restoreExpandedDirectories(const QSet
<KUrl
>& urls
)
467 m_urlsToExpand
= urls
;
470 void KFileItemModel::expandParentDirectories(const KUrl
& url
)
472 const int pos
= m_dirLister
->url().path().length();
474 // Assure that each sub-path of the URL that should be
475 // expanded is added to m_urlsToExpand. KDirLister
476 // does not care whether the parent-URL has already been
478 KUrl urlToExpand
= m_dirLister
->url();
479 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator());
480 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
481 urlToExpand
.addPath(subDirs
.at(i
));
482 m_urlsToExpand
.insert(urlToExpand
);
485 // KDirLister::open() must called at least once to trigger an initial
486 // loading. The pending URLs that must be restored are handled
487 // in slotCompleted().
488 QSetIterator
<KUrl
> it2(m_urlsToExpand
);
489 while (it2
.hasNext()) {
490 const int idx
= index(it2
.next());
491 if (idx
>= 0 && !isExpanded(idx
)) {
492 setExpanded(idx
, true);
498 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
500 if (m_filter
.pattern() != nameFilter
) {
501 dispatchPendingItemsToInsert();
503 m_filter
.setPattern(nameFilter
);
505 // Check which shown items from m_itemData must get
506 // hidden and hence moved to m_filteredItems.
507 KFileItemList newFilteredItems
;
509 foreach (ItemData
* itemData
, m_itemData
) {
510 if (!m_filter
.matches(itemData
->item
)) {
511 // Only filter non-expanded items as child items may never
512 // exist without a parent item
513 if (!itemData
->values
.value("isExpanded").toBool()) {
514 newFilteredItems
.append(itemData
->item
);
515 m_filteredItems
.insert(itemData
->item
);
520 removeItems(newFilteredItems
);
522 // Check which hidden items from m_filteredItems should
523 // get visible again and hence removed from m_filteredItems.
524 KFileItemList newVisibleItems
;
526 QMutableSetIterator
<KFileItem
> it(m_filteredItems
);
527 while (it
.hasNext()) {
528 const KFileItem item
= it
.next();
529 if (m_filter
.matches(item
)) {
530 newVisibleItems
.append(item
);
531 m_filteredItems
.remove(item
);
535 insertItems(newVisibleItems
);
539 QString
KFileItemModel::nameFilter() const
541 return m_filter
.pattern();
544 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
546 static QList
<RoleInfo
> rolesInfo
;
547 if (rolesInfo
.isEmpty()) {
549 const RoleInfoMap
* map
= rolesInfoMap(count
);
550 for (int i
= 0; i
< count
; ++i
) {
551 if (map
[i
].roleType
!= NoRole
) {
553 info
.role
= map
[i
].role
;
554 info
.translation
= map
[i
].roleTranslation
;
555 info
.group
= map
[i
].groupTranslation
;
556 info
.requiresNepomuk
= map
[i
].requiresNepomuk
;
557 info
.requiresIndexer
= map
[i
].requiresIndexer
;
558 rolesInfo
.append(info
);
566 void KFileItemModel::onGroupedSortingChanged(bool current
)
572 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
575 m_sortRole
= typeForRole(current
);
577 #ifdef KFILEITEMMODEL_DEBUG
578 if (!m_requestRole
[m_sortRole
]) {
579 kWarning() << "The sort-role has been changed to a role that has not been received yet";
586 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
593 void KFileItemModel::resortAllItems()
595 m_resortAllItemsTimer
->stop();
597 const int itemCount
= count();
598 if (itemCount
<= 0) {
602 #ifdef KFILEITEMMODEL_DEBUG
605 kDebug() << "===========================================================";
606 kDebug() << "Resorting" << itemCount
<< "items";
609 // Remember the order of the current URLs so
610 // that it can be determined which indexes have
611 // been moved because of the resorting.
613 oldUrls
.reserve(itemCount
);
614 foreach (const ItemData
* itemData
, m_itemData
) {
615 oldUrls
.append(itemData
->item
.url());
622 KFileItemModelSortAlgorithm::sort(this, m_itemData
.begin(), m_itemData
.end());
623 for (int i
= 0; i
< itemCount
; ++i
) {
624 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
627 // Determine the indexes that have been moved
628 QList
<int> movedToIndexes
;
629 movedToIndexes
.reserve(itemCount
);
630 for (int i
= 0; i
< itemCount
; i
++) {
631 const int newIndex
= m_items
.value(oldUrls
.at(i
).url());
632 movedToIndexes
.append(newIndex
);
635 // Don't check whether items have really been moved and always emit a
636 // itemsMoved() signal after resorting: In case of grouped items
637 // the groups might change even if the items themselves don't change their
638 // position. Let the receiver of the signal decide whether a check for moved
639 // items makes sense.
640 emit
itemsMoved(KItemRange(0, itemCount
), movedToIndexes
);
642 #ifdef KFILEITEMMODEL_DEBUG
643 kDebug() << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
647 void KFileItemModel::slotCompleted()
649 dispatchPendingItemsToInsert();
651 if (!m_urlsToExpand
.isEmpty()) {
652 // Try to find a URL that can be expanded.
653 // Note that the parent folder must be expanded before any of its subfolders become visible.
654 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
655 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
656 foreach(const KUrl
& url
, m_urlsToExpand
) {
657 const int index
= m_items
.value(url
, -1);
659 m_urlsToExpand
.remove(url
);
660 if (setExpanded(index
, true)) {
661 // The dir lister has been triggered. This slot will be called
662 // again after the directory has been expanded.
668 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
669 // if these URLs have been deleted in the meantime.
670 m_urlsToExpand
.clear();
673 emit
directoryLoadingCompleted();
676 void KFileItemModel::slotCanceled()
678 m_maximumUpdateIntervalTimer
->stop();
679 dispatchPendingItemsToInsert();
682 void KFileItemModel::slotNewItems(const KFileItemList
& items
)
684 Q_ASSERT(!items
.isEmpty());
686 if (m_requestRole
[ExpandedParentsCountRole
] && m_expandedParentsCountRoot
>= 0) {
687 // To be able to compare whether the new items may be inserted as children
688 // of a parent item the pending items must be added to the model first.
689 dispatchPendingItemsToInsert();
691 KFileItem item
= items
.first();
693 // If the expanding of items is enabled, the call
694 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
695 // might result in emitting the same items twice due to the Keep-parameter.
696 // This case happens if an item gets expanded, collapsed and expanded again
697 // before the items could be loaded for the first expansion.
698 const int index
= m_items
.value(item
.url(), -1);
700 // The items are already part of the model.
704 // KDirLister keeps the children of items that got expanded once even if
705 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
706 // checked whether the parent for new items is still expanded.
707 KUrl parentUrl
= item
.url().upUrl();
708 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
709 const int parentIndex
= m_items
.value(parentUrl
, -1);
710 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
711 // The parent is not expanded.
716 if (m_filter
.pattern().isEmpty()) {
717 m_pendingItemsToInsert
.append(items
);
719 // The name-filter is active. Hide filtered items
720 // before inserting them into the model and remember
721 // the filtered items in m_filteredItems.
722 KFileItemList filteredItems
;
723 foreach (const KFileItem
& item
, items
) {
724 if (m_filter
.matches(item
)) {
725 filteredItems
.append(item
);
727 m_filteredItems
.insert(item
);
731 m_pendingItemsToInsert
.append(filteredItems
);
734 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer
->isActive()) {
735 // Assure that items get dispatched if no completed() or canceled() signal is
736 // emitted during the maximum update interval.
737 m_maximumUpdateIntervalTimer
->start();
741 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
743 dispatchPendingItemsToInsert();
745 KFileItemList itemsToRemove
= items
;
746 if (m_requestRole
[ExpandedParentsCountRole
] && m_expandedParentsCountRoot
>= 0) {
747 // Assure that removing a parent item also results in removing all children
748 foreach (const KFileItem
& item
, items
) {
749 itemsToRemove
.append(childItems(item
));
753 if (!m_filteredItems
.isEmpty()) {
754 foreach (const KFileItem
& item
, itemsToRemove
) {
755 m_filteredItems
.remove(item
);
759 removeItems(itemsToRemove
);
762 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
764 Q_ASSERT(!items
.isEmpty());
765 #ifdef KFILEITEMMODEL_DEBUG
766 kDebug() << "Refreshing" << items
.count() << "items";
771 // Get the indexes of all items that have been refreshed
773 indexes
.reserve(items
.count());
775 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
776 while (it
.hasNext()) {
777 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
778 const KFileItem
& oldItem
= itemPair
.first
;
779 const KFileItem
& newItem
= itemPair
.second
;
780 const int index
= m_items
.value(oldItem
.url(), -1);
782 m_itemData
[index
]->item
= newItem
;
784 // Keep old values as long as possible if they could not retrieved synchronously yet.
785 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
786 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
));
787 while (it
.hasNext()) {
789 m_itemData
[index
]->values
.insert(it
.key(), it
.value());
792 m_items
.remove(oldItem
.url());
793 m_items
.insert(newItem
.url(), index
);
794 indexes
.append(index
);
798 // If the changed items have been created recently, they might not be in m_items yet.
799 // In that case, the list 'indexes' might be empty.
800 if (indexes
.isEmpty()) {
804 // Extract the item-ranges out of the changed indexes
807 KItemRangeList itemRangeList
;
808 int previousIndex
= indexes
.at(0);
809 int rangeIndex
= previousIndex
;
812 const int maxIndex
= indexes
.count() - 1;
813 for (int i
= 1; i
<= maxIndex
; ++i
) {
814 const int currentIndex
= indexes
.at(i
);
815 if (currentIndex
== previousIndex
+ 1) {
818 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
820 rangeIndex
= currentIndex
;
823 previousIndex
= currentIndex
;
826 if (rangeCount
> 0) {
827 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
830 emit
itemsChanged(itemRangeList
, m_roles
);
835 void KFileItemModel::slotClear()
837 #ifdef KFILEITEMMODEL_DEBUG
838 kDebug() << "Clearing all items";
841 m_filteredItems
.clear();
844 m_maximumUpdateIntervalTimer
->stop();
845 m_resortAllItemsTimer
->stop();
846 m_pendingItemsToInsert
.clear();
848 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
850 const int removedCount
= m_itemData
.count();
851 if (removedCount
> 0) {
852 qDeleteAll(m_itemData
);
855 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
858 m_expandedDirs
.clear();
861 void KFileItemModel::slotClear(const KUrl
& url
)
866 void KFileItemModel::slotNaturalSortingChanged()
868 m_naturalSorting
= KGlobalSettings::naturalSorting();
872 void KFileItemModel::dispatchPendingItemsToInsert()
874 if (!m_pendingItemsToInsert
.isEmpty()) {
875 insertItems(m_pendingItemsToInsert
);
876 m_pendingItemsToInsert
.clear();
880 void KFileItemModel::insertItems(const KFileItemList
& items
)
882 if (items
.isEmpty()) {
886 if (m_sortRole
== TypeRole
) {
887 // Try to resolve the MIME-types synchronously to prevent a reordering of
888 // the items when sorting by type (per default MIME-types are resolved
889 // asynchronously by KFileItemModelRolesUpdater).
890 determineMimeTypes(items
, 200);
893 #ifdef KFILEITEMMODEL_DEBUG
896 kDebug() << "===========================================================";
897 kDebug() << "Inserting" << items
.count() << "items";
902 QList
<ItemData
*> sortedItems
= createItemDataList(items
);
903 KFileItemModelSortAlgorithm::sort(this, sortedItems
.begin(), sortedItems
.end());
905 #ifdef KFILEITEMMODEL_DEBUG
906 kDebug() << "[TIME] Sorting:" << timer
.elapsed();
909 KItemRangeList itemRanges
;
912 int insertedAtIndex
= -1; // Index for the current item-range
913 int insertedCount
= 0; // Count for the current item-range
914 int previouslyInsertedCount
= 0; // Sum of previously inserted items for all ranges
915 while (sourceIndex
< sortedItems
.count()) {
916 // Find target index from m_items to insert the current item
918 const int previousTargetIndex
= targetIndex
;
919 while (targetIndex
< m_itemData
.count()) {
920 if (!lessThan(m_itemData
.at(targetIndex
), sortedItems
.at(sourceIndex
))) {
926 if (targetIndex
- previousTargetIndex
> 0 && insertedAtIndex
>= 0) {
927 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
928 previouslyInsertedCount
+= insertedCount
;
929 insertedAtIndex
= targetIndex
- previouslyInsertedCount
;
933 // Insert item at the position targetIndex by transfering
934 // the ownership of the item-data from sortedItems to m_itemData.
935 // m_items will be inserted after the loop (see comment below)
936 m_itemData
.insert(targetIndex
, sortedItems
.at(sourceIndex
));
939 if (insertedAtIndex
< 0) {
940 insertedAtIndex
= targetIndex
;
941 Q_ASSERT(previouslyInsertedCount
== 0);
947 // The indexes of all m_items must be adjusted, not only the index
949 const int itemDataCount
= m_itemData
.count();
950 for (int i
= 0; i
< itemDataCount
; ++i
) {
951 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
954 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
955 emit
itemsInserted(itemRanges
);
957 #ifdef KFILEITEMMODEL_DEBUG
958 kDebug() << "[TIME] Inserting of" << items
.count() << "items:" << timer
.elapsed();
962 void KFileItemModel::removeItems(const KFileItemList
& items
)
964 if (items
.isEmpty()) {
968 #ifdef KFILEITEMMODEL_DEBUG
969 kDebug() << "Removing " << items
.count() << "items";
974 QList
<ItemData
*> sortedItems
;
975 sortedItems
.reserve(items
.count());
976 foreach (const KFileItem
& item
, items
) {
977 const int index
= m_items
.value(item
.url(), -1);
979 sortedItems
.append(m_itemData
.at(index
));
982 KFileItemModelSortAlgorithm::sort(this, sortedItems
.begin(), sortedItems
.end());
984 QList
<int> indexesToRemove
;
985 indexesToRemove
.reserve(items
.count());
987 // Calculate the item ranges that will get deleted
988 KItemRangeList itemRanges
;
989 int removedAtIndex
= -1;
990 int removedCount
= 0;
992 foreach (const ItemData
* itemData
, sortedItems
) {
993 const KFileItem
& itemToRemove
= itemData
->item
;
995 const int previousTargetIndex
= targetIndex
;
996 while (targetIndex
< m_itemData
.count()) {
997 if (m_itemData
.at(targetIndex
)->item
.url() == itemToRemove
.url()) {
1002 if (targetIndex
>= m_itemData
.count()) {
1003 kWarning() << "Item that should be deleted has not been found!";
1007 if (targetIndex
- previousTargetIndex
> 0 && removedAtIndex
>= 0) {
1008 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
1009 removedAtIndex
= targetIndex
;
1013 indexesToRemove
.append(targetIndex
);
1014 if (removedAtIndex
< 0) {
1015 removedAtIndex
= targetIndex
;
1022 for (int i
= indexesToRemove
.count() - 1; i
>= 0; --i
) {
1023 const int indexToRemove
= indexesToRemove
.at(i
);
1024 ItemData
* data
= m_itemData
.at(indexToRemove
);
1026 m_items
.remove(data
->item
.url());
1029 m_itemData
.removeAt(indexToRemove
);
1032 // The indexes of all m_items must be adjusted, not only the index
1033 // of the removed items
1034 const int itemDataCount
= m_itemData
.count();
1035 for (int i
= 0; i
< itemDataCount
; ++i
) {
1036 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
1040 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
1043 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
1044 emit
itemsRemoved(itemRanges
);
1047 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const KFileItemList
& items
) const
1049 QList
<ItemData
*> itemDataList
;
1050 itemDataList
.reserve(items
.count());
1052 foreach (const KFileItem
& item
, items
) {
1053 ItemData
* itemData
= new ItemData();
1054 itemData
->item
= item
;
1055 itemData
->values
= retrieveData(item
);
1056 itemData
->parent
= 0;
1058 const bool determineParent
= m_requestRole
[ExpandedParentsCountRole
]
1059 && itemData
->values
["expandedParentsCount"].toInt() > 0;
1060 if (determineParent
) {
1061 KUrl parentUrl
= item
.url().upUrl();
1062 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
1063 const int parentIndex
= m_items
.value(parentUrl
, -1);
1064 if (parentIndex
>= 0) {
1065 itemData
->parent
= m_itemData
.at(parentIndex
);
1067 kWarning() << "Parent item not found for" << item
.url();
1071 itemDataList
.append(itemData
);
1074 return itemDataList
;
1077 void KFileItemModel::removeExpandedItems()
1079 KFileItemList expandedItems
;
1081 const int maxIndex
= m_itemData
.count() - 1;
1082 for (int i
= 0; i
<= maxIndex
; ++i
) {
1083 const ItemData
* itemData
= m_itemData
.at(i
);
1084 if (itemData
->values
.value("expandedParentsCount").toInt() > 0) {
1085 expandedItems
.append(itemData
->item
);
1089 // The m_expandedParentsCountRoot may not get reset before all items with
1090 // a bigger count have been removed.
1091 removeItems(expandedItems
);
1093 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
1094 m_expandedDirs
.clear();
1097 void KFileItemModel::resetRoles()
1099 for (int i
= 0; i
< RolesCount
; ++i
) {
1100 m_requestRole
[i
] = false;
1104 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1106 static QHash
<QByteArray
, RoleType
> roles
;
1107 if (roles
.isEmpty()) {
1108 // Insert user visible roles that can be accessed with
1109 // KFileItemModel::roleInformation()
1111 const RoleInfoMap
* map
= rolesInfoMap(count
);
1112 for (int i
= 0; i
< count
; ++i
) {
1113 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1116 // Insert internal roles (take care to synchronize the implementation
1117 // with KFileItemModel::roleForType() in case if a change is done).
1118 roles
.insert("isDir", IsDirRole
);
1119 roles
.insert("isExpanded", IsExpandedRole
);
1120 roles
.insert("isExpandable", IsExpandableRole
);
1121 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1123 Q_ASSERT(roles
.count() == RolesCount
);
1126 return roles
.value(role
, NoRole
);
1129 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1131 static QHash
<RoleType
, QByteArray
> roles
;
1132 if (roles
.isEmpty()) {
1133 // Insert user visible roles that can be accessed with
1134 // KFileItemModel::roleInformation()
1136 const RoleInfoMap
* map
= rolesInfoMap(count
);
1137 for (int i
= 0; i
< count
; ++i
) {
1138 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1141 // Insert internal roles (take care to synchronize the implementation
1142 // with KFileItemModel::typeForRole() in case if a change is done).
1143 roles
.insert(IsDirRole
, "isDir");
1144 roles
.insert(IsExpandedRole
, "isExpanded");
1145 roles
.insert(IsExpandableRole
, "isExpandable");
1146 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1148 Q_ASSERT(roles
.count() == RolesCount
);
1151 return roles
.value(roleType
);
1154 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
) const
1156 // It is important to insert only roles that are fast to retrieve. E.g.
1157 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1158 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1159 QHash
<QByteArray
, QVariant
> data
;
1160 data
.insert("url", item
.url());
1162 const bool isDir
= item
.isDir();
1163 if (m_requestRole
[IsDirRole
]) {
1164 data
.insert("isDir", isDir
);
1167 if (m_requestRole
[NameRole
]) {
1168 data
.insert("text", item
.text());
1171 if (m_requestRole
[SizeRole
]) {
1173 data
.insert("size", QVariant());
1175 data
.insert("size", item
.size());
1179 if (m_requestRole
[DateRole
]) {
1180 // Don't use KFileItem::timeString() as this is too expensive when
1181 // having several thousands of items. Instead the formatting of the
1182 // date-time will be done on-demand by the view when the date will be shown.
1183 const KDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
1184 data
.insert("date", dateTime
.dateTime());
1187 if (m_requestRole
[PermissionsRole
]) {
1188 data
.insert("permissions", item
.permissionsString());
1191 if (m_requestRole
[OwnerRole
]) {
1192 data
.insert("owner", item
.user());
1195 if (m_requestRole
[GroupRole
]) {
1196 data
.insert("group", item
.group());
1199 if (m_requestRole
[DestinationRole
]) {
1200 QString destination
= item
.linkDest();
1201 if (destination
.isEmpty()) {
1202 destination
= QLatin1String("-");
1204 data
.insert("destination", destination
);
1207 if (m_requestRole
[PathRole
]) {
1209 if (item
.url().protocol() == QLatin1String("trash")) {
1210 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1212 path
= item
.localPath();
1215 const int index
= path
.lastIndexOf(item
.text());
1216 path
= path
.mid(0, index
- 1);
1217 data
.insert("path", path
);
1220 if (m_requestRole
[IsExpandedRole
]) {
1221 data
.insert("isExpanded", false);
1224 if (m_requestRole
[IsExpandableRole
]) {
1225 data
.insert("isExpandable", item
.isDir() && item
.url() == item
.targetUrl());
1228 if (m_requestRole
[ExpandedParentsCountRole
]) {
1229 if (m_expandedParentsCountRoot
== UninitializedExpandedParentsCountRoot
) {
1230 const KUrl rootUrl
= m_dirLister
->url();
1231 const QString protocol
= rootUrl
.protocol();
1232 const bool forceExpandedParentsCountRoot
= (protocol
== QLatin1String("trash") ||
1233 protocol
== QLatin1String("nepomuk") ||
1234 protocol
== QLatin1String("remote") ||
1235 protocol
.contains(QLatin1String("search")));
1236 if (forceExpandedParentsCountRoot
) {
1237 m_expandedParentsCountRoot
= ForceExpandedParentsCountRoot
;
1239 const QString rootDir
= rootUrl
.path(KUrl::AddTrailingSlash
);
1240 m_expandedParentsCountRoot
= rootDir
.count('/');
1244 if (m_expandedParentsCountRoot
== ForceExpandedParentsCountRoot
) {
1245 data
.insert("expandedParentsCount", -1);
1247 const QString dir
= item
.url().directory(KUrl::AppendTrailingSlash
);
1248 const int level
= dir
.count('/') - m_expandedParentsCountRoot
;
1249 data
.insert("expandedParentsCount", level
);
1253 if (item
.isMimeTypeKnown()) {
1254 data
.insert("iconName", item
.iconName());
1256 if (m_requestRole
[TypeRole
]) {
1257 data
.insert("type", item
.mimeComment());
1264 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
) const
1268 if (m_expandedParentsCountRoot
>= 0) {
1269 result
= expandedParentsCountCompare(a
, b
);
1271 // The items have parents with different expansion levels
1272 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1276 if (m_sortDirsFirst
|| m_sortRole
== SizeRole
) {
1277 const bool isDirA
= a
->item
.isDir();
1278 const bool isDirB
= b
->item
.isDir();
1279 if (isDirA
&& !isDirB
) {
1281 } else if (!isDirA
&& isDirB
) {
1286 result
= sortRoleCompare(a
, b
);
1288 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1291 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
) const
1293 const KFileItem
& itemA
= a
->item
;
1294 const KFileItem
& itemB
= b
->item
;
1298 switch (m_sortRole
) {
1300 // The name role is handled as default fallback after the switch
1304 if (itemA
.isDir()) {
1305 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1306 Q_ASSERT(itemB
.isDir());
1308 const QVariant valueA
= a
->values
.value("size");
1309 const QVariant valueB
= b
->values
.value("size");
1310 if (valueA
.isNull() && valueB
.isNull()) {
1312 } else if (valueA
.isNull()) {
1314 } else if (valueB
.isNull()) {
1317 result
= valueA
.toInt() - valueB
.toInt();
1320 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1321 Q_ASSERT(!itemB
.isDir());
1322 const KIO::filesize_t sizeA
= itemA
.size();
1323 const KIO::filesize_t sizeB
= itemB
.size();
1324 if (sizeA
> sizeB
) {
1326 } else if (sizeA
< sizeB
) {
1336 const KDateTime dateTimeA
= itemA
.time(KFileItem::ModificationTime
);
1337 const KDateTime dateTimeB
= itemB
.time(KFileItem::ModificationTime
);
1338 if (dateTimeA
< dateTimeB
) {
1340 } else if (dateTimeA
> dateTimeB
) {
1347 result
= a
->values
.value("rating").toInt() - b
->values
.value("rating").toInt();
1351 case ImageSizeRole
: {
1352 // Alway use a natural comparing to interpret the numbers of a string like
1353 // "1600 x 1200" for having a correct sorting.
1354 result
= KStringHandler::naturalCompare(a
->values
.value("imageSize").toString(),
1355 b
->values
.value("imageSize").toString(),
1360 case PermissionsRole
:
1364 case DestinationRole
:
1368 const QByteArray role
= roleForType(m_sortRole
);
1369 result
= QString::compare(a
->values
.value(role
).toString(),
1370 b
->values
.value(role
).toString());
1379 // The current sort role was sufficient to define an order
1383 // Fallback #1: Compare the text of the items
1384 result
= stringCompare(itemA
.text(), itemB
.text());
1389 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1390 result
= stringCompare(itemA
.name(m_caseSensitivity
== Qt::CaseInsensitive
),
1391 itemB
.name(m_caseSensitivity
== Qt::CaseInsensitive
));
1396 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1397 // equal. In this case a comparison of the URL is done which is unique in all cases
1398 // within KDirLister.
1399 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1402 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
) const
1404 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1405 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1406 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1407 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1409 if (m_caseSensitivity
== Qt::CaseInsensitive
) {
1410 const int result
= m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseInsensitive
)
1411 : QString::compare(a
, b
, Qt::CaseInsensitive
);
1413 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1414 // comparison, still a deterministic sort order is required. A case sensitive
1415 // comparison is done as fallback.
1420 return m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseSensitive
)
1421 : QString::compare(a
, b
, Qt::CaseSensitive
);
1424 int KFileItemModel::expandedParentsCountCompare(const ItemData
* a
, const ItemData
* b
) const
1426 const KUrl urlA
= a
->item
.url();
1427 const KUrl urlB
= b
->item
.url();
1428 if (urlA
.directory() == urlB
.directory()) {
1429 // Both items have the same directory as parent
1433 // Check whether one item is the parent of the other item
1434 if (urlA
.isParentOf(urlB
)) {
1435 return (sortOrder() == Qt::AscendingOrder
) ? -1 : +1;
1436 } else if (urlB
.isParentOf(urlA
)) {
1437 return (sortOrder() == Qt::AscendingOrder
) ? +1 : -1;
1440 // Determine the maximum common path of both items and
1441 // remember the index in 'index'
1442 const QString pathA
= urlA
.path();
1443 const QString pathB
= urlB
.path();
1445 const int maxIndex
= qMin(pathA
.length(), pathB
.length()) - 1;
1447 while (index
<= maxIndex
&& pathA
.at(index
) == pathB
.at(index
)) {
1450 if (index
> maxIndex
) {
1453 while ((pathA
.at(index
) != QLatin1Char('/') || pathB
.at(index
) != QLatin1Char('/')) && index
> 0) {
1457 // Determine the first sub-path after the common path and
1458 // check whether it represents a directory or already a file
1460 const QString subPathA
= subPath(a
->item
, pathA
, index
, &isDirA
);
1462 const QString subPathB
= subPath(b
->item
, pathB
, index
, &isDirB
);
1464 if (m_sortDirsFirst
|| m_sortRole
== SizeRole
) {
1465 if (isDirA
&& !isDirB
) {
1466 return (sortOrder() == Qt::AscendingOrder
) ? -1 : +1;
1467 } else if (!isDirA
&& isDirB
) {
1468 return (sortOrder() == Qt::AscendingOrder
) ? +1 : -1;
1472 // Compare the items of the parents that represent the first
1473 // different path after the common path.
1474 const QString parentPathA
= pathA
.left(index
) + subPathA
;
1475 const QString parentPathB
= pathB
.left(index
) + subPathB
;
1477 const ItemData
* parentA
= a
;
1478 while (parentA
&& parentA
->item
.url().path() != parentPathA
) {
1479 parentA
= parentA
->parent
;
1482 const ItemData
* parentB
= b
;
1483 while (parentB
&& parentB
->item
.url().path() != parentPathB
) {
1484 parentB
= parentB
->parent
;
1487 if (parentA
&& parentB
) {
1488 return sortRoleCompare(parentA
, parentB
);
1491 kWarning() << "Child items without parent detected:" << a
->item
.url() << b
->item
.url();
1492 return QString::compare(urlA
.url(), urlB
.url(), Qt::CaseSensitive
);
1495 QString
KFileItemModel::subPath(const KFileItem
& item
,
1496 const QString
& itemPath
,
1501 const int pathIndex
= itemPath
.indexOf('/', start
+ 1);
1502 *isDir
= (pathIndex
> 0) || item
.isDir();
1503 return itemPath
.mid(start
, pathIndex
- start
);
1506 bool KFileItemModel::useMaximumUpdateInterval() const
1508 return !m_dirLister
->url().isLocalFile();
1511 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1513 Q_ASSERT(!m_itemData
.isEmpty());
1515 const int maxIndex
= count() - 1;
1516 QList
<QPair
<int, QVariant
> > groups
;
1520 bool isLetter
= false;
1521 for (int i
= 0; i
<= maxIndex
; ++i
) {
1522 if (isChildItem(i
)) {
1526 const QString name
= m_itemData
.at(i
)->values
.value("text").toString();
1528 // Use the first character of the name as group indication
1529 QChar newFirstChar
= name
.at(0).toUpper();
1530 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1531 newFirstChar
= name
.at(1).toUpper();
1534 if (firstChar
!= newFirstChar
) {
1535 QString newGroupValue
;
1536 if (newFirstChar
>= QLatin1Char('A') && newFirstChar
<= QLatin1Char('Z')) {
1537 // Apply group 'A' - 'Z'
1538 newGroupValue
= newFirstChar
;
1540 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
1541 // Apply group '0 - 9' for any name that starts with a digit
1542 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
1546 // If the current group is 'A' - 'Z' check whether a locale character
1547 // fits into the existing group.
1548 // TODO: This does not work in the case if e.g. the group 'O' starts with
1549 // an umlaut 'O' -> provide unit-test to document this known issue
1550 const QChar
prevChar(firstChar
.unicode() - ushort(1));
1551 const QChar
nextChar(firstChar
.unicode() + ushort(1));
1552 const QString
currChar(newFirstChar
);
1553 const bool partOfCurrentGroup
= currChar
.localeAwareCompare(prevChar
) > 0 &&
1554 currChar
.localeAwareCompare(nextChar
) < 0;
1555 if (partOfCurrentGroup
) {
1559 newGroupValue
= i18nc("@title:group", "Others");
1563 if (newGroupValue
!= groupValue
) {
1564 groupValue
= newGroupValue
;
1565 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1568 firstChar
= newFirstChar
;
1574 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
1576 Q_ASSERT(!m_itemData
.isEmpty());
1578 const int maxIndex
= count() - 1;
1579 QList
<QPair
<int, QVariant
> > groups
;
1582 for (int i
= 0; i
<= maxIndex
; ++i
) {
1583 if (isChildItem(i
)) {
1587 const KFileItem
& item
= m_itemData
.at(i
)->item
;
1588 const KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
1589 QString newGroupValue
;
1590 if (!item
.isNull() && item
.isDir()) {
1591 newGroupValue
= i18nc("@title:group Size", "Folders");
1592 } else if (fileSize
< 5 * 1024 * 1024) {
1593 newGroupValue
= i18nc("@title:group Size", "Small");
1594 } else if (fileSize
< 10 * 1024 * 1024) {
1595 newGroupValue
= i18nc("@title:group Size", "Medium");
1597 newGroupValue
= i18nc("@title:group Size", "Big");
1600 if (newGroupValue
!= groupValue
) {
1601 groupValue
= newGroupValue
;
1602 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1609 QList
<QPair
<int, QVariant
> > KFileItemModel::dateRoleGroups() const
1611 Q_ASSERT(!m_itemData
.isEmpty());
1613 const int maxIndex
= count() - 1;
1614 QList
<QPair
<int, QVariant
> > groups
;
1616 const QDate currentDate
= KDateTime::currentLocalDateTime().date();
1618 int yearForCurrentWeek
= 0;
1619 int currentWeek
= currentDate
.weekNumber(&yearForCurrentWeek
);
1620 if (yearForCurrentWeek
== currentDate
.year() + 1) {
1624 QDate previousModifiedDate
;
1626 for (int i
= 0; i
<= maxIndex
; ++i
) {
1627 if (isChildItem(i
)) {
1631 const KDateTime modifiedTime
= m_itemData
.at(i
)->item
.time(KFileItem::ModificationTime
);
1632 const QDate modifiedDate
= modifiedTime
.date();
1633 if (modifiedDate
== previousModifiedDate
) {
1634 // The current item is in the same group as the previous item
1637 previousModifiedDate
= modifiedDate
;
1639 const int daysDistance
= modifiedDate
.daysTo(currentDate
);
1641 int yearForModifiedWeek
= 0;
1642 int modifiedWeek
= modifiedDate
.weekNumber(&yearForModifiedWeek
);
1643 if (yearForModifiedWeek
== modifiedDate
.year() + 1) {
1647 QString newGroupValue
;
1648 if (currentDate
.year() == modifiedDate
.year() && currentDate
.month() == modifiedDate
.month()) {
1649 if (modifiedWeek
> currentWeek
) {
1650 // Usecase: modified date = 2010-01-01, current date = 2010-01-22
1651 // modified week = 53, current week = 3
1654 switch (currentWeek
- modifiedWeek
) {
1656 switch (daysDistance
) {
1657 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
1658 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
1659 default: newGroupValue
= modifiedTime
.toString(i18nc("@title:group The week day name: %A", "%A"));
1663 newGroupValue
= i18nc("@title:group Date", "Last Week");
1666 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
1669 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
1673 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
1679 const QDate lastMonthDate
= currentDate
.addMonths(-1);
1680 if (lastMonthDate
.year() == modifiedDate
.year() && lastMonthDate
.month() == modifiedDate
.month()) {
1681 if (daysDistance
== 1) {
1682 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Yesterday (%B, %Y)"));
1683 } else if (daysDistance
<= 7) {
1684 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)"));
1685 } else if (daysDistance
<= 7 * 2) {
1686 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)"));
1687 } else if (daysDistance
<= 7 * 3) {
1688 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)"));
1689 } else if (daysDistance
<= 7 * 4) {
1690 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)"));
1692 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"));
1695 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"));
1699 if (newGroupValue
!= groupValue
) {
1700 groupValue
= newGroupValue
;
1701 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1708 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
1710 Q_ASSERT(!m_itemData
.isEmpty());
1712 const int maxIndex
= count() - 1;
1713 QList
<QPair
<int, QVariant
> > groups
;
1715 QString permissionsString
;
1717 for (int i
= 0; i
<= maxIndex
; ++i
) {
1718 if (isChildItem(i
)) {
1722 const ItemData
* itemData
= m_itemData
.at(i
);
1723 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
1724 if (newPermissionsString
== permissionsString
) {
1727 permissionsString
= newPermissionsString
;
1729 const QFileInfo
info(itemData
->item
.url().pathOrUrl());
1733 if (info
.permission(QFile::ReadUser
)) {
1734 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1736 if (info
.permission(QFile::WriteUser
)) {
1737 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1739 if (info
.permission(QFile::ExeUser
)) {
1740 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1742 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
1746 if (info
.permission(QFile::ReadGroup
)) {
1747 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1749 if (info
.permission(QFile::WriteGroup
)) {
1750 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1752 if (info
.permission(QFile::ExeGroup
)) {
1753 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1755 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
1757 // Set others string
1759 if (info
.permission(QFile::ReadOther
)) {
1760 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1762 if (info
.permission(QFile::WriteOther
)) {
1763 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1765 if (info
.permission(QFile::ExeOther
)) {
1766 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1768 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
1770 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
1771 if (newGroupValue
!= groupValue
) {
1772 groupValue
= newGroupValue
;
1773 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1780 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
1782 Q_ASSERT(!m_itemData
.isEmpty());
1784 const int maxIndex
= count() - 1;
1785 QList
<QPair
<int, QVariant
> > groups
;
1787 int groupValue
= -1;
1788 for (int i
= 0; i
<= maxIndex
; ++i
) {
1789 if (isChildItem(i
)) {
1792 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
1793 if (newGroupValue
!= groupValue
) {
1794 groupValue
= newGroupValue
;
1795 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1802 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
1804 Q_ASSERT(!m_itemData
.isEmpty());
1806 const int maxIndex
= count() - 1;
1807 QList
<QPair
<int, QVariant
> > groups
;
1809 bool isFirstGroupValue
= true;
1811 for (int i
= 0; i
<= maxIndex
; ++i
) {
1812 if (isChildItem(i
)) {
1815 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
1816 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
1817 groupValue
= newGroupValue
;
1818 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1819 isFirstGroupValue
= false;
1826 KFileItemList
KFileItemModel::childItems(const KFileItem
& item
) const
1828 KFileItemList items
;
1830 int index
= m_items
.value(item
.url(), -1);
1832 const int parentLevel
= m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt();
1834 while (index
< m_itemData
.count() && m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt() > parentLevel
) {
1835 items
.append(m_itemData
.at(index
)->item
);
1843 void KFileItemModel::emitSortProgress(int resolvedCount
)
1845 // Be tolerant against a resolvedCount with a wrong range.
1846 // Although there should not be a case where KFileItemModelRolesUpdater
1847 // (= caller) provides a wrong range, it is important to emit
1848 // a useful progress information even if there is an unexpected
1849 // implementation issue.
1851 const int itemCount
= count();
1852 if (resolvedCount
>= itemCount
) {
1853 m_sortingProgressPercent
= -1;
1854 if (m_resortAllItemsTimer
->isActive()) {
1855 m_resortAllItemsTimer
->stop();
1859 emit
directorySortingProgress(100);
1860 } else if (itemCount
> 0) {
1861 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
1863 const int progress
= resolvedCount
* 100 / itemCount
;
1864 if (m_sortingProgressPercent
!= progress
) {
1865 m_sortingProgressPercent
= progress
;
1866 emit
directorySortingProgress(progress
);
1871 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
1873 static const RoleInfoMap rolesInfoMap
[] = {
1874 // | role | roleType | role translation | group translation | requires Nepomuk | requires indexer
1875 { 0, NoRole
, 0, 0, 0, 0, false, false },
1876 { "text", NameRole
, I18N_NOOP2_NOSTRIP("@label", "Name"), 0, 0, false, false },
1877 { "size", SizeRole
, I18N_NOOP2_NOSTRIP("@label", "Size"), 0, 0, false, false },
1878 { "date", DateRole
, I18N_NOOP2_NOSTRIP("@label", "Date"), 0, 0, false, false },
1879 { "type", TypeRole
, I18N_NOOP2_NOSTRIP("@label", "Type"), 0, 0, false, false },
1880 { "rating", RatingRole
, I18N_NOOP2_NOSTRIP("@label", "Rating"), 0, 0, true, false },
1881 { "tags", TagsRole
, I18N_NOOP2_NOSTRIP("@label", "Tags"), 0, 0, true, false },
1882 { "comment", CommentRole
, I18N_NOOP2_NOSTRIP("@label", "Comment"), 0, 0, true, false },
1883 { "wordCount", WordCountRole
, I18N_NOOP2_NOSTRIP("@label", "Word Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
1884 { "lineCount", LineCountRole
, I18N_NOOP2_NOSTRIP("@label", "Line Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
1885 { "imageSize", ImageSizeRole
, I18N_NOOP2_NOSTRIP("@label", "Image Size"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
1886 { "orientation", OrientationRole
, I18N_NOOP2_NOSTRIP("@label", "Orientation"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
1887 { "artist", ArtistRole
, I18N_NOOP2_NOSTRIP("@label", "Artist"), I18N_NOOP2_NOSTRIP("@label", "Music"), true, true },
1888 { "album", AlbumRole
, I18N_NOOP2_NOSTRIP("@label", "Album"), I18N_NOOP2_NOSTRIP("@label", "Music"), true, true },
1889 { "duration", DurationRole
, I18N_NOOP2_NOSTRIP("@label", "Duration"), I18N_NOOP2_NOSTRIP("@label", "Music"), true, true },
1890 { "track", TrackRole
, I18N_NOOP2_NOSTRIP("@label", "Track"), I18N_NOOP2_NOSTRIP("@label", "Music"), true, true },
1891 { "path", PathRole
, I18N_NOOP2_NOSTRIP("@label", "Path"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1892 { "destination", DestinationRole
, I18N_NOOP2_NOSTRIP("@label", "Link Destination"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1893 { "copiedFrom", CopiedFromRole
, I18N_NOOP2_NOSTRIP("@label", "Copied From"), I18N_NOOP2_NOSTRIP("@label", "Other"), true, false },
1894 { "permissions", PermissionsRole
, I18N_NOOP2_NOSTRIP("@label", "Permissions"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1895 { "owner", OwnerRole
, I18N_NOOP2_NOSTRIP("@label", "Owner"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1896 { "group", GroupRole
, I18N_NOOP2_NOSTRIP("@label", "User Group"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1899 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
1900 return rolesInfoMap
;
1903 void KFileItemModel::determineMimeTypes(const KFileItemList
& items
, int timeout
)
1905 QElapsedTimer timer
;
1907 foreach (KFileItem item
, items
) {
1908 item
.determineMimeType();
1909 if (timer
.elapsed() > timeout
) {
1910 // Don't block the user interface, let the remaining items
1911 // be resolved asynchronously.
1917 #include "kfileitemmodel.moc"