1 /*****************************************************************************
2 * Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
3 * Copyright (C) 2013 by Frank Reininghaus <frank78ac@googlemail.com> *
4 * Copyright (C) 2013 by Emmanuel Pescosta <emmanuelpescosta099@gmail.com> *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the *
18 * Free Software Foundation, Inc., *
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
20 *****************************************************************************/
22 #include "kfileitemmodel.h"
24 #include <KGlobalSettings>
26 #include <KStringHandler>
29 #include "private/kfileitemmodelsortalgorithm.h"
30 #include "private/kfileitemmodeldirlister.h"
32 #include <QApplication>
40 // #define KFILEITEMMODEL_DEBUG
42 KFileItemModel::KFileItemModel(QObject
* parent
) :
43 KItemModelBase("text", parent
),
45 m_naturalSorting(KGlobalSettings::naturalSorting()),
46 m_sortDirsFirst(true),
48 m_sortingProgressPercent(-1),
50 m_caseSensitivity(Qt::CaseInsensitive
),
56 m_maximumUpdateIntervalTimer(0),
57 m_resortAllItemsTimer(0),
58 m_pendingItemsToInsert(),
63 m_dirLister
= new KFileItemModelDirLister(this);
64 m_dirLister
->setDelayedMimeTypes(true);
66 const QWidget
* parentWidget
= qobject_cast
<QWidget
*>(parent
);
68 m_dirLister
->setMainWindow(parentWidget
->window());
71 connect(m_dirLister
, SIGNAL(started(KUrl
)), this, SIGNAL(directoryLoadingStarted()));
72 connect(m_dirLister
, SIGNAL(canceled()), this, SLOT(slotCanceled()));
73 connect(m_dirLister
, SIGNAL(completed(KUrl
)), this, SLOT(slotCompleted()));
74 connect(m_dirLister
, SIGNAL(itemsAdded(KUrl
,KFileItemList
)), this, SLOT(slotItemsAdded(KUrl
,KFileItemList
)));
75 connect(m_dirLister
, SIGNAL(itemsDeleted(KFileItemList
)), this, SLOT(slotItemsDeleted(KFileItemList
)));
76 connect(m_dirLister
, SIGNAL(refreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)), this, SLOT(slotRefreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)));
77 connect(m_dirLister
, SIGNAL(clear()), this, SLOT(slotClear()));
78 connect(m_dirLister
, SIGNAL(infoMessage(QString
)), this, SIGNAL(infoMessage(QString
)));
79 connect(m_dirLister
, SIGNAL(errorMessage(QString
)), this, SIGNAL(errorMessage(QString
)));
80 connect(m_dirLister
, SIGNAL(redirection(KUrl
,KUrl
)), this, SIGNAL(directoryRedirection(KUrl
,KUrl
)));
81 connect(m_dirLister
, SIGNAL(urlIsFileError(KUrl
)), this, SIGNAL(urlIsFileError(KUrl
)));
83 // Apply default roles that should be determined
85 m_requestRole
[NameRole
] = true;
86 m_requestRole
[IsDirRole
] = true;
87 m_requestRole
[IsLinkRole
] = true;
88 m_roles
.insert("text");
89 m_roles
.insert("isDir");
90 m_roles
.insert("isLink");
92 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
93 // before the completed() or canceled() signal has been emitted.
94 m_maximumUpdateIntervalTimer
= new QTimer(this);
95 m_maximumUpdateIntervalTimer
->setInterval(2000);
96 m_maximumUpdateIntervalTimer
->setSingleShot(true);
97 connect(m_maximumUpdateIntervalTimer
, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
99 // When changing the value of an item which represents the sort-role a resorting must be
100 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
101 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
102 // resorting is postponed until the timer has been exceeded.
103 m_resortAllItemsTimer
= new QTimer(this);
104 m_resortAllItemsTimer
->setInterval(500);
105 m_resortAllItemsTimer
->setSingleShot(true);
106 connect(m_resortAllItemsTimer
, SIGNAL(timeout()), this, SLOT(resortAllItems()));
108 connect(KGlobalSettings::self(), SIGNAL(naturalSortingChanged()), this, SLOT(slotNaturalSortingChanged()));
111 KFileItemModel::~KFileItemModel()
113 qDeleteAll(m_itemData
);
114 qDeleteAll(m_filteredItems
.values());
115 qDeleteAll(m_pendingItemsToInsert
);
118 void KFileItemModel::loadDirectory(const KUrl
& url
)
120 m_dirLister
->openUrl(url
);
123 void KFileItemModel::refreshDirectory(const KUrl
& url
)
125 // Refresh all expanded directories first (Bug 295300)
126 QHashIterator
<KUrl
, KUrl
> expandedDirs(m_expandedDirs
);
127 while (expandedDirs
.hasNext()) {
129 m_dirLister
->openUrl(expandedDirs
.value(), KDirLister::Reload
);
132 m_dirLister
->openUrl(url
, KDirLister::Reload
);
135 KUrl
KFileItemModel::directory() const
137 return m_dirLister
->url();
140 void KFileItemModel::cancelDirectoryLoading()
145 int KFileItemModel::count() const
147 return m_itemData
.count();
150 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
152 if (index
>= 0 && index
< count()) {
153 ItemData
* data
= m_itemData
.at(index
);
154 if (data
->values
.isEmpty()) {
155 data
->values
= retrieveData(data
->item
, data
->parent
);
160 return QHash
<QByteArray
, QVariant
>();
163 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
165 if (index
< 0 || index
>= count()) {
169 QHash
<QByteArray
, QVariant
> currentValues
= data(index
);
171 // Determine which roles have been changed
172 QSet
<QByteArray
> changedRoles
;
173 QHashIterator
<QByteArray
, QVariant
> it(values
);
174 while (it
.hasNext()) {
176 const QByteArray role
= sharedValue(it
.key());
177 const QVariant value
= it
.value();
179 if (currentValues
[role
] != value
) {
180 currentValues
[role
] = value
;
181 changedRoles
.insert(role
);
185 if (changedRoles
.isEmpty()) {
189 m_itemData
[index
]->values
= currentValues
;
190 if (changedRoles
.contains("text")) {
191 KUrl url
= m_itemData
[index
]->item
.url();
192 url
.setFileName(currentValues
["text"].toString());
193 m_itemData
[index
]->item
.setUrl(url
);
196 emitItemsChangedAndTriggerResorting(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
201 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
203 if (dirsFirst
!= m_sortDirsFirst
) {
204 m_sortDirsFirst
= dirsFirst
;
209 bool KFileItemModel::sortDirectoriesFirst() const
211 return m_sortDirsFirst
;
214 void KFileItemModel::setShowHiddenFiles(bool show
)
216 m_dirLister
->setShowingDotFiles(show
);
217 m_dirLister
->emitChanges();
223 bool KFileItemModel::showHiddenFiles() const
225 return m_dirLister
->showingDotFiles();
228 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
230 m_dirLister
->setDirOnlyMode(enabled
);
233 bool KFileItemModel::showDirectoriesOnly() const
235 return m_dirLister
->dirOnlyMode();
238 QMimeData
* KFileItemModel::createMimeData(const KItemSet
& indexes
) const
240 QMimeData
* data
= new QMimeData();
242 // The following code has been taken from KDirModel::mimeData()
243 // (kdelibs/kio/kio/kdirmodel.cpp)
244 // Copyright (C) 2006 David Faure <faure@kde.org>
246 KUrl::List mostLocalUrls
;
247 bool canUseMostLocalUrls
= true;
248 const ItemData
* lastAddedItem
= 0;
250 foreach (int index
, indexes
) {
251 const ItemData
* itemData
= m_itemData
.at(index
);
252 const ItemData
* parent
= itemData
->parent
;
254 while (parent
&& parent
!= lastAddedItem
) {
255 parent
= parent
->parent
;
258 if (parent
&& parent
== lastAddedItem
) {
259 // A parent of 'itemData' has been added already.
263 lastAddedItem
= itemData
;
264 const KFileItem
& item
= itemData
->item
;
265 if (!item
.isNull()) {
266 urls
<< item
.targetUrl();
269 mostLocalUrls
<< item
.mostLocalUrl(isLocal
);
271 canUseMostLocalUrls
= false;
276 const bool different
= canUseMostLocalUrls
&& mostLocalUrls
!= urls
;
278 urls
.populateMimeData(mostLocalUrls
, data
);
280 urls
.populateMimeData(data
);
286 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
288 startFromIndex
= qMax(0, startFromIndex
);
289 for (int i
= startFromIndex
; i
< count(); ++i
) {
290 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
294 for (int i
= 0; i
< startFromIndex
; ++i
) {
295 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
302 bool KFileItemModel::supportsDropping(int index
) const
304 const KFileItem item
= fileItem(index
);
305 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
308 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
310 static QHash
<QByteArray
, QString
> description
;
311 if (description
.isEmpty()) {
313 const RoleInfoMap
* map
= rolesInfoMap(count
);
314 for (int i
= 0; i
< count
; ++i
) {
315 description
.insert(map
[i
].role
, i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
));
319 return description
.value(role
);
322 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
324 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
325 #ifdef KFILEITEMMODEL_DEBUG
329 switch (typeForRole(sortRole())) {
330 case NameRole
: m_groups
= nameRoleGroups(); break;
331 case SizeRole
: m_groups
= sizeRoleGroups(); break;
332 case DateRole
: m_groups
= dateRoleGroups(); break;
333 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
334 case RatingRole
: m_groups
= ratingRoleGroups(); break;
335 default: m_groups
= genericStringRoleGroups(sortRole()); break;
338 #ifdef KFILEITEMMODEL_DEBUG
339 kDebug() << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
346 KFileItem
KFileItemModel::fileItem(int index
) const
348 if (index
>= 0 && index
< count()) {
349 return m_itemData
.at(index
)->item
;
355 KFileItem
KFileItemModel::fileItem(const KUrl
& url
) const
357 const int indexForUrl
= index(url
);
358 if (indexForUrl
>= 0) {
359 return m_itemData
.at(indexForUrl
)->item
;
364 int KFileItemModel::index(const KFileItem
& item
) const
366 return index(item
.url());
369 int KFileItemModel::index(const KUrl
& url
) const
371 KUrl urlToFind
= url
;
372 urlToFind
.adjustPath(KUrl::RemoveTrailingSlash
);
374 const int itemCount
= m_itemData
.count();
375 int itemsInHash
= m_items
.count();
377 int index
= m_items
.value(urlToFind
, -1);
378 while (index
< 0 && itemsInHash
< itemCount
) {
379 // Not all URLs are stored yet in m_items. We grow m_items until either
380 // urlToFind is found, or all URLs have been stored in m_items.
381 // Note that we do not add the URLs to m_items one by one, but in
382 // larger blocks. After each block, we check if urlToFind is in
383 // m_items. We could in principle compare urlToFind with each URL while
384 // we are going through m_itemData, but comparing two QUrls will,
385 // unlike calling qHash for the URLs, trigger a parsing of the URLs
386 // which costs both CPU cycles and memory.
387 const int blockSize
= 1000;
388 const int currentBlockEnd
= qMin(itemsInHash
+ blockSize
, itemCount
);
389 for (int i
= itemsInHash
; i
< currentBlockEnd
; ++i
) {
390 const KUrl nextUrl
= m_itemData
.at(i
)->item
.url();
391 m_items
.insert(nextUrl
, i
);
394 itemsInHash
= currentBlockEnd
;
395 index
= m_items
.value(urlToFind
, -1);
398 Q_ASSERT(index
>= 0 || m_items
.count() == m_itemData
.count());
403 KFileItem
KFileItemModel::rootItem() const
405 return m_dirLister
->rootItem();
408 void KFileItemModel::clear()
413 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
415 if (m_roles
== roles
) {
421 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
422 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
423 if (supportedExpanding
&& !willSupportExpanding
) {
424 // No expanding is supported anymore. Take care to delete all items that have an expansion level
425 // that is not 0 (and hence are part of an expanded item).
426 removeExpandedItems();
433 QSetIterator
<QByteArray
> it(roles
);
434 while (it
.hasNext()) {
435 const QByteArray
& role
= it
.next();
436 m_requestRole
[typeForRole(role
)] = true;
440 // Update m_data with the changed requested roles
441 const int maxIndex
= count() - 1;
442 for (int i
= 0; i
<= maxIndex
; ++i
) {
443 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
, m_itemData
.at(i
)->parent
);
446 kWarning() << "TODO: Emitting itemsChanged() with no information what has changed!";
447 emit
itemsChanged(KItemRangeList() << KItemRange(0, count()), QSet
<QByteArray
>());
450 // Clear the 'values' of all filtered items. They will be re-populated with the
451 // correct roles the next time 'values' will be accessed via data(int).
452 QHash
<KFileItem
, ItemData
*>::iterator filteredIt
= m_filteredItems
.begin();
453 const QHash
<KFileItem
, ItemData
*>::iterator filteredEnd
= m_filteredItems
.end();
454 while (filteredIt
!= filteredEnd
) {
455 (*filteredIt
)->values
.clear();
460 QSet
<QByteArray
> KFileItemModel::roles() const
465 bool KFileItemModel::setExpanded(int index
, bool expanded
)
467 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
471 QHash
<QByteArray
, QVariant
> values
;
472 values
.insert(sharedValue("isExpanded"), expanded
);
473 if (!setData(index
, values
)) {
477 const KFileItem item
= m_itemData
.at(index
)->item
;
478 const KUrl url
= item
.url();
479 const KUrl targetUrl
= item
.targetUrl();
481 m_expandedDirs
.insert(targetUrl
, url
);
482 m_dirLister
->openUrl(url
, KDirLister::Keep
);
484 const KUrl::List previouslyExpandedChildren
= m_itemData
.at(index
)->values
.value("previouslyExpandedChildren").value
<KUrl::List
>();
485 foreach (const KUrl
& url
, previouslyExpandedChildren
) {
486 m_urlsToExpand
.insert(url
);
489 m_expandedDirs
.remove(targetUrl
);
490 m_dirLister
->stop(url
);
492 const int parentLevel
= expandedParentsCount(index
);
493 const int itemCount
= m_itemData
.count();
494 const int firstChildIndex
= index
+ 1;
496 KUrl::List expandedChildren
;
498 int childIndex
= firstChildIndex
;
499 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
500 ItemData
* itemData
= m_itemData
.at(childIndex
);
501 if (itemData
->values
.value("isExpanded").toBool()) {
502 const KUrl targetUrl
= itemData
->item
.targetUrl();
503 m_expandedDirs
.remove(targetUrl
);
504 expandedChildren
.append(targetUrl
);
508 const int childrenCount
= childIndex
- firstChildIndex
;
510 removeFilteredChildren(KItemRangeList() << KItemRange(index
, 1 + childrenCount
));
511 removeItems(KItemRangeList() << KItemRange(firstChildIndex
, childrenCount
), DeleteItemData
);
513 m_itemData
.at(index
)->values
.insert("previouslyExpandedChildren", expandedChildren
);
519 bool KFileItemModel::isExpanded(int index
) const
521 if (index
>= 0 && index
< count()) {
522 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
527 bool KFileItemModel::isExpandable(int index
) const
529 if (index
>= 0 && index
< count()) {
530 // Call data (instead of accessing m_itemData directly)
531 // to ensure that the value is initialized.
532 return data(index
).value("isExpandable").toBool();
537 int KFileItemModel::expandedParentsCount(int index
) const
539 if (index
>= 0 && index
< count()) {
540 return expandedParentsCount(m_itemData
.at(index
));
545 QSet
<KUrl
> KFileItemModel::expandedDirectories() const
547 return m_expandedDirs
.values().toSet();
550 void KFileItemModel::restoreExpandedDirectories(const QSet
<KUrl
>& urls
)
552 m_urlsToExpand
= urls
;
555 void KFileItemModel::expandParentDirectories(const KUrl
& url
)
557 const int pos
= m_dirLister
->url().path().length();
559 // Assure that each sub-path of the URL that should be
560 // expanded is added to m_urlsToExpand. KDirLister
561 // does not care whether the parent-URL has already been
563 KUrl urlToExpand
= m_dirLister
->url();
564 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator());
565 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
566 urlToExpand
.addPath(subDirs
.at(i
));
567 m_urlsToExpand
.insert(urlToExpand
);
570 // KDirLister::open() must called at least once to trigger an initial
571 // loading. The pending URLs that must be restored are handled
572 // in slotCompleted().
573 QSetIterator
<KUrl
> it2(m_urlsToExpand
);
574 while (it2
.hasNext()) {
575 const int idx
= index(it2
.next());
576 if (idx
>= 0 && !isExpanded(idx
)) {
577 setExpanded(idx
, true);
583 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
585 if (m_filter
.pattern() != nameFilter
) {
586 dispatchPendingItemsToInsert();
587 m_filter
.setPattern(nameFilter
);
592 QString
KFileItemModel::nameFilter() const
594 return m_filter
.pattern();
597 void KFileItemModel::setMimeTypeFilters(const QStringList
& filters
)
599 if (m_filter
.mimeTypes() != filters
) {
600 dispatchPendingItemsToInsert();
601 m_filter
.setMimeTypes(filters
);
606 QStringList
KFileItemModel::mimeTypeFilters() const
608 return m_filter
.mimeTypes();
612 void KFileItemModel::applyFilters()
614 // Check which shown items from m_itemData must get
615 // hidden and hence moved to m_filteredItems.
616 QVector
<int> newFilteredIndexes
;
618 const int itemCount
= m_itemData
.count();
619 for (int index
= 0; index
< itemCount
; ++index
) {
620 ItemData
* itemData
= m_itemData
.at(index
);
622 // Only filter non-expanded items as child items may never
623 // exist without a parent item
624 if (!itemData
->values
.value("isExpanded").toBool()) {
625 const KFileItem item
= itemData
->item
;
626 if (!m_filter
.matches(item
)) {
627 newFilteredIndexes
.append(index
);
628 m_filteredItems
.insert(item
, itemData
);
633 const KItemRangeList removedRanges
= KItemRangeList::fromSortedContainer(newFilteredIndexes
);
634 removeItems(removedRanges
, KeepItemData
);
636 // Check which hidden items from m_filteredItems should
637 // get visible again and hence removed from m_filteredItems.
638 QList
<ItemData
*> newVisibleItems
;
640 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
641 while (it
!= m_filteredItems
.end()) {
642 if (m_filter
.matches(it
.key())) {
643 newVisibleItems
.append(it
.value());
644 it
= m_filteredItems
.erase(it
);
650 insertItems(newVisibleItems
);
653 void KFileItemModel::removeFilteredChildren(const KItemRangeList
& itemRanges
)
655 if (m_filteredItems
.isEmpty() || !m_requestRole
[ExpandedParentsCountRole
]) {
656 // There are either no filtered items, or it is not possible to expand
657 // folders -> there cannot be any filtered children.
661 QSet
<ItemData
*> parents
;
662 foreach (const KItemRange
& range
, itemRanges
) {
663 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
664 parents
.insert(m_itemData
.at(index
));
668 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
669 while (it
!= m_filteredItems
.end()) {
670 if (parents
.contains(it
.value()->parent
)) {
672 it
= m_filteredItems
.erase(it
);
679 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
681 static QList
<RoleInfo
> rolesInfo
;
682 if (rolesInfo
.isEmpty()) {
684 const RoleInfoMap
* map
= rolesInfoMap(count
);
685 for (int i
= 0; i
< count
; ++i
) {
686 if (map
[i
].roleType
!= NoRole
) {
688 info
.role
= map
[i
].role
;
689 info
.translation
= i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
);
690 if (map
[i
].groupTranslation
) {
691 info
.group
= i18nc(map
[i
].groupTranslationContext
, map
[i
].groupTranslation
);
693 // For top level roles, groupTranslation is 0. We must make sure that
694 // info.group is an empty string then because the code that generates
695 // menus tries to put the actions into sub menus otherwise.
696 info
.group
= QString();
698 info
.requiresBaloo
= map
[i
].requiresBaloo
;
699 info
.requiresIndexer
= map
[i
].requiresIndexer
;
700 rolesInfo
.append(info
);
708 void KFileItemModel::onGroupedSortingChanged(bool current
)
714 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
717 m_sortRole
= typeForRole(current
);
719 if (!m_requestRole
[m_sortRole
]) {
720 QSet
<QByteArray
> newRoles
= m_roles
;
728 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
735 void KFileItemModel::resortAllItems()
737 m_resortAllItemsTimer
->stop();
739 const int itemCount
= count();
740 if (itemCount
<= 0) {
744 #ifdef KFILEITEMMODEL_DEBUG
747 kDebug() << "===========================================================";
748 kDebug() << "Resorting" << itemCount
<< "items";
751 // Remember the order of the current URLs so
752 // that it can be determined which indexes have
753 // been moved because of the resorting.
755 oldUrls
.reserve(itemCount
);
756 foreach (const ItemData
* itemData
, m_itemData
) {
757 oldUrls
.append(itemData
->item
.url());
761 m_items
.reserve(itemCount
);
764 sort(m_itemData
.begin(), m_itemData
.end());
765 for (int i
= 0; i
< itemCount
; ++i
) {
766 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
769 // Determine the first index that has been moved.
770 int firstMovedIndex
= 0;
771 while (firstMovedIndex
< itemCount
772 && firstMovedIndex
== m_items
.value(oldUrls
.at(firstMovedIndex
))) {
776 const bool itemsHaveMoved
= firstMovedIndex
< itemCount
;
777 if (itemsHaveMoved
) {
780 int lastMovedIndex
= itemCount
- 1;
781 while (lastMovedIndex
> firstMovedIndex
782 && lastMovedIndex
== m_items
.value(oldUrls
.at(lastMovedIndex
))) {
786 Q_ASSERT(firstMovedIndex
<= lastMovedIndex
);
788 // Create a list movedToIndexes, which has the property that
789 // movedToIndexes[i] is the new index of the item with the old index
790 // firstMovedIndex + i.
791 const int movedItemsCount
= lastMovedIndex
- firstMovedIndex
+ 1;
792 QList
<int> movedToIndexes
;
793 movedToIndexes
.reserve(movedItemsCount
);
794 for (int i
= firstMovedIndex
; i
<= lastMovedIndex
; ++i
) {
795 const int newIndex
= m_items
.value(oldUrls
.at(i
));
796 movedToIndexes
.append(newIndex
);
799 emit
itemsMoved(KItemRange(firstMovedIndex
, movedItemsCount
), movedToIndexes
);
800 } else if (groupedSorting()) {
801 // The groups might have changed even if the order of the items has not.
802 const QList
<QPair
<int, QVariant
> > oldGroups
= m_groups
;
804 if (groups() != oldGroups
) {
805 emit
groupsChanged();
809 #ifdef KFILEITEMMODEL_DEBUG
810 kDebug() << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
814 void KFileItemModel::slotCompleted()
816 dispatchPendingItemsToInsert();
818 if (!m_urlsToExpand
.isEmpty()) {
819 // Try to find a URL that can be expanded.
820 // Note that the parent folder must be expanded before any of its subfolders become visible.
821 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
822 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
823 foreach (const KUrl
& url
, m_urlsToExpand
) {
824 const int indexForUrl
= index(url
);
825 if (indexForUrl
>= 0) {
826 m_urlsToExpand
.remove(url
);
827 if (setExpanded(indexForUrl
, true)) {
828 // The dir lister has been triggered. This slot will be called
829 // again after the directory has been expanded.
835 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
836 // if these URLs have been deleted in the meantime.
837 m_urlsToExpand
.clear();
840 emit
directoryLoadingCompleted();
843 void KFileItemModel::slotCanceled()
845 m_maximumUpdateIntervalTimer
->stop();
846 dispatchPendingItemsToInsert();
848 emit
directoryLoadingCanceled();
851 void KFileItemModel::slotItemsAdded(const KUrl
& directoryUrl
, const KFileItemList
& items
)
853 Q_ASSERT(!items
.isEmpty());
856 if (m_expandedDirs
.contains(directoryUrl
)) {
857 parentUrl
= m_expandedDirs
.value(directoryUrl
);
859 parentUrl
= directoryUrl
;
860 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
863 if (m_requestRole
[ExpandedParentsCountRole
]) {
864 // If the expanding of items is enabled, the call
865 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
866 // might result in emitting the same items twice due to the Keep-parameter.
867 // This case happens if an item gets expanded, collapsed and expanded again
868 // before the items could be loaded for the first expansion.
869 if (index(items
.first().url()) >= 0) {
870 // The items are already part of the model.
874 if (directoryUrl
!= directory()) {
875 // To be able to compare whether the new items may be inserted as children
876 // of a parent item the pending items must be added to the model first.
877 dispatchPendingItemsToInsert();
880 // KDirLister keeps the children of items that got expanded once even if
881 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
882 // checked whether the parent for new items is still expanded.
883 const int parentIndex
= index(parentUrl
);
884 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
885 // The parent is not expanded.
890 QList
<ItemData
*> itemDataList
= createItemDataList(parentUrl
, items
);
892 if (!m_filter
.hasSetFilters()) {
893 m_pendingItemsToInsert
.append(itemDataList
);
895 // The name or type filter is active. Hide filtered items
896 // before inserting them into the model and remember
897 // the filtered items in m_filteredItems.
898 foreach (ItemData
* itemData
, itemDataList
) {
899 if (m_filter
.matches(itemData
->item
)) {
900 m_pendingItemsToInsert
.append(itemData
);
902 m_filteredItems
.insert(itemData
->item
, itemData
);
907 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer
->isActive()) {
908 // Assure that items get dispatched if no completed() or canceled() signal is
909 // emitted during the maximum update interval.
910 m_maximumUpdateIntervalTimer
->start();
914 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
916 dispatchPendingItemsToInsert();
918 QVector
<int> indexesToRemove
;
919 indexesToRemove
.reserve(items
.count());
921 foreach (const KFileItem
& item
, items
) {
922 const int indexForItem
= index(item
);
923 if (indexForItem
>= 0) {
924 indexesToRemove
.append(indexForItem
);
926 // Probably the item has been filtered.
927 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(item
);
928 if (it
!= m_filteredItems
.end()) {
930 m_filteredItems
.erase(it
);
935 std::sort(indexesToRemove
.begin(), indexesToRemove
.end());
937 if (m_requestRole
[ExpandedParentsCountRole
] && !m_expandedDirs
.isEmpty()) {
938 // Assure that removing a parent item also results in removing all children
939 QVector
<int> indexesToRemoveWithChildren
;
940 indexesToRemoveWithChildren
.reserve(m_itemData
.count());
942 const int itemCount
= m_itemData
.count();
943 foreach (int index
, indexesToRemove
) {
944 indexesToRemoveWithChildren
.append(index
);
946 const int parentLevel
= expandedParentsCount(index
);
947 int childIndex
= index
+ 1;
948 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
949 indexesToRemoveWithChildren
.append(childIndex
);
954 indexesToRemove
= indexesToRemoveWithChildren
;
957 const KItemRangeList itemRanges
= KItemRangeList::fromSortedContainer(indexesToRemove
);
958 removeFilteredChildren(itemRanges
);
959 removeItems(itemRanges
, DeleteItemData
);
962 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
964 Q_ASSERT(!items
.isEmpty());
965 #ifdef KFILEITEMMODEL_DEBUG
966 kDebug() << "Refreshing" << items
.count() << "items";
969 // Get the indexes of all items that have been refreshed
971 indexes
.reserve(items
.count());
973 QSet
<QByteArray
> changedRoles
;
975 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
976 while (it
.hasNext()) {
977 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
978 const KFileItem
& oldItem
= itemPair
.first
;
979 const KFileItem
& newItem
= itemPair
.second
;
980 const int indexForItem
= index(oldItem
);
981 if (indexForItem
>= 0) {
982 m_itemData
[indexForItem
]->item
= newItem
;
984 // Keep old values as long as possible if they could not retrieved synchronously yet.
985 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
986 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
, m_itemData
.at(indexForItem
)->parent
));
987 QHash
<QByteArray
, QVariant
>& values
= m_itemData
[indexForItem
]->values
;
988 while (it
.hasNext()) {
990 const QByteArray
& role
= it
.key();
991 if (values
.value(role
) != it
.value()) {
992 values
.insert(role
, it
.value());
993 changedRoles
.insert(role
);
997 m_items
.remove(oldItem
.url());
998 m_items
.insert(newItem
.url(), indexForItem
);
999 indexes
.append(indexForItem
);
1001 // Check if 'oldItem' is one of the filtered items.
1002 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(oldItem
);
1003 if (it
!= m_filteredItems
.end()) {
1004 ItemData
* itemData
= it
.value();
1005 itemData
->item
= newItem
;
1007 // The data stored in 'values' might have changed. Therefore, we clear
1008 // 'values' and re-populate it the next time it is requested via data(int).
1009 itemData
->values
.clear();
1011 m_filteredItems
.erase(it
);
1012 m_filteredItems
.insert(newItem
, itemData
);
1017 // If the changed items have been created recently, they might not be in m_items yet.
1018 // In that case, the list 'indexes' might be empty.
1019 if (indexes
.isEmpty()) {
1023 // Extract the item-ranges out of the changed indexes
1025 const KItemRangeList itemRangeList
= KItemRangeList::fromSortedContainer(indexes
);
1026 emitItemsChangedAndTriggerResorting(itemRangeList
, changedRoles
);
1029 void KFileItemModel::slotClear()
1031 #ifdef KFILEITEMMODEL_DEBUG
1032 kDebug() << "Clearing all items";
1035 qDeleteAll(m_filteredItems
.values());
1036 m_filteredItems
.clear();
1039 m_maximumUpdateIntervalTimer
->stop();
1040 m_resortAllItemsTimer
->stop();
1042 qDeleteAll(m_pendingItemsToInsert
);
1043 m_pendingItemsToInsert
.clear();
1045 const int removedCount
= m_itemData
.count();
1046 if (removedCount
> 0) {
1047 qDeleteAll(m_itemData
);
1050 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
1053 m_expandedDirs
.clear();
1056 void KFileItemModel::slotNaturalSortingChanged()
1058 m_naturalSorting
= KGlobalSettings::naturalSorting();
1062 void KFileItemModel::dispatchPendingItemsToInsert()
1064 if (!m_pendingItemsToInsert
.isEmpty()) {
1065 insertItems(m_pendingItemsToInsert
);
1066 m_pendingItemsToInsert
.clear();
1070 void KFileItemModel::insertItems(QList
<ItemData
*>& newItems
)
1072 if (newItems
.isEmpty()) {
1076 #ifdef KFILEITEMMODEL_DEBUG
1077 QElapsedTimer timer
;
1079 kDebug() << "===========================================================";
1080 kDebug() << "Inserting" << newItems
.count() << "items";
1084 prepareItemsForSorting(newItems
);
1086 if (m_sortRole
== NameRole
&& m_naturalSorting
) {
1087 // Natural sorting of items can be very slow. However, it becomes much
1088 // faster if the input sequence is already mostly sorted. Therefore, we
1089 // first sort 'newItems' according to the QStrings returned by
1090 // KFileItem::text() using QString::operator<(), which is quite fast.
1091 parallelMergeSort(newItems
.begin(), newItems
.end(), nameLessThan
, QThread::idealThreadCount());
1094 sort(newItems
.begin(), newItems
.end());
1096 #ifdef KFILEITEMMODEL_DEBUG
1097 kDebug() << "[TIME] Sorting:" << timer
.elapsed();
1100 KItemRangeList itemRanges
;
1101 const int existingItemCount
= m_itemData
.count();
1102 const int newItemCount
= newItems
.count();
1103 const int totalItemCount
= existingItemCount
+ newItemCount
;
1105 if (existingItemCount
== 0) {
1106 // Optimization for the common special case that there are no
1107 // items in the model yet. Happens, e.g., when entering a folder.
1108 m_itemData
= newItems
;
1109 itemRanges
<< KItemRange(0, newItemCount
);
1111 m_itemData
.reserve(totalItemCount
);
1112 for (int i
= existingItemCount
; i
< totalItemCount
; ++i
) {
1113 m_itemData
.append(0);
1116 // We build the new list m_itemData in reverse order to minimize
1117 // the number of moves and guarantee O(N) complexity.
1118 int targetIndex
= totalItemCount
- 1;
1119 int sourceIndexExistingItems
= existingItemCount
- 1;
1120 int sourceIndexNewItems
= newItemCount
- 1;
1124 while (sourceIndexNewItems
>= 0) {
1125 ItemData
* newItem
= newItems
.at(sourceIndexNewItems
);
1126 if (sourceIndexExistingItems
>= 0 && lessThan(newItem
, m_itemData
.at(sourceIndexExistingItems
))) {
1127 // Move an existing item to its new position. If any new items
1128 // are behind it, push the item range to itemRanges.
1129 if (rangeCount
> 0) {
1130 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1134 m_itemData
[targetIndex
] = m_itemData
.at(sourceIndexExistingItems
);
1135 --sourceIndexExistingItems
;
1137 // Insert a new item into the list.
1139 m_itemData
[targetIndex
] = newItem
;
1140 --sourceIndexNewItems
;
1145 // Push the final item range to itemRanges.
1146 if (rangeCount
> 0) {
1147 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1150 // Note that itemRanges is still sorted in reverse order.
1151 std::reverse(itemRanges
.begin(), itemRanges
.end());
1154 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1155 // It will be re-populated with the updated indices if index(const KUrl&) is called.
1158 emit
itemsInserted(itemRanges
);
1160 #ifdef KFILEITEMMODEL_DEBUG
1161 kDebug() << "[TIME] Inserting of" << newItems
.count() << "items:" << timer
.elapsed();
1165 void KFileItemModel::removeItems(const KItemRangeList
& itemRanges
, RemoveItemsBehavior behavior
)
1167 if (itemRanges
.isEmpty()) {
1173 // Step 1: Remove the items from m_itemData, and free the ItemData.
1174 int removedItemsCount
= 0;
1175 foreach (const KItemRange
& range
, itemRanges
) {
1176 removedItemsCount
+= range
.count
;
1178 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
1179 if (behavior
== DeleteItemData
) {
1180 delete m_itemData
.at(index
);
1183 m_itemData
[index
] = 0;
1187 // Step 2: Remove the ItemData pointers from the list m_itemData.
1188 int target
= itemRanges
.at(0).index
;
1189 int source
= itemRanges
.at(0).index
+ itemRanges
.at(0).count
;
1192 const int oldItemDataCount
= m_itemData
.count();
1193 while (source
< oldItemDataCount
) {
1194 m_itemData
[target
] = m_itemData
[source
];
1198 if (nextRange
< itemRanges
.count() && source
== itemRanges
.at(nextRange
).index
) {
1199 // Skip the items in the next removed range.
1200 source
+= itemRanges
.at(nextRange
).count
;
1205 m_itemData
.erase(m_itemData
.end() - removedItemsCount
, m_itemData
.end());
1207 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1208 // It will be re-populated with the updated indices if index(const KUrl&) is called.
1211 emit
itemsRemoved(itemRanges
);
1214 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const KUrl
& parentUrl
, const KFileItemList
& items
) const
1216 if (m_sortRole
== TypeRole
) {
1217 // Try to resolve the MIME-types synchronously to prevent a reordering of
1218 // the items when sorting by type (per default MIME-types are resolved
1219 // asynchronously by KFileItemModelRolesUpdater).
1220 determineMimeTypes(items
, 200);
1223 const int parentIndex
= index(parentUrl
);
1224 ItemData
* parentItem
= parentIndex
< 0 ? 0 : m_itemData
.at(parentIndex
);
1226 QList
<ItemData
*> itemDataList
;
1227 itemDataList
.reserve(items
.count());
1229 foreach (const KFileItem
& item
, items
) {
1230 ItemData
* itemData
= new ItemData();
1231 itemData
->item
= item
;
1232 itemData
->parent
= parentItem
;
1233 itemDataList
.append(itemData
);
1236 return itemDataList
;
1239 void KFileItemModel::prepareItemsForSorting(QList
<ItemData
*>& itemDataList
)
1241 switch (m_sortRole
) {
1242 case PermissionsRole
:
1245 case DestinationRole
:
1247 // These roles can be determined with retrieveData, and they have to be stored
1248 // in the QHash "values" for the sorting.
1249 foreach (ItemData
* itemData
, itemDataList
) {
1250 if (itemData
->values
.isEmpty()) {
1251 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1257 // At least store the data including the file type for items with known MIME type.
1258 foreach (ItemData
* itemData
, itemDataList
) {
1259 if (itemData
->values
.isEmpty()) {
1260 const KFileItem item
= itemData
->item
;
1261 if (item
.isDir() || item
.isMimeTypeKnown()) {
1262 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1269 // The other roles are either resolved by KFileItemModelRolesUpdater
1270 // (this includes the SizeRole for directories), or they do not need
1271 // to be stored in the QHash "values" for sorting because the data can
1272 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1278 int KFileItemModel::expandedParentsCount(const ItemData
* data
)
1280 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1281 // if the corresponding item is expanded, and it is not a top-level item.
1282 const ItemData
* parent
= data
->parent
;
1284 if (parent
->parent
) {
1285 Q_ASSERT(parent
->values
.contains("expandedParentsCount"));
1286 return parent
->values
.value("expandedParentsCount").toInt() + 1;
1295 void KFileItemModel::removeExpandedItems()
1297 QVector
<int> indexesToRemove
;
1299 const int maxIndex
= m_itemData
.count() - 1;
1300 for (int i
= 0; i
<= maxIndex
; ++i
) {
1301 const ItemData
* itemData
= m_itemData
.at(i
);
1302 if (itemData
->parent
) {
1303 indexesToRemove
.append(i
);
1307 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove
), DeleteItemData
);
1308 m_expandedDirs
.clear();
1310 // Also remove all filtered items which have a parent.
1311 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
1312 const QHash
<KFileItem
, ItemData
*>::iterator end
= m_filteredItems
.end();
1315 if (it
.value()->parent
) {
1317 it
= m_filteredItems
.erase(it
);
1324 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList
& itemRanges
, const QSet
<QByteArray
>& changedRoles
)
1326 emit
itemsChanged(itemRanges
, changedRoles
);
1328 // Trigger a resorting if necessary. Note that this can happen even if the sort
1329 // role has not changed at all because the file name can be used as a fallback.
1330 if (changedRoles
.contains(sortRole()) || changedRoles
.contains(roleForType(NameRole
))) {
1331 foreach (const KItemRange
& range
, itemRanges
) {
1332 bool needsResorting
= false;
1334 const int first
= range
.index
;
1335 const int last
= range
.index
+ range
.count
- 1;
1337 // Resorting the model is necessary if
1338 // (a) The first item in the range is "lessThan" its predecessor,
1339 // (b) the successor of the last item is "lessThan" the last item, or
1340 // (c) the internal order of the items in the range is incorrect.
1342 && lessThan(m_itemData
.at(first
), m_itemData
.at(first
- 1))) {
1343 needsResorting
= true;
1344 } else if (last
< count() - 1
1345 && lessThan(m_itemData
.at(last
+ 1), m_itemData
.at(last
))) {
1346 needsResorting
= true;
1348 for (int index
= first
; index
< last
; ++index
) {
1349 if (lessThan(m_itemData
.at(index
+ 1), m_itemData
.at(index
))) {
1350 needsResorting
= true;
1356 if (needsResorting
) {
1357 m_resortAllItemsTimer
->start();
1363 if (groupedSorting() && changedRoles
.contains(sortRole())) {
1364 // The position is still correct, but the groups might have changed
1365 // if the changed item is either the first or the last item in a
1367 // In principle, we could try to find out if the item really is the
1368 // first or last one in its group and then update the groups
1369 // (possibly with a delayed timer to make sure that we don't
1370 // re-calculate the groups very often if items are updated one by
1371 // one), but starting m_resortAllItemsTimer is easier.
1372 m_resortAllItemsTimer
->start();
1376 void KFileItemModel::resetRoles()
1378 for (int i
= 0; i
< RolesCount
; ++i
) {
1379 m_requestRole
[i
] = false;
1383 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1385 static QHash
<QByteArray
, RoleType
> roles
;
1386 if (roles
.isEmpty()) {
1387 // Insert user visible roles that can be accessed with
1388 // KFileItemModel::roleInformation()
1390 const RoleInfoMap
* map
= rolesInfoMap(count
);
1391 for (int i
= 0; i
< count
; ++i
) {
1392 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1395 // Insert internal roles (take care to synchronize the implementation
1396 // with KFileItemModel::roleForType() in case if a change is done).
1397 roles
.insert("isDir", IsDirRole
);
1398 roles
.insert("isLink", IsLinkRole
);
1399 roles
.insert("isExpanded", IsExpandedRole
);
1400 roles
.insert("isExpandable", IsExpandableRole
);
1401 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1403 Q_ASSERT(roles
.count() == RolesCount
);
1406 return roles
.value(role
, NoRole
);
1409 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1411 static QHash
<RoleType
, QByteArray
> roles
;
1412 if (roles
.isEmpty()) {
1413 // Insert user visible roles that can be accessed with
1414 // KFileItemModel::roleInformation()
1416 const RoleInfoMap
* map
= rolesInfoMap(count
);
1417 for (int i
= 0; i
< count
; ++i
) {
1418 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1421 // Insert internal roles (take care to synchronize the implementation
1422 // with KFileItemModel::typeForRole() in case if a change is done).
1423 roles
.insert(IsDirRole
, "isDir");
1424 roles
.insert(IsLinkRole
, "isLink");
1425 roles
.insert(IsExpandedRole
, "isExpanded");
1426 roles
.insert(IsExpandableRole
, "isExpandable");
1427 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1429 Q_ASSERT(roles
.count() == RolesCount
);
1432 return roles
.value(roleType
);
1435 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
, const ItemData
* parent
) const
1437 // It is important to insert only roles that are fast to retrieve. E.g.
1438 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1439 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1440 QHash
<QByteArray
, QVariant
> data
;
1441 data
.insert(sharedValue("url"), item
.url());
1443 const bool isDir
= item
.isDir();
1444 if (m_requestRole
[IsDirRole
] && isDir
) {
1445 data
.insert(sharedValue("isDir"), true);
1448 if (m_requestRole
[IsLinkRole
] && item
.isLink()) {
1449 data
.insert(sharedValue("isLink"), true);
1452 if (m_requestRole
[NameRole
]) {
1453 data
.insert(sharedValue("text"), item
.text());
1456 if (m_requestRole
[SizeRole
] && !isDir
) {
1457 data
.insert(sharedValue("size"), item
.size());
1460 if (m_requestRole
[DateRole
]) {
1461 // Don't use KFileItem::timeString() as this is too expensive when
1462 // having several thousands of items. Instead the formatting of the
1463 // date-time will be done on-demand by the view when the date will be shown.
1464 const KDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
1465 data
.insert(sharedValue("date"), dateTime
.dateTime());
1468 if (m_requestRole
[PermissionsRole
]) {
1469 data
.insert(sharedValue("permissions"), item
.permissionsString());
1472 if (m_requestRole
[OwnerRole
]) {
1473 data
.insert(sharedValue("owner"), item
.user());
1476 if (m_requestRole
[GroupRole
]) {
1477 data
.insert(sharedValue("group"), item
.group());
1480 if (m_requestRole
[DestinationRole
]) {
1481 QString destination
= item
.linkDest();
1482 if (destination
.isEmpty()) {
1483 destination
= QLatin1String("-");
1485 data
.insert(sharedValue("destination"), destination
);
1488 if (m_requestRole
[PathRole
]) {
1490 if (item
.url().protocol() == QLatin1String("trash")) {
1491 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1493 // For performance reasons cache the home-path in a static QString
1494 // (see QDir::homePath() for more details)
1495 static QString homePath
;
1496 if (homePath
.isEmpty()) {
1497 homePath
= QDir::homePath();
1500 path
= item
.localPath();
1501 if (path
.startsWith(homePath
)) {
1502 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1506 const int index
= path
.lastIndexOf(item
.text());
1507 path
= path
.mid(0, index
- 1);
1508 data
.insert(sharedValue("path"), path
);
1511 if (m_requestRole
[IsExpandableRole
] && isDir
) {
1512 data
.insert(sharedValue("isExpandable"), true);
1515 if (m_requestRole
[ExpandedParentsCountRole
]) {
1517 const int level
= expandedParentsCount(parent
) + 1;
1518 data
.insert(sharedValue("expandedParentsCount"), level
);
1522 if (item
.isMimeTypeKnown()) {
1523 data
.insert(sharedValue("iconName"), item
.iconName());
1525 if (m_requestRole
[TypeRole
]) {
1526 data
.insert(sharedValue("type"), item
.mimeComment());
1528 } else if (m_requestRole
[TypeRole
] && isDir
) {
1529 static const QString folderMimeType
= item
.mimeComment();
1530 data
.insert(sharedValue("type"), folderMimeType
);
1536 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
) const
1540 if (a
->parent
!= b
->parent
) {
1541 const int expansionLevelA
= expandedParentsCount(a
);
1542 const int expansionLevelB
= expandedParentsCount(b
);
1544 // If b has a higher expansion level than a, check if a is a parent
1545 // of b, and make sure that both expansion levels are equal otherwise.
1546 for (int i
= expansionLevelB
; i
> expansionLevelA
; --i
) {
1547 if (b
->parent
== a
) {
1553 // If a has a higher expansion level than a, check if b is a parent
1554 // of a, and make sure that both expansion levels are equal otherwise.
1555 for (int i
= expansionLevelA
; i
> expansionLevelB
; --i
) {
1556 if (a
->parent
== b
) {
1562 Q_ASSERT(expandedParentsCount(a
) == expandedParentsCount(b
));
1564 // Compare the last parents of a and b which are different.
1565 while (a
->parent
!= b
->parent
) {
1571 if (m_sortDirsFirst
|| m_sortRole
== SizeRole
) {
1572 const bool isDirA
= a
->item
.isDir();
1573 const bool isDirB
= b
->item
.isDir();
1574 if (isDirA
&& !isDirB
) {
1576 } else if (!isDirA
&& isDirB
) {
1581 result
= sortRoleCompare(a
, b
);
1583 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1587 * Helper class for KFileItemModel::sort().
1589 class KFileItemModelLessThan
1592 KFileItemModelLessThan(const KFileItemModel
* model
) :
1597 bool operator()(const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
) const
1599 return m_model
->lessThan(a
, b
);
1603 const KFileItemModel
* m_model
;
1606 void KFileItemModel::sort(QList
<KFileItemModel::ItemData
*>::iterator begin
,
1607 QList
<KFileItemModel::ItemData
*>::iterator end
) const
1609 KFileItemModelLessThan
lessThan(this);
1611 if (m_sortRole
== NameRole
) {
1612 // Sorting by name can be expensive, in particular if natural sorting is
1613 // enabled. Use all CPU cores to speed up the sorting process.
1614 static const int numberOfThreads
= QThread::idealThreadCount();
1615 parallelMergeSort(begin
, end
, lessThan
, numberOfThreads
);
1617 // Sorting by other roles is quite fast. Use only one thread to prevent
1618 // problems caused by non-reentrant comparison functions, see
1619 // https://bugs.kde.org/show_bug.cgi?id=312679
1620 mergeSort(begin
, end
, lessThan
);
1624 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
) const
1626 const KFileItem
& itemA
= a
->item
;
1627 const KFileItem
& itemB
= b
->item
;
1631 switch (m_sortRole
) {
1633 // The name role is handled as default fallback after the switch
1637 if (itemA
.isDir()) {
1638 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1639 Q_ASSERT(itemB
.isDir());
1641 const QVariant valueA
= a
->values
.value("size");
1642 const QVariant valueB
= b
->values
.value("size");
1643 if (valueA
.isNull() && valueB
.isNull()) {
1645 } else if (valueA
.isNull()) {
1647 } else if (valueB
.isNull()) {
1650 result
= valueA
.toInt() - valueB
.toInt();
1653 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1654 Q_ASSERT(!itemB
.isDir());
1655 const KIO::filesize_t sizeA
= itemA
.size();
1656 const KIO::filesize_t sizeB
= itemB
.size();
1657 if (sizeA
> sizeB
) {
1659 } else if (sizeA
< sizeB
) {
1669 const KDateTime dateTimeA
= itemA
.time(KFileItem::ModificationTime
);
1670 const KDateTime dateTimeB
= itemB
.time(KFileItem::ModificationTime
);
1671 if (dateTimeA
< dateTimeB
) {
1673 } else if (dateTimeA
> dateTimeB
) {
1680 result
= a
->values
.value("rating").toInt() - b
->values
.value("rating").toInt();
1684 case ImageSizeRole
: {
1685 // Alway use a natural comparing to interpret the numbers of a string like
1686 // "1600 x 1200" for having a correct sorting.
1687 result
= KStringHandler::naturalCompare(a
->values
.value("imageSize").toString(),
1688 b
->values
.value("imageSize").toString(),
1694 const QByteArray role
= roleForType(m_sortRole
);
1695 result
= QString::compare(a
->values
.value(role
).toString(),
1696 b
->values
.value(role
).toString());
1703 // The current sort role was sufficient to define an order
1707 // Fallback #1: Compare the text of the items
1708 result
= stringCompare(itemA
.text(), itemB
.text());
1713 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1714 result
= stringCompare(itemA
.name(m_caseSensitivity
== Qt::CaseInsensitive
),
1715 itemB
.name(m_caseSensitivity
== Qt::CaseInsensitive
));
1720 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1721 // equal. In this case a comparison of the URL is done which is unique in all cases
1722 // within KDirLister.
1723 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1726 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
) const
1728 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1729 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1730 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1731 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1733 if (m_caseSensitivity
== Qt::CaseInsensitive
) {
1734 const int result
= m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseInsensitive
)
1735 : QString::compare(a
, b
, Qt::CaseInsensitive
);
1737 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1738 // comparison, still a deterministic sort order is required. A case sensitive
1739 // comparison is done as fallback.
1744 return m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseSensitive
)
1745 : QString::compare(a
, b
, Qt::CaseSensitive
);
1748 bool KFileItemModel::useMaximumUpdateInterval() const
1750 return !m_dirLister
->url().isLocalFile();
1753 static bool localeAwareLessThan(const QChar
& c1
, const QChar
& c2
)
1755 return QString::localeAwareCompare(c1
, c2
) < 0;
1758 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1760 Q_ASSERT(!m_itemData
.isEmpty());
1762 const int maxIndex
= count() - 1;
1763 QList
<QPair
<int, QVariant
> > groups
;
1767 for (int i
= 0; i
<= maxIndex
; ++i
) {
1768 if (isChildItem(i
)) {
1772 const QString name
= m_itemData
.at(i
)->item
.text();
1774 // Use the first character of the name as group indication
1775 QChar newFirstChar
= name
.at(0).toUpper();
1776 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1777 newFirstChar
= name
.at(1).toUpper();
1780 if (firstChar
!= newFirstChar
) {
1781 QString newGroupValue
;
1782 if (newFirstChar
.isLetter()) {
1783 // Try to find a matching group in the range 'A' to 'Z'.
1784 static std::vector
<QChar
> lettersAtoZ
;
1785 if (lettersAtoZ
.empty()) {
1786 for (char c
= 'A'; c
<= 'Z'; ++c
) {
1787 lettersAtoZ
.push_back(QLatin1Char(c
));
1791 std::vector
<QChar
>::iterator it
= std::lower_bound(lettersAtoZ
.begin(), lettersAtoZ
.end(), newFirstChar
, localeAwareLessThan
);
1792 if (it
!= lettersAtoZ
.end()) {
1793 if (localeAwareLessThan(newFirstChar
, *it
) && it
!= lettersAtoZ
.begin()) {
1794 // newFirstChar belongs to the group preceding *it.
1795 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
1798 newGroupValue
= *it
;
1800 newGroupValue
= newFirstChar
;
1802 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
1803 // Apply group '0 - 9' for any name that starts with a digit
1804 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
1806 newGroupValue
= i18nc("@title:group", "Others");
1809 if (newGroupValue
!= groupValue
) {
1810 groupValue
= newGroupValue
;
1811 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1814 firstChar
= newFirstChar
;
1820 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
1822 Q_ASSERT(!m_itemData
.isEmpty());
1824 const int maxIndex
= count() - 1;
1825 QList
<QPair
<int, QVariant
> > groups
;
1828 for (int i
= 0; i
<= maxIndex
; ++i
) {
1829 if (isChildItem(i
)) {
1833 const KFileItem
& item
= m_itemData
.at(i
)->item
;
1834 const KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
1835 QString newGroupValue
;
1836 if (!item
.isNull() && item
.isDir()) {
1837 newGroupValue
= i18nc("@title:group Size", "Folders");
1838 } else if (fileSize
< 5 * 1024 * 1024) {
1839 newGroupValue
= i18nc("@title:group Size", "Small");
1840 } else if (fileSize
< 10 * 1024 * 1024) {
1841 newGroupValue
= i18nc("@title:group Size", "Medium");
1843 newGroupValue
= i18nc("@title:group Size", "Big");
1846 if (newGroupValue
!= groupValue
) {
1847 groupValue
= newGroupValue
;
1848 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1855 QList
<QPair
<int, QVariant
> > KFileItemModel::dateRoleGroups() const
1857 Q_ASSERT(!m_itemData
.isEmpty());
1859 const int maxIndex
= count() - 1;
1860 QList
<QPair
<int, QVariant
> > groups
;
1862 const QDate currentDate
= KDateTime::currentLocalDateTime().date();
1864 QDate previousModifiedDate
;
1866 for (int i
= 0; i
<= maxIndex
; ++i
) {
1867 if (isChildItem(i
)) {
1871 const KDateTime modifiedTime
= m_itemData
.at(i
)->item
.time(KFileItem::ModificationTime
);
1872 const QDate modifiedDate
= modifiedTime
.date();
1873 if (modifiedDate
== previousModifiedDate
) {
1874 // The current item is in the same group as the previous item
1877 previousModifiedDate
= modifiedDate
;
1879 const int daysDistance
= modifiedDate
.daysTo(currentDate
);
1881 QString newGroupValue
;
1882 if (currentDate
.year() == modifiedDate
.year() && currentDate
.month() == modifiedDate
.month()) {
1883 switch (daysDistance
/ 7) {
1885 switch (daysDistance
) {
1886 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
1887 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
1888 default: newGroupValue
= modifiedTime
.toString(i18nc("@title:group The week day name: %A", "%A"));
1892 newGroupValue
= i18nc("@title:group Date", "One Week Ago");
1895 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
1898 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
1902 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
1908 const QDate lastMonthDate
= currentDate
.addMonths(-1);
1909 if (lastMonthDate
.year() == modifiedDate
.year() && lastMonthDate
.month() == modifiedDate
.month()) {
1910 if (daysDistance
== 1) {
1911 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Yesterday (%B, %Y)"));
1912 } else if (daysDistance
<= 7) {
1913 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)"));
1914 } else if (daysDistance
<= 7 * 2) {
1915 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "One Week Ago (%B, %Y)"));
1916 } else if (daysDistance
<= 7 * 3) {
1917 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)"));
1918 } else if (daysDistance
<= 7 * 4) {
1919 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)"));
1921 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"));
1924 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"));
1928 if (newGroupValue
!= groupValue
) {
1929 groupValue
= newGroupValue
;
1930 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1937 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
1939 Q_ASSERT(!m_itemData
.isEmpty());
1941 const int maxIndex
= count() - 1;
1942 QList
<QPair
<int, QVariant
> > groups
;
1944 QString permissionsString
;
1946 for (int i
= 0; i
<= maxIndex
; ++i
) {
1947 if (isChildItem(i
)) {
1951 const ItemData
* itemData
= m_itemData
.at(i
);
1952 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
1953 if (newPermissionsString
== permissionsString
) {
1956 permissionsString
= newPermissionsString
;
1958 const QFileInfo
info(itemData
->item
.url().pathOrUrl());
1962 if (info
.permission(QFile::ReadUser
)) {
1963 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1965 if (info
.permission(QFile::WriteUser
)) {
1966 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1968 if (info
.permission(QFile::ExeUser
)) {
1969 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1971 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
1975 if (info
.permission(QFile::ReadGroup
)) {
1976 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1978 if (info
.permission(QFile::WriteGroup
)) {
1979 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1981 if (info
.permission(QFile::ExeGroup
)) {
1982 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1984 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
1986 // Set others string
1988 if (info
.permission(QFile::ReadOther
)) {
1989 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1991 if (info
.permission(QFile::WriteOther
)) {
1992 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1994 if (info
.permission(QFile::ExeOther
)) {
1995 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1997 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
1999 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
2000 if (newGroupValue
!= groupValue
) {
2001 groupValue
= newGroupValue
;
2002 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2009 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
2011 Q_ASSERT(!m_itemData
.isEmpty());
2013 const int maxIndex
= count() - 1;
2014 QList
<QPair
<int, QVariant
> > groups
;
2016 int groupValue
= -1;
2017 for (int i
= 0; i
<= maxIndex
; ++i
) {
2018 if (isChildItem(i
)) {
2021 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
2022 if (newGroupValue
!= groupValue
) {
2023 groupValue
= newGroupValue
;
2024 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2031 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
2033 Q_ASSERT(!m_itemData
.isEmpty());
2035 const int maxIndex
= count() - 1;
2036 QList
<QPair
<int, QVariant
> > groups
;
2038 bool isFirstGroupValue
= true;
2040 for (int i
= 0; i
<= maxIndex
; ++i
) {
2041 if (isChildItem(i
)) {
2044 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
2045 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
2046 groupValue
= newGroupValue
;
2047 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2048 isFirstGroupValue
= false;
2055 void KFileItemModel::emitSortProgress(int resolvedCount
)
2057 // Be tolerant against a resolvedCount with a wrong range.
2058 // Although there should not be a case where KFileItemModelRolesUpdater
2059 // (= caller) provides a wrong range, it is important to emit
2060 // a useful progress information even if there is an unexpected
2061 // implementation issue.
2063 const int itemCount
= count();
2064 if (resolvedCount
>= itemCount
) {
2065 m_sortingProgressPercent
= -1;
2066 if (m_resortAllItemsTimer
->isActive()) {
2067 m_resortAllItemsTimer
->stop();
2071 emit
directorySortingProgress(100);
2072 } else if (itemCount
> 0) {
2073 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
2075 const int progress
= resolvedCount
* 100 / itemCount
;
2076 if (m_sortingProgressPercent
!= progress
) {
2077 m_sortingProgressPercent
= progress
;
2078 emit
directorySortingProgress(progress
);
2083 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
2085 static const RoleInfoMap rolesInfoMap
[] = {
2086 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
2087 { 0, NoRole
, 0, 0, 0, 0, false, false },
2088 { "text", NameRole
, I18N_NOOP2_NOSTRIP("@label", "Name"), 0, 0, false, false },
2089 { "size", SizeRole
, I18N_NOOP2_NOSTRIP("@label", "Size"), 0, 0, false, false },
2090 { "date", DateRole
, I18N_NOOP2_NOSTRIP("@label", "Date"), 0, 0, false, false },
2091 { "type", TypeRole
, I18N_NOOP2_NOSTRIP("@label", "Type"), 0, 0, false, false },
2092 { "rating", RatingRole
, I18N_NOOP2_NOSTRIP("@label", "Rating"), 0, 0, true, false },
2093 { "tags", TagsRole
, I18N_NOOP2_NOSTRIP("@label", "Tags"), 0, 0, true, false },
2094 { "comment", CommentRole
, I18N_NOOP2_NOSTRIP("@label", "Comment"), 0, 0, true, false },
2095 { "wordCount", WordCountRole
, I18N_NOOP2_NOSTRIP("@label", "Word Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
2096 { "lineCount", LineCountRole
, I18N_NOOP2_NOSTRIP("@label", "Line Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
2097 { "imageSize", ImageSizeRole
, I18N_NOOP2_NOSTRIP("@label", "Image Size"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
2098 { "orientation", OrientationRole
, I18N_NOOP2_NOSTRIP("@label", "Orientation"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
2099 { "artist", ArtistRole
, I18N_NOOP2_NOSTRIP("@label", "Artist"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
2100 { "album", AlbumRole
, I18N_NOOP2_NOSTRIP("@label", "Album"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
2101 { "duration", DurationRole
, I18N_NOOP2_NOSTRIP("@label", "Duration"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
2102 { "track", TrackRole
, I18N_NOOP2_NOSTRIP("@label", "Track"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
2103 { "path", PathRole
, I18N_NOOP2_NOSTRIP("@label", "Path"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2104 { "destination", DestinationRole
, I18N_NOOP2_NOSTRIP("@label", "Link Destination"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2105 { "copiedFrom", CopiedFromRole
, I18N_NOOP2_NOSTRIP("@label", "Copied From"), I18N_NOOP2_NOSTRIP("@label", "Other"), true, false },
2106 { "permissions", PermissionsRole
, I18N_NOOP2_NOSTRIP("@label", "Permissions"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2107 { "owner", OwnerRole
, I18N_NOOP2_NOSTRIP("@label", "Owner"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2108 { "group", GroupRole
, I18N_NOOP2_NOSTRIP("@label", "User Group"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2111 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
2112 return rolesInfoMap
;
2115 void KFileItemModel::determineMimeTypes(const KFileItemList
& items
, int timeout
)
2117 QElapsedTimer timer
;
2119 foreach (const KFileItem
& item
, items
) { // krazy:exclude=foreach
2120 // Only determine mime types for files here. For directories,
2121 // KFileItem::determineMimeType() reads the .directory file inside to
2122 // load the icon, but this is not necessary at all if we just need the
2123 // type. Some special code for setting the correct mime type for
2124 // directories is in retrieveData().
2125 if (!item
.isDir()) {
2126 item
.determineMimeType();
2129 if (timer
.elapsed() > timeout
) {
2130 // Don't block the user interface, let the remaining items
2131 // be resolved asynchronously.
2137 QByteArray
KFileItemModel::sharedValue(const QByteArray
& value
)
2139 static QSet
<QByteArray
> pool
;
2140 const QSet
<QByteArray
>::const_iterator it
= pool
.constFind(value
);
2142 if (it
!= pool
.constEnd()) {
2150 bool KFileItemModel::isConsistent() const
2152 // m_items may contain less items than m_itemData because m_items
2153 // is populated lazily, see KFileItemModel::index(const KUrl& url).
2154 if (m_items
.count() > m_itemData
.count()) {
2158 for (int i
= 0; i
< count(); ++i
) {
2159 // Check if m_items and m_itemData are consistent.
2160 const KFileItem item
= fileItem(i
);
2161 if (item
.isNull()) {
2162 qWarning() << "Item" << i
<< "is null";
2166 const int itemIndex
= index(item
);
2167 if (itemIndex
!= i
) {
2168 qWarning() << "Item" << i
<< "has a wrong index:" << itemIndex
;
2172 // Check if the items are sorted correctly.
2173 if (i
> 0 && !lessThan(m_itemData
.at(i
- 1), m_itemData
.at(i
))) {
2174 qWarning() << "The order of items" << i
- 1 << "and" << i
<< "is wrong:"
2175 << fileItem(i
- 1) << fileItem(i
);
2179 // Check if all parent-child relationships are consistent.
2180 const ItemData
* data
= m_itemData
.at(i
);
2181 const ItemData
* parent
= data
->parent
;
2183 if (expandedParentsCount(data
) != expandedParentsCount(parent
) + 1) {
2184 qWarning() << "expandedParentsCount is inconsistent for parent" << parent
->item
<< "and child" << data
->item
;
2188 const int parentIndex
= index(parent
->item
);
2189 if (parentIndex
>= i
) {
2190 qWarning() << "Index" << parentIndex
<< "of parent" << parent
->item
<< "is not smaller than index" << i
<< "of child" << data
->item
;
2199 #include "kfileitemmodel.moc"