1 /***************************************************************************
2 * Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
4 * This program is free software; you can redistribute it and/or modify *
5 * it under the terms of the GNU General Public License as published by *
6 * the Free Software Foundation; either version 2 of the License, or *
7 * (at your option) any later version. *
9 * This program is distributed in the hope that it will be useful, *
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
12 * GNU General Public License for more details. *
14 * You should have received a copy of the GNU General Public License *
15 * along with this program; if not, write to the *
16 * Free Software Foundation, Inc., *
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
18 ***************************************************************************/
20 #include "kfileitemmodel.h"
23 #include <KGlobalSettings>
25 #include <KStringHandler>
28 #include "private/kfileitemmodelsortalgorithm.h"
29 #include "private/kfileitemmodeldirlister.h"
31 #include <QApplication>
35 // #define KFILEITEMMODEL_DEBUG
37 KFileItemModel::KFileItemModel(QObject
* parent
) :
38 KItemModelBase("text", parent
),
40 m_naturalSorting(KGlobalSettings::naturalSorting()),
41 m_sortDirsFirst(true),
43 m_sortingProgressPercent(-1),
45 m_caseSensitivity(Qt::CaseInsensitive
),
51 m_maximumUpdateIntervalTimer(0),
52 m_resortAllItemsTimer(0),
53 m_pendingItemsToInsert(),
55 m_expandedParentsCountRoot(UninitializedExpandedParentsCountRoot
),
59 m_dirLister
= new KFileItemModelDirLister(this);
60 m_dirLister
->setAutoUpdate(true);
61 m_dirLister
->setDelayedMimeTypes(true);
62 m_dirLister
->setMainWindow(qApp
->activeWindow());
64 connect(m_dirLister
, SIGNAL(started(KUrl
)), this, SIGNAL(directoryLoadingStarted()));
65 connect(m_dirLister
, SIGNAL(canceled()), this, SLOT(slotCanceled()));
66 connect(m_dirLister
, SIGNAL(completed(KUrl
)), this, SLOT(slotCompleted()));
67 connect(m_dirLister
, SIGNAL(newItems(KFileItemList
)), this, SLOT(slotNewItems(KFileItemList
)));
68 connect(m_dirLister
, SIGNAL(itemsDeleted(KFileItemList
)), this, SLOT(slotItemsDeleted(KFileItemList
)));
69 connect(m_dirLister
, SIGNAL(refreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)), this, SLOT(slotRefreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)));
70 connect(m_dirLister
, SIGNAL(clear()), this, SLOT(slotClear()));
71 connect(m_dirLister
, SIGNAL(clear(KUrl
)), this, SLOT(slotClear(KUrl
)));
72 connect(m_dirLister
, SIGNAL(infoMessage(QString
)), this, SIGNAL(infoMessage(QString
)));
73 connect(m_dirLister
, SIGNAL(errorMessage(QString
)), this, SIGNAL(errorMessage(QString
)));
74 connect(m_dirLister
, SIGNAL(redirection(KUrl
,KUrl
)), this, SIGNAL(directoryRedirection(KUrl
,KUrl
)));
76 // Apply default roles that should be determined
78 m_requestRole
[NameRole
] = true;
79 m_requestRole
[IsDirRole
] = true;
80 m_requestRole
[IsLinkRole
] = true;
81 m_roles
.insert("text");
82 m_roles
.insert("isDir");
83 m_roles
.insert("isLink");
85 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
86 // before the completed() or canceled() signal has been emitted.
87 m_maximumUpdateIntervalTimer
= new QTimer(this);
88 m_maximumUpdateIntervalTimer
->setInterval(2000);
89 m_maximumUpdateIntervalTimer
->setSingleShot(true);
90 connect(m_maximumUpdateIntervalTimer
, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
92 // When changing the value of an item which represents the sort-role a resorting must be
93 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
94 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
95 // resorting is postponed until the timer has been exceeded.
96 m_resortAllItemsTimer
= new QTimer(this);
97 m_resortAllItemsTimer
->setInterval(500);
98 m_resortAllItemsTimer
->setSingleShot(true);
99 connect(m_resortAllItemsTimer
, SIGNAL(timeout()), this, SLOT(resortAllItems()));
101 connect(KGlobalSettings::self(), SIGNAL(naturalSortingChanged()), this, SLOT(slotNaturalSortingChanged()));
104 KFileItemModel::~KFileItemModel()
106 qDeleteAll(m_itemData
);
110 void KFileItemModel::loadDirectory(const KUrl
& url
)
112 m_dirLister
->openUrl(url
);
115 void KFileItemModel::refreshDirectory(const KUrl
& url
)
117 m_dirLister
->openUrl(url
, KDirLister::Reload
);
120 KUrl
KFileItemModel::directory() const
122 return m_dirLister
->url();
125 void KFileItemModel::cancelDirectoryLoading()
130 int KFileItemModel::count() const
132 return m_itemData
.count();
135 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
137 if (index
>= 0 && index
< count()) {
138 return m_itemData
.at(index
)->values
;
140 return QHash
<QByteArray
, QVariant
>();
143 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
145 if (index
< 0 || index
>= count()) {
149 QHash
<QByteArray
, QVariant
> currentValues
= m_itemData
.at(index
)->values
;
151 // Determine which roles have been changed
152 QSet
<QByteArray
> changedRoles
;
153 QHashIterator
<QByteArray
, QVariant
> it(values
);
154 while (it
.hasNext()) {
156 const QByteArray role
= it
.key();
157 const QVariant value
= it
.value();
159 if (currentValues
[role
] != value
) {
160 currentValues
[role
] = value
;
161 changedRoles
.insert(role
);
165 if (changedRoles
.isEmpty()) {
169 m_itemData
[index
]->values
= currentValues
;
170 if (changedRoles
.contains("text")) {
171 KUrl url
= m_itemData
[index
]->item
.url();
172 url
.setFileName(currentValues
["text"].toString());
173 m_itemData
[index
]->item
.setUrl(url
);
176 emit
itemsChanged(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
178 if (changedRoles
.contains(sortRole())) {
179 m_resortAllItemsTimer
->start();
185 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
187 if (dirsFirst
!= m_sortDirsFirst
) {
188 m_sortDirsFirst
= dirsFirst
;
193 bool KFileItemModel::sortDirectoriesFirst() const
195 return m_sortDirsFirst
;
198 void KFileItemModel::setShowHiddenFiles(bool show
)
200 m_dirLister
->setShowingDotFiles(show
);
201 m_dirLister
->emitChanges();
207 bool KFileItemModel::showHiddenFiles() const
209 return m_dirLister
->showingDotFiles();
212 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
214 m_dirLister
->setDirOnlyMode(enabled
);
217 bool KFileItemModel::showDirectoriesOnly() const
219 return m_dirLister
->dirOnlyMode();
222 QMimeData
* KFileItemModel::createMimeData(const QSet
<int>& indexes
) const
224 QMimeData
* data
= new QMimeData();
226 // The following code has been taken from KDirModel::mimeData()
227 // (kdelibs/kio/kio/kdirmodel.cpp)
228 // Copyright (C) 2006 David Faure <faure@kde.org>
230 KUrl::List mostLocalUrls
;
231 bool canUseMostLocalUrls
= true;
233 QSetIterator
<int> it(indexes
);
234 while (it
.hasNext()) {
235 const int index
= it
.next();
236 const KFileItem item
= fileItem(index
);
237 if (!item
.isNull()) {
241 mostLocalUrls
<< item
.mostLocalUrl(isLocal
);
243 canUseMostLocalUrls
= false;
248 const bool different
= canUseMostLocalUrls
&& mostLocalUrls
!= urls
;
249 urls
= KDirModel::simplifiedUrlList(urls
); // TODO: Check if we still need KDirModel for this in KDE 5.0
251 mostLocalUrls
= KDirModel::simplifiedUrlList(mostLocalUrls
);
252 urls
.populateMimeData(mostLocalUrls
, data
);
254 urls
.populateMimeData(data
);
260 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
262 startFromIndex
= qMax(0, startFromIndex
);
263 for (int i
= startFromIndex
; i
< count(); ++i
) {
264 if (data(i
)["text"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
268 for (int i
= 0; i
< startFromIndex
; ++i
) {
269 if (data(i
)["text"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
276 bool KFileItemModel::supportsDropping(int index
) const
278 const KFileItem item
= fileItem(index
);
279 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
282 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
284 static QHash
<QByteArray
, QString
> description
;
285 if (description
.isEmpty()) {
287 const RoleInfoMap
* map
= rolesInfoMap(count
);
288 for (int i
= 0; i
< count
; ++i
) {
289 description
.insert(map
[i
].role
, map
[i
].roleTranslation
);
293 return description
.value(role
);
296 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
298 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
299 #ifdef KFILEITEMMODEL_DEBUG
303 switch (typeForRole(sortRole())) {
304 case NameRole
: m_groups
= nameRoleGroups(); break;
305 case SizeRole
: m_groups
= sizeRoleGroups(); break;
306 case DateRole
: m_groups
= dateRoleGroups(); break;
307 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
308 case RatingRole
: m_groups
= ratingRoleGroups(); break;
309 default: m_groups
= genericStringRoleGroups(sortRole()); break;
312 #ifdef KFILEITEMMODEL_DEBUG
313 kDebug() << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
320 KFileItem
KFileItemModel::fileItem(int index
) const
322 if (index
>= 0 && index
< count()) {
323 return m_itemData
.at(index
)->item
;
329 KFileItem
KFileItemModel::fileItem(const KUrl
& url
) const
331 const int index
= m_items
.value(url
, -1);
333 return m_itemData
.at(index
)->item
;
338 int KFileItemModel::index(const KFileItem
& item
) const
344 return m_items
.value(item
.url(), -1);
347 int KFileItemModel::index(const KUrl
& url
) const
349 KUrl urlToFind
= url
;
350 urlToFind
.adjustPath(KUrl::RemoveTrailingSlash
);
351 return m_items
.value(urlToFind
, -1);
354 KFileItem
KFileItemModel::rootItem() const
356 return m_dirLister
->rootItem();
359 void KFileItemModel::clear()
364 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
366 if (m_roles
== roles
) {
372 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
373 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
374 if (supportedExpanding
&& !willSupportExpanding
) {
375 // No expanding is supported anymore. Take care to delete all items that have an expansion level
376 // that is not 0 (and hence are part of an expanded item).
377 removeExpandedItems();
384 QSetIterator
<QByteArray
> it(roles
);
385 while (it
.hasNext()) {
386 const QByteArray
& role
= it
.next();
387 m_requestRole
[typeForRole(role
)] = true;
391 // Update m_data with the changed requested roles
392 const int maxIndex
= count() - 1;
393 for (int i
= 0; i
<= maxIndex
; ++i
) {
394 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
);
397 kWarning() << "TODO: Emitting itemsChanged() with no information what has changed!";
398 emit
itemsChanged(KItemRangeList() << KItemRange(0, count()), QSet
<QByteArray
>());
402 QSet
<QByteArray
> KFileItemModel::roles() const
407 bool KFileItemModel::setExpanded(int index
, bool expanded
)
409 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
413 QHash
<QByteArray
, QVariant
> values
;
414 values
.insert("isExpanded", expanded
);
415 if (!setData(index
, values
)) {
419 const KUrl url
= m_itemData
.at(index
)->item
.url();
421 m_expandedDirs
.insert(url
);
422 m_dirLister
->openUrl(url
, KDirLister::Keep
);
424 m_expandedDirs
.remove(url
);
425 m_dirLister
->stop(url
);
428 KFileItemList itemsToRemove
;
429 const int expandedParentsCount
= data(index
)["expandedParentsCount"].toInt();
431 while (index
< count() && data(index
)["expandedParentsCount"].toInt() > expandedParentsCount
) {
432 itemsToRemove
.append(m_itemData
.at(index
)->item
);
435 removeItems(itemsToRemove
);
441 bool KFileItemModel::isExpanded(int index
) const
443 if (index
>= 0 && index
< count()) {
444 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
449 bool KFileItemModel::isExpandable(int index
) const
451 if (index
>= 0 && index
< count()) {
452 return m_itemData
.at(index
)->values
.value("isExpandable").toBool();
457 int KFileItemModel::expandedParentsCount(int index
) const
459 if (index
>= 0 && index
< count()) {
460 const int parentsCount
= m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt();
461 if (parentsCount
> 0) {
468 QSet
<KUrl
> KFileItemModel::expandedDirectories() const
470 return m_expandedDirs
;
473 void KFileItemModel::restoreExpandedDirectories(const QSet
<KUrl
>& urls
)
475 m_urlsToExpand
= urls
;
478 void KFileItemModel::expandParentDirectories(const KUrl
& url
)
480 const int pos
= m_dirLister
->url().path().length();
482 // Assure that each sub-path of the URL that should be
483 // expanded is added to m_urlsToExpand. KDirLister
484 // does not care whether the parent-URL has already been
486 KUrl urlToExpand
= m_dirLister
->url();
487 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator());
488 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
489 urlToExpand
.addPath(subDirs
.at(i
));
490 m_urlsToExpand
.insert(urlToExpand
);
493 // KDirLister::open() must called at least once to trigger an initial
494 // loading. The pending URLs that must be restored are handled
495 // in slotCompleted().
496 QSetIterator
<KUrl
> it2(m_urlsToExpand
);
497 while (it2
.hasNext()) {
498 const int idx
= index(it2
.next());
499 if (idx
>= 0 && !isExpanded(idx
)) {
500 setExpanded(idx
, true);
506 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
508 if (m_filter
.pattern() != nameFilter
) {
509 dispatchPendingItemsToInsert();
511 m_filter
.setPattern(nameFilter
);
513 // Check which shown items from m_itemData must get
514 // hidden and hence moved to m_filteredItems.
515 KFileItemList newFilteredItems
;
517 foreach (ItemData
* itemData
, m_itemData
) {
518 if (!m_filter
.matches(itemData
->item
)) {
519 // Only filter non-expanded items as child items may never
520 // exist without a parent item
521 if (!itemData
->values
.value("isExpanded").toBool()) {
522 newFilteredItems
.append(itemData
->item
);
523 m_filteredItems
.insert(itemData
->item
);
528 removeItems(newFilteredItems
);
530 // Check which hidden items from m_filteredItems should
531 // get visible again and hence removed from m_filteredItems.
532 KFileItemList newVisibleItems
;
534 QMutableSetIterator
<KFileItem
> it(m_filteredItems
);
535 while (it
.hasNext()) {
536 const KFileItem item
= it
.next();
537 if (m_filter
.matches(item
)) {
538 newVisibleItems
.append(item
);
543 insertItems(newVisibleItems
);
547 QString
KFileItemModel::nameFilter() const
549 return m_filter
.pattern();
552 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
554 static QList
<RoleInfo
> rolesInfo
;
555 if (rolesInfo
.isEmpty()) {
557 const RoleInfoMap
* map
= rolesInfoMap(count
);
558 for (int i
= 0; i
< count
; ++i
) {
559 if (map
[i
].roleType
!= NoRole
) {
561 info
.role
= map
[i
].role
;
562 info
.translation
= map
[i
].roleTranslation
;
563 info
.group
= map
[i
].groupTranslation
;
564 info
.requiresNepomuk
= map
[i
].requiresNepomuk
;
565 info
.requiresIndexer
= map
[i
].requiresIndexer
;
566 rolesInfo
.append(info
);
574 void KFileItemModel::onGroupedSortingChanged(bool current
)
580 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
583 m_sortRole
= typeForRole(current
);
585 #ifdef KFILEITEMMODEL_DEBUG
586 if (!m_requestRole
[m_sortRole
]) {
587 kWarning() << "The sort-role has been changed to a role that has not been received yet";
594 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
601 void KFileItemModel::resortAllItems()
603 m_resortAllItemsTimer
->stop();
605 const int itemCount
= count();
606 if (itemCount
<= 0) {
610 #ifdef KFILEITEMMODEL_DEBUG
613 kDebug() << "===========================================================";
614 kDebug() << "Resorting" << itemCount
<< "items";
617 // Remember the order of the current URLs so
618 // that it can be determined which indexes have
619 // been moved because of the resorting.
621 oldUrls
.reserve(itemCount
);
622 foreach (const ItemData
* itemData
, m_itemData
) {
623 oldUrls
.append(itemData
->item
.url());
630 KFileItemModelSortAlgorithm::sort(this, m_itemData
.begin(), m_itemData
.end());
631 for (int i
= 0; i
< itemCount
; ++i
) {
632 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
635 // Determine the indexes that have been moved
636 QList
<int> movedToIndexes
;
637 movedToIndexes
.reserve(itemCount
);
638 for (int i
= 0; i
< itemCount
; i
++) {
639 const int newIndex
= m_items
.value(oldUrls
.at(i
).url());
640 movedToIndexes
.append(newIndex
);
643 // Don't check whether items have really been moved and always emit a
644 // itemsMoved() signal after resorting: In case of grouped items
645 // the groups might change even if the items themselves don't change their
646 // position. Let the receiver of the signal decide whether a check for moved
647 // items makes sense.
648 emit
itemsMoved(KItemRange(0, itemCount
), movedToIndexes
);
650 #ifdef KFILEITEMMODEL_DEBUG
651 kDebug() << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
655 void KFileItemModel::slotCompleted()
657 dispatchPendingItemsToInsert();
659 if (!m_urlsToExpand
.isEmpty()) {
660 // Try to find a URL that can be expanded.
661 // Note that the parent folder must be expanded before any of its subfolders become visible.
662 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
663 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
664 foreach (const KUrl
& url
, m_urlsToExpand
) {
665 const int index
= m_items
.value(url
, -1);
667 m_urlsToExpand
.remove(url
);
668 if (setExpanded(index
, true)) {
669 // The dir lister has been triggered. This slot will be called
670 // again after the directory has been expanded.
676 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
677 // if these URLs have been deleted in the meantime.
678 m_urlsToExpand
.clear();
681 emit
directoryLoadingCompleted();
684 void KFileItemModel::slotCanceled()
686 m_maximumUpdateIntervalTimer
->stop();
687 dispatchPendingItemsToInsert();
690 void KFileItemModel::slotNewItems(const KFileItemList
& items
)
692 Q_ASSERT(!items
.isEmpty());
694 if (m_requestRole
[ExpandedParentsCountRole
] && m_expandedParentsCountRoot
>= 0) {
695 // To be able to compare whether the new items may be inserted as children
696 // of a parent item the pending items must be added to the model first.
697 dispatchPendingItemsToInsert();
699 KFileItem item
= items
.first();
701 // If the expanding of items is enabled, the call
702 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
703 // might result in emitting the same items twice due to the Keep-parameter.
704 // This case happens if an item gets expanded, collapsed and expanded again
705 // before the items could be loaded for the first expansion.
706 const int index
= m_items
.value(item
.url(), -1);
708 // The items are already part of the model.
712 // KDirLister keeps the children of items that got expanded once even if
713 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
714 // checked whether the parent for new items is still expanded.
715 KUrl parentUrl
= item
.url().upUrl();
716 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
717 const int parentIndex
= m_items
.value(parentUrl
, -1);
718 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
719 // The parent is not expanded.
724 if (m_filter
.pattern().isEmpty()) {
725 m_pendingItemsToInsert
.append(items
);
727 // The name-filter is active. Hide filtered items
728 // before inserting them into the model and remember
729 // the filtered items in m_filteredItems.
730 KFileItemList filteredItems
;
731 foreach (const KFileItem
& item
, items
) {
732 if (m_filter
.matches(item
)) {
733 filteredItems
.append(item
);
735 m_filteredItems
.insert(item
);
739 m_pendingItemsToInsert
.append(filteredItems
);
742 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer
->isActive()) {
743 // Assure that items get dispatched if no completed() or canceled() signal is
744 // emitted during the maximum update interval.
745 m_maximumUpdateIntervalTimer
->start();
749 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
751 dispatchPendingItemsToInsert();
753 KFileItemList itemsToRemove
= items
;
754 if (m_requestRole
[ExpandedParentsCountRole
] && m_expandedParentsCountRoot
>= 0) {
755 // Assure that removing a parent item also results in removing all children
756 foreach (const KFileItem
& item
, items
) {
757 itemsToRemove
.append(childItems(item
));
761 if (!m_filteredItems
.isEmpty()) {
762 foreach (const KFileItem
& item
, itemsToRemove
) {
763 m_filteredItems
.remove(item
);
767 removeItems(itemsToRemove
);
770 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
772 Q_ASSERT(!items
.isEmpty());
773 #ifdef KFILEITEMMODEL_DEBUG
774 kDebug() << "Refreshing" << items
.count() << "items";
779 // Get the indexes of all items that have been refreshed
781 indexes
.reserve(items
.count());
783 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
784 while (it
.hasNext()) {
785 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
786 const KFileItem
& oldItem
= itemPair
.first
;
787 const KFileItem
& newItem
= itemPair
.second
;
788 const int index
= m_items
.value(oldItem
.url(), -1);
790 m_itemData
[index
]->item
= newItem
;
792 // Keep old values as long as possible if they could not retrieved synchronously yet.
793 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
794 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
));
795 while (it
.hasNext()) {
797 m_itemData
[index
]->values
.insert(it
.key(), it
.value());
800 m_items
.remove(oldItem
.url());
801 m_items
.insert(newItem
.url(), index
);
802 indexes
.append(index
);
806 // If the changed items have been created recently, they might not be in m_items yet.
807 // In that case, the list 'indexes' might be empty.
808 if (indexes
.isEmpty()) {
812 // Extract the item-ranges out of the changed indexes
815 KItemRangeList itemRangeList
;
816 int previousIndex
= indexes
.at(0);
817 int rangeIndex
= previousIndex
;
820 const int maxIndex
= indexes
.count() - 1;
821 for (int i
= 1; i
<= maxIndex
; ++i
) {
822 const int currentIndex
= indexes
.at(i
);
823 if (currentIndex
== previousIndex
+ 1) {
826 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
828 rangeIndex
= currentIndex
;
831 previousIndex
= currentIndex
;
834 if (rangeCount
> 0) {
835 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
838 emit
itemsChanged(itemRangeList
, m_roles
);
843 void KFileItemModel::slotClear()
845 #ifdef KFILEITEMMODEL_DEBUG
846 kDebug() << "Clearing all items";
849 m_filteredItems
.clear();
852 m_maximumUpdateIntervalTimer
->stop();
853 m_resortAllItemsTimer
->stop();
854 m_pendingItemsToInsert
.clear();
856 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
858 const int removedCount
= m_itemData
.count();
859 if (removedCount
> 0) {
860 qDeleteAll(m_itemData
);
863 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
866 m_expandedDirs
.clear();
869 void KFileItemModel::slotClear(const KUrl
& url
)
874 void KFileItemModel::slotNaturalSortingChanged()
876 m_naturalSorting
= KGlobalSettings::naturalSorting();
880 void KFileItemModel::dispatchPendingItemsToInsert()
882 if (!m_pendingItemsToInsert
.isEmpty()) {
883 insertItems(m_pendingItemsToInsert
);
884 m_pendingItemsToInsert
.clear();
888 void KFileItemModel::insertItems(const KFileItemList
& items
)
890 if (items
.isEmpty()) {
894 if (m_sortRole
== TypeRole
) {
895 // Try to resolve the MIME-types synchronously to prevent a reordering of
896 // the items when sorting by type (per default MIME-types are resolved
897 // asynchronously by KFileItemModelRolesUpdater).
898 determineMimeTypes(items
, 200);
901 #ifdef KFILEITEMMODEL_DEBUG
904 kDebug() << "===========================================================";
905 kDebug() << "Inserting" << items
.count() << "items";
910 QList
<ItemData
*> sortedItems
= createItemDataList(items
);
911 KFileItemModelSortAlgorithm::sort(this, sortedItems
.begin(), sortedItems
.end());
913 #ifdef KFILEITEMMODEL_DEBUG
914 kDebug() << "[TIME] Sorting:" << timer
.elapsed();
917 KItemRangeList itemRanges
;
920 int insertedAtIndex
= -1; // Index for the current item-range
921 int insertedCount
= 0; // Count for the current item-range
922 int previouslyInsertedCount
= 0; // Sum of previously inserted items for all ranges
923 while (sourceIndex
< sortedItems
.count()) {
924 // Find target index from m_items to insert the current item
926 const int previousTargetIndex
= targetIndex
;
927 while (targetIndex
< m_itemData
.count()) {
928 if (!lessThan(m_itemData
.at(targetIndex
), sortedItems
.at(sourceIndex
))) {
934 if (targetIndex
- previousTargetIndex
> 0 && insertedAtIndex
>= 0) {
935 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
936 previouslyInsertedCount
+= insertedCount
;
937 insertedAtIndex
= targetIndex
- previouslyInsertedCount
;
941 // Insert item at the position targetIndex by transferring
942 // the ownership of the item-data from sortedItems to m_itemData.
943 // m_items will be inserted after the loop (see comment below)
944 m_itemData
.insert(targetIndex
, sortedItems
.at(sourceIndex
));
947 if (insertedAtIndex
< 0) {
948 insertedAtIndex
= targetIndex
;
949 Q_ASSERT(previouslyInsertedCount
== 0);
955 // The indexes of all m_items must be adjusted, not only the index
957 const int itemDataCount
= m_itemData
.count();
958 for (int i
= 0; i
< itemDataCount
; ++i
) {
959 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
962 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
963 emit
itemsInserted(itemRanges
);
965 #ifdef KFILEITEMMODEL_DEBUG
966 kDebug() << "[TIME] Inserting of" << items
.count() << "items:" << timer
.elapsed();
970 void KFileItemModel::removeItems(const KFileItemList
& items
)
972 if (items
.isEmpty()) {
976 #ifdef KFILEITEMMODEL_DEBUG
977 kDebug() << "Removing " << items
.count() << "items";
982 QList
<ItemData
*> sortedItems
;
983 sortedItems
.reserve(items
.count());
984 foreach (const KFileItem
& item
, items
) {
985 const int index
= m_items
.value(item
.url(), -1);
987 sortedItems
.append(m_itemData
.at(index
));
990 KFileItemModelSortAlgorithm::sort(this, sortedItems
.begin(), sortedItems
.end());
992 QList
<int> indexesToRemove
;
993 indexesToRemove
.reserve(items
.count());
995 // Calculate the item ranges that will get deleted
996 KItemRangeList itemRanges
;
997 int removedAtIndex
= -1;
998 int removedCount
= 0;
1000 foreach (const ItemData
* itemData
, sortedItems
) {
1001 const KFileItem
& itemToRemove
= itemData
->item
;
1003 const int previousTargetIndex
= targetIndex
;
1004 while (targetIndex
< m_itemData
.count()) {
1005 if (m_itemData
.at(targetIndex
)->item
.url() == itemToRemove
.url()) {
1010 if (targetIndex
>= m_itemData
.count()) {
1011 kWarning() << "Item that should be deleted has not been found!";
1015 if (targetIndex
- previousTargetIndex
> 0 && removedAtIndex
>= 0) {
1016 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
1017 removedAtIndex
= targetIndex
;
1021 indexesToRemove
.append(targetIndex
);
1022 if (removedAtIndex
< 0) {
1023 removedAtIndex
= targetIndex
;
1030 for (int i
= indexesToRemove
.count() - 1; i
>= 0; --i
) {
1031 const int indexToRemove
= indexesToRemove
.at(i
);
1032 ItemData
* data
= m_itemData
.at(indexToRemove
);
1034 m_items
.remove(data
->item
.url());
1037 m_itemData
.removeAt(indexToRemove
);
1040 // The indexes of all m_items must be adjusted, not only the index
1041 // of the removed items
1042 const int itemDataCount
= m_itemData
.count();
1043 for (int i
= 0; i
< itemDataCount
; ++i
) {
1044 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
1048 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
1051 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
1052 emit
itemsRemoved(itemRanges
);
1055 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const KFileItemList
& items
) const
1057 QList
<ItemData
*> itemDataList
;
1058 itemDataList
.reserve(items
.count());
1060 foreach (const KFileItem
& item
, items
) {
1061 ItemData
* itemData
= new ItemData();
1062 itemData
->item
= item
;
1063 itemData
->values
= retrieveData(item
);
1064 itemData
->parent
= 0;
1066 const bool determineParent
= m_requestRole
[ExpandedParentsCountRole
]
1067 && itemData
->values
["expandedParentsCount"].toInt() > 0;
1068 if (determineParent
) {
1069 KUrl parentUrl
= item
.url().upUrl();
1070 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
1071 const int parentIndex
= m_items
.value(parentUrl
, -1);
1072 if (parentIndex
>= 0) {
1073 itemData
->parent
= m_itemData
.at(parentIndex
);
1075 kWarning() << "Parent item not found for" << item
.url();
1079 itemDataList
.append(itemData
);
1082 return itemDataList
;
1085 void KFileItemModel::removeExpandedItems()
1087 KFileItemList expandedItems
;
1089 const int maxIndex
= m_itemData
.count() - 1;
1090 for (int i
= 0; i
<= maxIndex
; ++i
) {
1091 const ItemData
* itemData
= m_itemData
.at(i
);
1092 if (itemData
->values
.value("expandedParentsCount").toInt() > 0) {
1093 expandedItems
.append(itemData
->item
);
1097 // The m_expandedParentsCountRoot may not get reset before all items with
1098 // a bigger count have been removed.
1099 removeItems(expandedItems
);
1101 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
1102 m_expandedDirs
.clear();
1105 void KFileItemModel::resetRoles()
1107 for (int i
= 0; i
< RolesCount
; ++i
) {
1108 m_requestRole
[i
] = false;
1112 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1114 static QHash
<QByteArray
, RoleType
> roles
;
1115 if (roles
.isEmpty()) {
1116 // Insert user visible roles that can be accessed with
1117 // KFileItemModel::roleInformation()
1119 const RoleInfoMap
* map
= rolesInfoMap(count
);
1120 for (int i
= 0; i
< count
; ++i
) {
1121 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1124 // Insert internal roles (take care to synchronize the implementation
1125 // with KFileItemModel::roleForType() in case if a change is done).
1126 roles
.insert("isDir", IsDirRole
);
1127 roles
.insert("isLink", IsLinkRole
);
1128 roles
.insert("isExpanded", IsExpandedRole
);
1129 roles
.insert("isExpandable", IsExpandableRole
);
1130 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1132 Q_ASSERT(roles
.count() == RolesCount
);
1135 return roles
.value(role
, NoRole
);
1138 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1140 static QHash
<RoleType
, QByteArray
> roles
;
1141 if (roles
.isEmpty()) {
1142 // Insert user visible roles that can be accessed with
1143 // KFileItemModel::roleInformation()
1145 const RoleInfoMap
* map
= rolesInfoMap(count
);
1146 for (int i
= 0; i
< count
; ++i
) {
1147 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1150 // Insert internal roles (take care to synchronize the implementation
1151 // with KFileItemModel::typeForRole() in case if a change is done).
1152 roles
.insert(IsDirRole
, "isDir");
1153 roles
.insert(IsLinkRole
, "isLink");
1154 roles
.insert(IsExpandedRole
, "isExpanded");
1155 roles
.insert(IsExpandableRole
, "isExpandable");
1156 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1158 Q_ASSERT(roles
.count() == RolesCount
);
1161 return roles
.value(roleType
);
1164 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
) const
1166 // It is important to insert only roles that are fast to retrieve. E.g.
1167 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1168 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1169 QHash
<QByteArray
, QVariant
> data
;
1170 data
.insert("url", item
.url());
1172 const bool isDir
= item
.isDir();
1173 if (m_requestRole
[IsDirRole
]) {
1174 data
.insert("isDir", isDir
);
1177 if (m_requestRole
[IsLinkRole
]) {
1178 const bool isLink
= item
.isLink();
1179 data
.insert("isLink", isLink
);
1182 if (m_requestRole
[NameRole
]) {
1183 data
.insert("text", item
.text());
1186 if (m_requestRole
[SizeRole
]) {
1188 data
.insert("size", QVariant());
1190 data
.insert("size", item
.size());
1194 if (m_requestRole
[DateRole
]) {
1195 // Don't use KFileItem::timeString() as this is too expensive when
1196 // having several thousands of items. Instead the formatting of the
1197 // date-time will be done on-demand by the view when the date will be shown.
1198 const KDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
1199 data
.insert("date", dateTime
.dateTime());
1202 if (m_requestRole
[PermissionsRole
]) {
1203 data
.insert("permissions", item
.permissionsString());
1206 if (m_requestRole
[OwnerRole
]) {
1207 data
.insert("owner", item
.user());
1210 if (m_requestRole
[GroupRole
]) {
1211 data
.insert("group", item
.group());
1214 if (m_requestRole
[DestinationRole
]) {
1215 QString destination
= item
.linkDest();
1216 if (destination
.isEmpty()) {
1217 destination
= QLatin1String("-");
1219 data
.insert("destination", destination
);
1222 if (m_requestRole
[PathRole
]) {
1224 if (item
.url().protocol() == QLatin1String("trash")) {
1225 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1227 // For performance reasons cache the home-path in a static QString
1228 // (see QDir::homePath() for more details)
1229 static QString homePath
;
1230 if (homePath
.isEmpty()) {
1231 homePath
= QDir::homePath();
1234 path
= item
.localPath();
1235 if (path
.startsWith(homePath
)) {
1236 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1240 const int index
= path
.lastIndexOf(item
.text());
1241 path
= path
.mid(0, index
- 1);
1242 data
.insert("path", path
);
1245 if (m_requestRole
[IsExpandedRole
]) {
1246 data
.insert("isExpanded", false);
1249 if (m_requestRole
[IsExpandableRole
]) {
1250 data
.insert("isExpandable", item
.isDir() && item
.url() == item
.targetUrl());
1253 if (m_requestRole
[ExpandedParentsCountRole
]) {
1254 if (m_expandedParentsCountRoot
== UninitializedExpandedParentsCountRoot
) {
1255 const KUrl rootUrl
= m_dirLister
->url();
1256 const QString protocol
= rootUrl
.protocol();
1257 const bool forceExpandedParentsCountRoot
= (protocol
== QLatin1String("trash") ||
1258 protocol
== QLatin1String("nepomuk") ||
1259 protocol
== QLatin1String("remote") ||
1260 protocol
.contains(QLatin1String("search")));
1261 if (forceExpandedParentsCountRoot
) {
1262 m_expandedParentsCountRoot
= ForceExpandedParentsCountRoot
;
1264 const QString rootDir
= rootUrl
.path(KUrl::AddTrailingSlash
);
1265 m_expandedParentsCountRoot
= rootDir
.count('/');
1269 if (m_expandedParentsCountRoot
== ForceExpandedParentsCountRoot
) {
1270 data
.insert("expandedParentsCount", -1);
1272 const QString dir
= item
.url().directory(KUrl::AppendTrailingSlash
);
1273 const int level
= dir
.count('/') - m_expandedParentsCountRoot
;
1274 data
.insert("expandedParentsCount", level
);
1278 if (item
.isMimeTypeKnown()) {
1279 data
.insert("iconName", item
.iconName());
1281 if (m_requestRole
[TypeRole
]) {
1282 data
.insert("type", item
.mimeComment());
1289 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
) const
1293 if (m_expandedParentsCountRoot
>= 0) {
1294 result
= expandedParentsCountCompare(a
, b
);
1296 // The items have parents with different expansion levels
1297 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1301 if (m_sortDirsFirst
|| m_sortRole
== SizeRole
) {
1302 const bool isDirA
= a
->item
.isDir();
1303 const bool isDirB
= b
->item
.isDir();
1304 if (isDirA
&& !isDirB
) {
1306 } else if (!isDirA
&& isDirB
) {
1311 result
= sortRoleCompare(a
, b
);
1313 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1316 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
) const
1318 const KFileItem
& itemA
= a
->item
;
1319 const KFileItem
& itemB
= b
->item
;
1323 switch (m_sortRole
) {
1325 // The name role is handled as default fallback after the switch
1329 if (itemA
.isDir()) {
1330 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1331 Q_ASSERT(itemB
.isDir());
1333 const QVariant valueA
= a
->values
.value("size");
1334 const QVariant valueB
= b
->values
.value("size");
1335 if (valueA
.isNull() && valueB
.isNull()) {
1337 } else if (valueA
.isNull()) {
1339 } else if (valueB
.isNull()) {
1342 result
= valueA
.toInt() - valueB
.toInt();
1345 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1346 Q_ASSERT(!itemB
.isDir());
1347 const KIO::filesize_t sizeA
= itemA
.size();
1348 const KIO::filesize_t sizeB
= itemB
.size();
1349 if (sizeA
> sizeB
) {
1351 } else if (sizeA
< sizeB
) {
1361 const KDateTime dateTimeA
= itemA
.time(KFileItem::ModificationTime
);
1362 const KDateTime dateTimeB
= itemB
.time(KFileItem::ModificationTime
);
1363 if (dateTimeA
< dateTimeB
) {
1365 } else if (dateTimeA
> dateTimeB
) {
1372 result
= a
->values
.value("rating").toInt() - b
->values
.value("rating").toInt();
1376 case ImageSizeRole
: {
1377 // Alway use a natural comparing to interpret the numbers of a string like
1378 // "1600 x 1200" for having a correct sorting.
1379 result
= KStringHandler::naturalCompare(a
->values
.value("imageSize").toString(),
1380 b
->values
.value("imageSize").toString(),
1386 const QByteArray role
= roleForType(m_sortRole
);
1387 result
= QString::compare(a
->values
.value(role
).toString(),
1388 b
->values
.value(role
).toString());
1395 // The current sort role was sufficient to define an order
1399 // Fallback #1: Compare the text of the items
1400 result
= stringCompare(itemA
.text(), itemB
.text());
1405 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1406 result
= stringCompare(itemA
.name(m_caseSensitivity
== Qt::CaseInsensitive
),
1407 itemB
.name(m_caseSensitivity
== Qt::CaseInsensitive
));
1412 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1413 // equal. In this case a comparison of the URL is done which is unique in all cases
1414 // within KDirLister.
1415 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1418 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
) const
1420 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1421 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1422 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1423 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1425 if (m_caseSensitivity
== Qt::CaseInsensitive
) {
1426 const int result
= m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseInsensitive
)
1427 : QString::compare(a
, b
, Qt::CaseInsensitive
);
1429 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1430 // comparison, still a deterministic sort order is required. A case sensitive
1431 // comparison is done as fallback.
1436 return m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseSensitive
)
1437 : QString::compare(a
, b
, Qt::CaseSensitive
);
1440 int KFileItemModel::expandedParentsCountCompare(const ItemData
* a
, const ItemData
* b
) const
1442 const KUrl urlA
= a
->item
.url();
1443 const KUrl urlB
= b
->item
.url();
1444 if (urlA
.directory() == urlB
.directory()) {
1445 // Both items have the same directory as parent
1449 // Check whether one item is the parent of the other item
1450 if (urlA
.isParentOf(urlB
)) {
1451 return (sortOrder() == Qt::AscendingOrder
) ? -1 : +1;
1452 } else if (urlB
.isParentOf(urlA
)) {
1453 return (sortOrder() == Qt::AscendingOrder
) ? +1 : -1;
1456 // Determine the maximum common path of both items and
1457 // remember the index in 'index'
1458 const QString pathA
= urlA
.path();
1459 const QString pathB
= urlB
.path();
1461 const int maxIndex
= qMin(pathA
.length(), pathB
.length()) - 1;
1463 while (index
<= maxIndex
&& pathA
.at(index
) == pathB
.at(index
)) {
1466 if (index
> maxIndex
) {
1469 while ((pathA
.at(index
) != QLatin1Char('/') || pathB
.at(index
) != QLatin1Char('/')) && index
> 0) {
1473 // Determine the first sub-path after the common path and
1474 // check whether it represents a directory or already a file
1476 const QString subPathA
= subPath(a
->item
, pathA
, index
, &isDirA
);
1478 const QString subPathB
= subPath(b
->item
, pathB
, index
, &isDirB
);
1480 if (m_sortDirsFirst
|| m_sortRole
== SizeRole
) {
1481 if (isDirA
&& !isDirB
) {
1482 return (sortOrder() == Qt::AscendingOrder
) ? -1 : +1;
1483 } else if (!isDirA
&& isDirB
) {
1484 return (sortOrder() == Qt::AscendingOrder
) ? +1 : -1;
1488 // Compare the items of the parents that represent the first
1489 // different path after the common path.
1490 const QString parentPathA
= pathA
.left(index
) + subPathA
;
1491 const QString parentPathB
= pathB
.left(index
) + subPathB
;
1493 const ItemData
* parentA
= a
;
1494 while (parentA
&& parentA
->item
.url().path() != parentPathA
) {
1495 parentA
= parentA
->parent
;
1498 const ItemData
* parentB
= b
;
1499 while (parentB
&& parentB
->item
.url().path() != parentPathB
) {
1500 parentB
= parentB
->parent
;
1503 if (parentA
&& parentB
) {
1504 return sortRoleCompare(parentA
, parentB
);
1507 kWarning() << "Child items without parent detected:" << a
->item
.url() << b
->item
.url();
1508 return QString::compare(urlA
.url(), urlB
.url(), Qt::CaseSensitive
);
1511 QString
KFileItemModel::subPath(const KFileItem
& item
,
1512 const QString
& itemPath
,
1517 const int pathIndex
= itemPath
.indexOf('/', start
+ 1);
1518 *isDir
= (pathIndex
> 0) || item
.isDir();
1519 return itemPath
.mid(start
, pathIndex
- start
);
1522 bool KFileItemModel::useMaximumUpdateInterval() const
1524 return !m_dirLister
->url().isLocalFile();
1527 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1529 Q_ASSERT(!m_itemData
.isEmpty());
1531 const int maxIndex
= count() - 1;
1532 QList
<QPair
<int, QVariant
> > groups
;
1536 bool isLetter
= false;
1537 for (int i
= 0; i
<= maxIndex
; ++i
) {
1538 if (isChildItem(i
)) {
1542 const QString name
= m_itemData
.at(i
)->values
.value("text").toString();
1544 // Use the first character of the name as group indication
1545 QChar newFirstChar
= name
.at(0).toUpper();
1546 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1547 newFirstChar
= name
.at(1).toUpper();
1550 if (firstChar
!= newFirstChar
) {
1551 QString newGroupValue
;
1552 if (newFirstChar
>= QLatin1Char('A') && newFirstChar
<= QLatin1Char('Z')) {
1553 // Apply group 'A' - 'Z'
1554 newGroupValue
= newFirstChar
;
1556 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
1557 // Apply group '0 - 9' for any name that starts with a digit
1558 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
1562 // If the current group is 'A' - 'Z' check whether a locale character
1563 // fits into the existing group.
1564 // TODO: This does not work in the case if e.g. the group 'O' starts with
1565 // an umlaut 'O' -> provide unit-test to document this known issue
1566 const QChar
prevChar(firstChar
.unicode() - ushort(1));
1567 const QChar
nextChar(firstChar
.unicode() + ushort(1));
1568 const QString
currChar(newFirstChar
);
1569 const bool partOfCurrentGroup
= currChar
.localeAwareCompare(prevChar
) > 0 &&
1570 currChar
.localeAwareCompare(nextChar
) < 0;
1571 if (partOfCurrentGroup
) {
1575 newGroupValue
= i18nc("@title:group", "Others");
1579 if (newGroupValue
!= groupValue
) {
1580 groupValue
= newGroupValue
;
1581 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1584 firstChar
= newFirstChar
;
1590 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
1592 Q_ASSERT(!m_itemData
.isEmpty());
1594 const int maxIndex
= count() - 1;
1595 QList
<QPair
<int, QVariant
> > groups
;
1598 for (int i
= 0; i
<= maxIndex
; ++i
) {
1599 if (isChildItem(i
)) {
1603 const KFileItem
& item
= m_itemData
.at(i
)->item
;
1604 const KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
1605 QString newGroupValue
;
1606 if (!item
.isNull() && item
.isDir()) {
1607 newGroupValue
= i18nc("@title:group Size", "Folders");
1608 } else if (fileSize
< 5 * 1024 * 1024) {
1609 newGroupValue
= i18nc("@title:group Size", "Small");
1610 } else if (fileSize
< 10 * 1024 * 1024) {
1611 newGroupValue
= i18nc("@title:group Size", "Medium");
1613 newGroupValue
= i18nc("@title:group Size", "Big");
1616 if (newGroupValue
!= groupValue
) {
1617 groupValue
= newGroupValue
;
1618 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1625 QList
<QPair
<int, QVariant
> > KFileItemModel::dateRoleGroups() const
1627 Q_ASSERT(!m_itemData
.isEmpty());
1629 const int maxIndex
= count() - 1;
1630 QList
<QPair
<int, QVariant
> > groups
;
1632 const QDate currentDate
= KDateTime::currentLocalDateTime().date();
1634 int yearForCurrentWeek
= 0;
1635 int currentWeek
= currentDate
.weekNumber(&yearForCurrentWeek
);
1636 if (yearForCurrentWeek
== currentDate
.year() + 1) {
1640 QDate previousModifiedDate
;
1642 for (int i
= 0; i
<= maxIndex
; ++i
) {
1643 if (isChildItem(i
)) {
1647 const KDateTime modifiedTime
= m_itemData
.at(i
)->item
.time(KFileItem::ModificationTime
);
1648 const QDate modifiedDate
= modifiedTime
.date();
1649 if (modifiedDate
== previousModifiedDate
) {
1650 // The current item is in the same group as the previous item
1653 previousModifiedDate
= modifiedDate
;
1655 const int daysDistance
= modifiedDate
.daysTo(currentDate
);
1657 int yearForModifiedWeek
= 0;
1658 int modifiedWeek
= modifiedDate
.weekNumber(&yearForModifiedWeek
);
1659 if (yearForModifiedWeek
== modifiedDate
.year() + 1) {
1663 QString newGroupValue
;
1664 if (currentDate
.year() == modifiedDate
.year() && currentDate
.month() == modifiedDate
.month()) {
1665 if (modifiedWeek
> currentWeek
) {
1666 // Usecase: modified date = 2010-01-01, current date = 2010-01-22
1667 // modified week = 53, current week = 3
1670 switch (currentWeek
- modifiedWeek
) {
1672 switch (daysDistance
) {
1673 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
1674 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
1675 default: newGroupValue
= modifiedTime
.toString(i18nc("@title:group The week day name: %A", "%A"));
1679 newGroupValue
= i18nc("@title:group Date", "Last Week");
1682 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
1685 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
1689 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
1695 const QDate lastMonthDate
= currentDate
.addMonths(-1);
1696 if (lastMonthDate
.year() == modifiedDate
.year() && lastMonthDate
.month() == modifiedDate
.month()) {
1697 if (daysDistance
== 1) {
1698 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Yesterday (%B, %Y)"));
1699 } else if (daysDistance
<= 7) {
1700 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)"));
1701 } else if (daysDistance
<= 7 * 2) {
1702 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)"));
1703 } else if (daysDistance
<= 7 * 3) {
1704 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)"));
1705 } else if (daysDistance
<= 7 * 4) {
1706 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)"));
1708 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"));
1711 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"));
1715 if (newGroupValue
!= groupValue
) {
1716 groupValue
= newGroupValue
;
1717 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1724 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
1726 Q_ASSERT(!m_itemData
.isEmpty());
1728 const int maxIndex
= count() - 1;
1729 QList
<QPair
<int, QVariant
> > groups
;
1731 QString permissionsString
;
1733 for (int i
= 0; i
<= maxIndex
; ++i
) {
1734 if (isChildItem(i
)) {
1738 const ItemData
* itemData
= m_itemData
.at(i
);
1739 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
1740 if (newPermissionsString
== permissionsString
) {
1743 permissionsString
= newPermissionsString
;
1745 const QFileInfo
info(itemData
->item
.url().pathOrUrl());
1749 if (info
.permission(QFile::ReadUser
)) {
1750 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1752 if (info
.permission(QFile::WriteUser
)) {
1753 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1755 if (info
.permission(QFile::ExeUser
)) {
1756 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1758 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
1762 if (info
.permission(QFile::ReadGroup
)) {
1763 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1765 if (info
.permission(QFile::WriteGroup
)) {
1766 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1768 if (info
.permission(QFile::ExeGroup
)) {
1769 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1771 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
1773 // Set others string
1775 if (info
.permission(QFile::ReadOther
)) {
1776 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1778 if (info
.permission(QFile::WriteOther
)) {
1779 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1781 if (info
.permission(QFile::ExeOther
)) {
1782 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1784 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
1786 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
1787 if (newGroupValue
!= groupValue
) {
1788 groupValue
= newGroupValue
;
1789 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1796 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
1798 Q_ASSERT(!m_itemData
.isEmpty());
1800 const int maxIndex
= count() - 1;
1801 QList
<QPair
<int, QVariant
> > groups
;
1803 int groupValue
= -1;
1804 for (int i
= 0; i
<= maxIndex
; ++i
) {
1805 if (isChildItem(i
)) {
1808 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
1809 if (newGroupValue
!= groupValue
) {
1810 groupValue
= newGroupValue
;
1811 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1818 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
1820 Q_ASSERT(!m_itemData
.isEmpty());
1822 const int maxIndex
= count() - 1;
1823 QList
<QPair
<int, QVariant
> > groups
;
1825 bool isFirstGroupValue
= true;
1827 for (int i
= 0; i
<= maxIndex
; ++i
) {
1828 if (isChildItem(i
)) {
1831 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
1832 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
1833 groupValue
= newGroupValue
;
1834 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1835 isFirstGroupValue
= false;
1842 KFileItemList
KFileItemModel::childItems(const KFileItem
& item
) const
1844 KFileItemList items
;
1846 int index
= m_items
.value(item
.url(), -1);
1848 const int parentLevel
= m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt();
1850 while (index
< m_itemData
.count() && m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt() > parentLevel
) {
1851 items
.append(m_itemData
.at(index
)->item
);
1859 void KFileItemModel::emitSortProgress(int resolvedCount
)
1861 // Be tolerant against a resolvedCount with a wrong range.
1862 // Although there should not be a case where KFileItemModelRolesUpdater
1863 // (= caller) provides a wrong range, it is important to emit
1864 // a useful progress information even if there is an unexpected
1865 // implementation issue.
1867 const int itemCount
= count();
1868 if (resolvedCount
>= itemCount
) {
1869 m_sortingProgressPercent
= -1;
1870 if (m_resortAllItemsTimer
->isActive()) {
1871 m_resortAllItemsTimer
->stop();
1875 emit
directorySortingProgress(100);
1876 } else if (itemCount
> 0) {
1877 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
1879 const int progress
= resolvedCount
* 100 / itemCount
;
1880 if (m_sortingProgressPercent
!= progress
) {
1881 m_sortingProgressPercent
= progress
;
1882 emit
directorySortingProgress(progress
);
1887 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
1889 static const RoleInfoMap rolesInfoMap
[] = {
1890 // | role | roleType | role translation | group translation | requires Nepomuk | requires indexer
1891 { 0, NoRole
, 0, 0, 0, 0, false, false },
1892 { "text", NameRole
, I18N_NOOP2_NOSTRIP("@label", "Name"), 0, 0, false, false },
1893 { "size", SizeRole
, I18N_NOOP2_NOSTRIP("@label", "Size"), 0, 0, false, false },
1894 { "date", DateRole
, I18N_NOOP2_NOSTRIP("@label", "Date"), 0, 0, false, false },
1895 { "type", TypeRole
, I18N_NOOP2_NOSTRIP("@label", "Type"), 0, 0, false, false },
1896 { "rating", RatingRole
, I18N_NOOP2_NOSTRIP("@label", "Rating"), 0, 0, true, false },
1897 { "tags", TagsRole
, I18N_NOOP2_NOSTRIP("@label", "Tags"), 0, 0, true, false },
1898 { "comment", CommentRole
, I18N_NOOP2_NOSTRIP("@label", "Comment"), 0, 0, true, false },
1899 { "wordCount", WordCountRole
, I18N_NOOP2_NOSTRIP("@label", "Word Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
1900 { "lineCount", LineCountRole
, I18N_NOOP2_NOSTRIP("@label", "Line Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
1901 { "imageSize", ImageSizeRole
, I18N_NOOP2_NOSTRIP("@label", "Image Size"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
1902 { "orientation", OrientationRole
, I18N_NOOP2_NOSTRIP("@label", "Orientation"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
1903 { "artist", ArtistRole
, I18N_NOOP2_NOSTRIP("@label", "Artist"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1904 { "album", AlbumRole
, I18N_NOOP2_NOSTRIP("@label", "Album"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1905 { "duration", DurationRole
, I18N_NOOP2_NOSTRIP("@label", "Duration"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1906 { "track", TrackRole
, I18N_NOOP2_NOSTRIP("@label", "Track"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1907 { "path", PathRole
, I18N_NOOP2_NOSTRIP("@label", "Path"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1908 { "destination", DestinationRole
, I18N_NOOP2_NOSTRIP("@label", "Link Destination"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1909 { "copiedFrom", CopiedFromRole
, I18N_NOOP2_NOSTRIP("@label", "Copied From"), I18N_NOOP2_NOSTRIP("@label", "Other"), true, false },
1910 { "permissions", PermissionsRole
, I18N_NOOP2_NOSTRIP("@label", "Permissions"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1911 { "owner", OwnerRole
, I18N_NOOP2_NOSTRIP("@label", "Owner"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1912 { "group", GroupRole
, I18N_NOOP2_NOSTRIP("@label", "User Group"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1915 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
1916 return rolesInfoMap
;
1919 void KFileItemModel::determineMimeTypes(const KFileItemList
& items
, int timeout
)
1921 QElapsedTimer timer
;
1923 foreach (KFileItem item
, items
) { // krazy:exclude=foreach
1924 item
.determineMimeType();
1925 if (timer
.elapsed() > timeout
) {
1926 // Don't block the user interface, let the remaining items
1927 // be resolved asynchronously.
1933 #include "kfileitemmodel.moc"