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>
28 #include <kstringhandler_deprecated.h> //TODO: port to QCollator
30 #include "private/kfileitemmodelsortalgorithm.h"
31 #include "private/kfileitemmodeldirlister.h"
33 #include <QApplication>
41 // #define KFILEITEMMODEL_DEBUG
43 KFileItemModel::KFileItemModel(QObject
* parent
) :
44 KItemModelBase("text", parent
),
46 m_naturalSorting(KGlobalSettings::naturalSorting()),
47 m_sortDirsFirst(true),
49 m_sortingProgressPercent(-1),
51 m_caseSensitivity(Qt::CaseInsensitive
),
57 m_maximumUpdateIntervalTimer(0),
58 m_resortAllItemsTimer(0),
59 m_pendingItemsToInsert(),
64 m_dirLister
= new KFileItemModelDirLister(this);
65 m_dirLister
->setDelayedMimeTypes(true);
67 const QWidget
* parentWidget
= qobject_cast
<QWidget
*>(parent
);
69 m_dirLister
->setMainWindow(parentWidget
->window());
72 connect(m_dirLister
, &KFileItemModelDirLister::started
, this, &KFileItemModel::directoryLoadingStarted
);
73 connect(m_dirLister
, static_cast<void(KFileItemModelDirLister::*)()>(&KFileItemModelDirLister::canceled
), this, &KFileItemModel::slotCanceled
);
74 connect(m_dirLister
, static_cast<void(KFileItemModelDirLister::*)(const QUrl
&)>(&KFileItemModelDirLister::completed
), this, &KFileItemModel::slotCompleted
);
75 connect(m_dirLister
, &KFileItemModelDirLister::itemsAdded
, this, &KFileItemModel::slotItemsAdded
);
76 connect(m_dirLister
, &KFileItemModelDirLister::itemsDeleted
, this, &KFileItemModel::slotItemsDeleted
);
77 connect(m_dirLister
, &KFileItemModelDirLister::refreshItems
, this, &KFileItemModel::slotRefreshItems
);
78 connect(m_dirLister
, static_cast<void(KFileItemModelDirLister::*)()>(&KFileItemModelDirLister::clear
), this, &KFileItemModel::slotClear
);
79 connect(m_dirLister
, &KFileItemModelDirLister::infoMessage
, this, &KFileItemModel::infoMessage
);
80 connect(m_dirLister
, &KFileItemModelDirLister::errorMessage
, this, &KFileItemModel::errorMessage
);
81 connect(m_dirLister
, static_cast<void(KFileItemModelDirLister::*)(const QUrl
&, const QUrl
&)>(&KFileItemModelDirLister::redirection
), this, &KFileItemModel::directoryRedirection
);
82 connect(m_dirLister
, &KFileItemModelDirLister::urlIsFileError
, this, &KFileItemModel::urlIsFileError
);
84 // Apply default roles that should be determined
86 m_requestRole
[NameRole
] = true;
87 m_requestRole
[IsDirRole
] = true;
88 m_requestRole
[IsLinkRole
] = true;
89 m_roles
.insert("text");
90 m_roles
.insert("isDir");
91 m_roles
.insert("isLink");
93 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
94 // before the completed() or canceled() signal has been emitted.
95 m_maximumUpdateIntervalTimer
= new QTimer(this);
96 m_maximumUpdateIntervalTimer
->setInterval(2000);
97 m_maximumUpdateIntervalTimer
->setSingleShot(true);
98 connect(m_maximumUpdateIntervalTimer
, &QTimer::timeout
, this, &KFileItemModel::dispatchPendingItemsToInsert
);
100 // When changing the value of an item which represents the sort-role a resorting must be
101 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
102 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
103 // resorting is postponed until the timer has been exceeded.
104 m_resortAllItemsTimer
= new QTimer(this);
105 m_resortAllItemsTimer
->setInterval(500);
106 m_resortAllItemsTimer
->setSingleShot(true);
107 connect(m_resortAllItemsTimer
, &QTimer::timeout
, this, &KFileItemModel::resortAllItems
);
109 connect(KGlobalSettings::self(), &KGlobalSettings::naturalSortingChanged
,
110 this, &KFileItemModel::slotNaturalSortingChanged
);
113 KFileItemModel::~KFileItemModel()
115 qDeleteAll(m_itemData
);
116 qDeleteAll(m_filteredItems
.values());
117 qDeleteAll(m_pendingItemsToInsert
);
120 void KFileItemModel::loadDirectory(const KUrl
& url
)
122 m_dirLister
->openUrl(url
);
125 void KFileItemModel::refreshDirectory(const KUrl
& url
)
127 // Refresh all expanded directories first (Bug 295300)
128 QHashIterator
<KUrl
, KUrl
> expandedDirs(m_expandedDirs
);
129 while (expandedDirs
.hasNext()) {
131 m_dirLister
->openUrl(expandedDirs
.value(), KDirLister::Reload
);
134 m_dirLister
->openUrl(url
, KDirLister::Reload
);
137 KUrl
KFileItemModel::directory() const
139 return m_dirLister
->url();
142 void KFileItemModel::cancelDirectoryLoading()
147 int KFileItemModel::count() const
149 return m_itemData
.count();
152 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
154 if (index
>= 0 && index
< count()) {
155 ItemData
* data
= m_itemData
.at(index
);
156 if (data
->values
.isEmpty()) {
157 data
->values
= retrieveData(data
->item
, data
->parent
);
162 return QHash
<QByteArray
, QVariant
>();
165 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
167 if (index
< 0 || index
>= count()) {
171 QHash
<QByteArray
, QVariant
> currentValues
= data(index
);
173 // Determine which roles have been changed
174 QSet
<QByteArray
> changedRoles
;
175 QHashIterator
<QByteArray
, QVariant
> it(values
);
176 while (it
.hasNext()) {
178 const QByteArray role
= sharedValue(it
.key());
179 const QVariant value
= it
.value();
181 if (currentValues
[role
] != value
) {
182 currentValues
[role
] = value
;
183 changedRoles
.insert(role
);
187 if (changedRoles
.isEmpty()) {
191 m_itemData
[index
]->values
= currentValues
;
192 if (changedRoles
.contains("text")) {
193 KUrl url
= m_itemData
[index
]->item
.url();
194 url
.setFileName(currentValues
["text"].toString());
195 m_itemData
[index
]->item
.setUrl(url
);
198 emitItemsChangedAndTriggerResorting(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
203 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
205 if (dirsFirst
!= m_sortDirsFirst
) {
206 m_sortDirsFirst
= dirsFirst
;
211 bool KFileItemModel::sortDirectoriesFirst() const
213 return m_sortDirsFirst
;
216 void KFileItemModel::setShowHiddenFiles(bool show
)
218 m_dirLister
->setShowingDotFiles(show
);
219 m_dirLister
->emitChanges();
221 dispatchPendingItemsToInsert();
225 bool KFileItemModel::showHiddenFiles() const
227 return m_dirLister
->showingDotFiles();
230 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
232 m_dirLister
->setDirOnlyMode(enabled
);
235 bool KFileItemModel::showDirectoriesOnly() const
237 return m_dirLister
->dirOnlyMode();
240 QMimeData
* KFileItemModel::createMimeData(const KItemSet
& indexes
) const
242 QMimeData
* data
= new QMimeData();
244 // The following code has been taken from KDirModel::mimeData()
245 // (kdelibs/kio/kio/kdirmodel.cpp)
246 // Copyright (C) 2006 David Faure <faure@kde.org>
248 KUrl::List mostLocalUrls
;
249 bool canUseMostLocalUrls
= true;
250 const ItemData
* lastAddedItem
= 0;
252 foreach (int index
, indexes
) {
253 const ItemData
* itemData
= m_itemData
.at(index
);
254 const ItemData
* parent
= itemData
->parent
;
256 while (parent
&& parent
!= lastAddedItem
) {
257 parent
= parent
->parent
;
260 if (parent
&& parent
== lastAddedItem
) {
261 // A parent of 'itemData' has been added already.
265 lastAddedItem
= itemData
;
266 const KFileItem
& item
= itemData
->item
;
267 if (!item
.isNull()) {
268 urls
<< item
.targetUrl();
271 mostLocalUrls
<< item
.mostLocalUrl(isLocal
);
273 canUseMostLocalUrls
= false;
278 const bool different
= canUseMostLocalUrls
&& mostLocalUrls
!= urls
;
280 urls
.populateMimeData(mostLocalUrls
, data
);
282 urls
.populateMimeData(data
);
288 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
290 startFromIndex
= qMax(0, startFromIndex
);
291 for (int i
= startFromIndex
; i
< count(); ++i
) {
292 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
296 for (int i
= 0; i
< startFromIndex
; ++i
) {
297 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
304 bool KFileItemModel::supportsDropping(int index
) const
306 const KFileItem item
= fileItem(index
);
307 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
310 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
312 static QHash
<QByteArray
, QString
> description
;
313 if (description
.isEmpty()) {
315 const RoleInfoMap
* map
= rolesInfoMap(count
);
316 for (int i
= 0; i
< count
; ++i
) {
317 description
.insert(map
[i
].role
, i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
));
321 return description
.value(role
);
324 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
326 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
327 #ifdef KFILEITEMMODEL_DEBUG
331 switch (typeForRole(sortRole())) {
332 case NameRole
: m_groups
= nameRoleGroups(); break;
333 case SizeRole
: m_groups
= sizeRoleGroups(); break;
334 case DateRole
: m_groups
= dateRoleGroups(); break;
335 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
336 case RatingRole
: m_groups
= ratingRoleGroups(); break;
337 default: m_groups
= genericStringRoleGroups(sortRole()); break;
340 #ifdef KFILEITEMMODEL_DEBUG
341 kDebug() << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
348 KFileItem
KFileItemModel::fileItem(int index
) const
350 if (index
>= 0 && index
< count()) {
351 return m_itemData
.at(index
)->item
;
357 KFileItem
KFileItemModel::fileItem(const KUrl
& url
) const
359 const int indexForUrl
= index(url
);
360 if (indexForUrl
>= 0) {
361 return m_itemData
.at(indexForUrl
)->item
;
366 int KFileItemModel::index(const KFileItem
& item
) const
368 return index(KUrl(item
.url()));
371 int KFileItemModel::index(const KUrl
& url
) const
373 KUrl urlToFind
= url
;
374 urlToFind
.adjustPath(KUrl::RemoveTrailingSlash
);
376 const int itemCount
= m_itemData
.count();
377 int itemsInHash
= m_items
.count();
379 int index
= m_items
.value(urlToFind
, -1);
380 while (index
< 0 && itemsInHash
< itemCount
) {
381 // Not all URLs are stored yet in m_items. We grow m_items until either
382 // urlToFind is found, or all URLs have been stored in m_items.
383 // Note that we do not add the URLs to m_items one by one, but in
384 // larger blocks. After each block, we check if urlToFind is in
385 // m_items. We could in principle compare urlToFind with each URL while
386 // we are going through m_itemData, but comparing two QUrls will,
387 // unlike calling qHash for the URLs, trigger a parsing of the URLs
388 // which costs both CPU cycles and memory.
389 const int blockSize
= 1000;
390 const int currentBlockEnd
= qMin(itemsInHash
+ blockSize
, itemCount
);
391 for (int i
= itemsInHash
; i
< currentBlockEnd
; ++i
) {
392 const KUrl nextUrl
= m_itemData
.at(i
)->item
.url();
393 m_items
.insert(nextUrl
, i
);
396 itemsInHash
= currentBlockEnd
;
397 index
= m_items
.value(urlToFind
, -1);
400 Q_ASSERT(index
>= 0 || m_items
.count() == m_itemData
.count());
405 KFileItem
KFileItemModel::rootItem() const
407 return m_dirLister
->rootItem();
410 void KFileItemModel::clear()
415 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
417 if (m_roles
== roles
) {
423 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
424 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
425 if (supportedExpanding
&& !willSupportExpanding
) {
426 // No expanding is supported anymore. Take care to delete all items that have an expansion level
427 // that is not 0 (and hence are part of an expanded item).
428 removeExpandedItems();
435 QSetIterator
<QByteArray
> it(roles
);
436 while (it
.hasNext()) {
437 const QByteArray
& role
= it
.next();
438 m_requestRole
[typeForRole(role
)] = true;
442 // Update m_data with the changed requested roles
443 const int maxIndex
= count() - 1;
444 for (int i
= 0; i
<= maxIndex
; ++i
) {
445 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
, m_itemData
.at(i
)->parent
);
448 kWarning() << "TODO: Emitting itemsChanged() with no information what has changed!";
449 emit
itemsChanged(KItemRangeList() << KItemRange(0, count()), QSet
<QByteArray
>());
452 // Clear the 'values' of all filtered items. They will be re-populated with the
453 // correct roles the next time 'values' will be accessed via data(int).
454 QHash
<KFileItem
, ItemData
*>::iterator filteredIt
= m_filteredItems
.begin();
455 const QHash
<KFileItem
, ItemData
*>::iterator filteredEnd
= m_filteredItems
.end();
456 while (filteredIt
!= filteredEnd
) {
457 (*filteredIt
)->values
.clear();
462 QSet
<QByteArray
> KFileItemModel::roles() const
467 bool KFileItemModel::setExpanded(int index
, bool expanded
)
469 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
473 QHash
<QByteArray
, QVariant
> values
;
474 values
.insert(sharedValue("isExpanded"), expanded
);
475 if (!setData(index
, values
)) {
479 const KFileItem item
= m_itemData
.at(index
)->item
;
480 const KUrl url
= item
.url();
481 const KUrl targetUrl
= item
.targetUrl();
483 m_expandedDirs
.insert(targetUrl
, url
);
484 m_dirLister
->openUrl(url
, KDirLister::Keep
);
486 const KUrl::List previouslyExpandedChildren
= m_itemData
.at(index
)->values
.value("previouslyExpandedChildren").value
<KUrl::List
>();
487 foreach (const KUrl
& url
, previouslyExpandedChildren
) {
488 m_urlsToExpand
.insert(url
);
491 // Note that there might be (indirect) children of the folder which is to be collapsed in
492 // m_pendingItemsToInsert. To prevent that they will be inserted into the model later,
493 // possibly without a parent, which might result in a crash, we insert all pending items
494 // right now. All new items which would be without a parent will then be removed.
495 dispatchPendingItemsToInsert();
497 // Check if the index of the collapsed folder has changed. If that is the case, then items
498 // were inserted before the collapsed folder, and its index needs to be updated.
499 if (m_itemData
.at(index
)->item
!= item
) {
500 index
= this->index(item
);
503 m_expandedDirs
.remove(targetUrl
);
504 m_dirLister
->stop(url
);
506 const int parentLevel
= expandedParentsCount(index
);
507 const int itemCount
= m_itemData
.count();
508 const int firstChildIndex
= index
+ 1;
510 KUrl::List expandedChildren
;
512 int childIndex
= firstChildIndex
;
513 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
514 ItemData
* itemData
= m_itemData
.at(childIndex
);
515 if (itemData
->values
.value("isExpanded").toBool()) {
516 const KUrl targetUrl
= itemData
->item
.targetUrl();
517 const KUrl url
= itemData
->item
.url();
518 m_expandedDirs
.remove(targetUrl
);
519 m_dirLister
->stop(url
); // TODO: try to unit-test this, see https://bugs.kde.org/show_bug.cgi?id=332102#c11
520 expandedChildren
.append(targetUrl
);
524 const int childrenCount
= childIndex
- firstChildIndex
;
526 removeFilteredChildren(KItemRangeList() << KItemRange(index
, 1 + childrenCount
));
527 removeItems(KItemRangeList() << KItemRange(firstChildIndex
, childrenCount
), DeleteItemData
);
529 m_itemData
.at(index
)->values
.insert("previouslyExpandedChildren", expandedChildren
);
535 bool KFileItemModel::isExpanded(int index
) const
537 if (index
>= 0 && index
< count()) {
538 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
543 bool KFileItemModel::isExpandable(int index
) const
545 if (index
>= 0 && index
< count()) {
546 // Call data (instead of accessing m_itemData directly)
547 // to ensure that the value is initialized.
548 return data(index
).value("isExpandable").toBool();
553 int KFileItemModel::expandedParentsCount(int index
) const
555 if (index
>= 0 && index
< count()) {
556 return expandedParentsCount(m_itemData
.at(index
));
561 QSet
<KUrl
> KFileItemModel::expandedDirectories() const
563 return m_expandedDirs
.values().toSet();
566 void KFileItemModel::restoreExpandedDirectories(const QSet
<KUrl
>& urls
)
568 m_urlsToExpand
= urls
;
571 void KFileItemModel::expandParentDirectories(const KUrl
& url
)
573 const int pos
= m_dirLister
->url().path().length();
575 // Assure that each sub-path of the URL that should be
576 // expanded is added to m_urlsToExpand. KDirLister
577 // does not care whether the parent-URL has already been
579 KUrl urlToExpand
= m_dirLister
->url();
580 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator());
581 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
582 urlToExpand
.addPath(subDirs
.at(i
));
583 m_urlsToExpand
.insert(urlToExpand
);
586 // KDirLister::open() must called at least once to trigger an initial
587 // loading. The pending URLs that must be restored are handled
588 // in slotCompleted().
589 QSetIterator
<KUrl
> it2(m_urlsToExpand
);
590 while (it2
.hasNext()) {
591 const int idx
= index(it2
.next());
592 if (idx
>= 0 && !isExpanded(idx
)) {
593 setExpanded(idx
, true);
599 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
601 if (m_filter
.pattern() != nameFilter
) {
602 dispatchPendingItemsToInsert();
603 m_filter
.setPattern(nameFilter
);
608 QString
KFileItemModel::nameFilter() const
610 return m_filter
.pattern();
613 void KFileItemModel::setMimeTypeFilters(const QStringList
& filters
)
615 if (m_filter
.mimeTypes() != filters
) {
616 dispatchPendingItemsToInsert();
617 m_filter
.setMimeTypes(filters
);
622 QStringList
KFileItemModel::mimeTypeFilters() const
624 return m_filter
.mimeTypes();
628 void KFileItemModel::applyFilters()
630 // Check which shown items from m_itemData must get
631 // hidden and hence moved to m_filteredItems.
632 QVector
<int> newFilteredIndexes
;
634 const int itemCount
= m_itemData
.count();
635 for (int index
= 0; index
< itemCount
; ++index
) {
636 ItemData
* itemData
= m_itemData
.at(index
);
638 // Only filter non-expanded items as child items may never
639 // exist without a parent item
640 if (!itemData
->values
.value("isExpanded").toBool()) {
641 const KFileItem item
= itemData
->item
;
642 if (!m_filter
.matches(item
)) {
643 newFilteredIndexes
.append(index
);
644 m_filteredItems
.insert(item
, itemData
);
649 const KItemRangeList removedRanges
= KItemRangeList::fromSortedContainer(newFilteredIndexes
);
650 removeItems(removedRanges
, KeepItemData
);
652 // Check which hidden items from m_filteredItems should
653 // get visible again and hence removed from m_filteredItems.
654 QList
<ItemData
*> newVisibleItems
;
656 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
657 while (it
!= m_filteredItems
.end()) {
658 if (m_filter
.matches(it
.key())) {
659 newVisibleItems
.append(it
.value());
660 it
= m_filteredItems
.erase(it
);
666 insertItems(newVisibleItems
);
669 void KFileItemModel::removeFilteredChildren(const KItemRangeList
& itemRanges
)
671 if (m_filteredItems
.isEmpty() || !m_requestRole
[ExpandedParentsCountRole
]) {
672 // There are either no filtered items, or it is not possible to expand
673 // folders -> there cannot be any filtered children.
677 QSet
<ItemData
*> parents
;
678 foreach (const KItemRange
& range
, itemRanges
) {
679 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
680 parents
.insert(m_itemData
.at(index
));
684 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
685 while (it
!= m_filteredItems
.end()) {
686 if (parents
.contains(it
.value()->parent
)) {
688 it
= m_filteredItems
.erase(it
);
695 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
697 static QList
<RoleInfo
> rolesInfo
;
698 if (rolesInfo
.isEmpty()) {
700 const RoleInfoMap
* map
= rolesInfoMap(count
);
701 for (int i
= 0; i
< count
; ++i
) {
702 if (map
[i
].roleType
!= NoRole
) {
704 info
.role
= map
[i
].role
;
705 info
.translation
= i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
);
706 if (map
[i
].groupTranslation
) {
707 info
.group
= i18nc(map
[i
].groupTranslationContext
, map
[i
].groupTranslation
);
709 // For top level roles, groupTranslation is 0. We must make sure that
710 // info.group is an empty string then because the code that generates
711 // menus tries to put the actions into sub menus otherwise.
712 info
.group
= QString();
714 info
.requiresBaloo
= map
[i
].requiresBaloo
;
715 info
.requiresIndexer
= map
[i
].requiresIndexer
;
716 rolesInfo
.append(info
);
724 void KFileItemModel::onGroupedSortingChanged(bool current
)
730 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
733 m_sortRole
= typeForRole(current
);
735 if (!m_requestRole
[m_sortRole
]) {
736 QSet
<QByteArray
> newRoles
= m_roles
;
744 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
751 void KFileItemModel::resortAllItems()
753 m_resortAllItemsTimer
->stop();
755 const int itemCount
= count();
756 if (itemCount
<= 0) {
760 #ifdef KFILEITEMMODEL_DEBUG
763 kDebug() << "===========================================================";
764 kDebug() << "Resorting" << itemCount
<< "items";
767 // Remember the order of the current URLs so
768 // that it can be determined which indexes have
769 // been moved because of the resorting.
771 oldUrls
.reserve(itemCount
);
772 foreach (const ItemData
* itemData
, m_itemData
) {
773 oldUrls
.append(itemData
->item
.url());
777 m_items
.reserve(itemCount
);
780 sort(m_itemData
.begin(), m_itemData
.end());
781 for (int i
= 0; i
< itemCount
; ++i
) {
782 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
785 // Determine the first index that has been moved.
786 int firstMovedIndex
= 0;
787 while (firstMovedIndex
< itemCount
788 && firstMovedIndex
== m_items
.value(oldUrls
.at(firstMovedIndex
))) {
792 const bool itemsHaveMoved
= firstMovedIndex
< itemCount
;
793 if (itemsHaveMoved
) {
796 int lastMovedIndex
= itemCount
- 1;
797 while (lastMovedIndex
> firstMovedIndex
798 && lastMovedIndex
== m_items
.value(oldUrls
.at(lastMovedIndex
))) {
802 Q_ASSERT(firstMovedIndex
<= lastMovedIndex
);
804 // Create a list movedToIndexes, which has the property that
805 // movedToIndexes[i] is the new index of the item with the old index
806 // firstMovedIndex + i.
807 const int movedItemsCount
= lastMovedIndex
- firstMovedIndex
+ 1;
808 QList
<int> movedToIndexes
;
809 movedToIndexes
.reserve(movedItemsCount
);
810 for (int i
= firstMovedIndex
; i
<= lastMovedIndex
; ++i
) {
811 const int newIndex
= m_items
.value(oldUrls
.at(i
));
812 movedToIndexes
.append(newIndex
);
815 emit
itemsMoved(KItemRange(firstMovedIndex
, movedItemsCount
), movedToIndexes
);
816 } else if (groupedSorting()) {
817 // The groups might have changed even if the order of the items has not.
818 const QList
<QPair
<int, QVariant
> > oldGroups
= m_groups
;
820 if (groups() != oldGroups
) {
821 emit
groupsChanged();
825 #ifdef KFILEITEMMODEL_DEBUG
826 kDebug() << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
830 void KFileItemModel::slotCompleted()
832 dispatchPendingItemsToInsert();
834 if (!m_urlsToExpand
.isEmpty()) {
835 // Try to find a URL that can be expanded.
836 // Note that the parent folder must be expanded before any of its subfolders become visible.
837 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
838 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
839 foreach (const KUrl
& url
, m_urlsToExpand
) {
840 const int indexForUrl
= index(url
);
841 if (indexForUrl
>= 0) {
842 m_urlsToExpand
.remove(url
);
843 if (setExpanded(indexForUrl
, true)) {
844 // The dir lister has been triggered. This slot will be called
845 // again after the directory has been expanded.
851 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
852 // if these URLs have been deleted in the meantime.
853 m_urlsToExpand
.clear();
856 emit
directoryLoadingCompleted();
859 void KFileItemModel::slotCanceled()
861 m_maximumUpdateIntervalTimer
->stop();
862 dispatchPendingItemsToInsert();
864 emit
directoryLoadingCanceled();
867 void KFileItemModel::slotItemsAdded(const KUrl
& directoryUrl
, const KFileItemList
& items
)
869 Q_ASSERT(!items
.isEmpty());
872 if (m_expandedDirs
.contains(directoryUrl
)) {
873 parentUrl
= m_expandedDirs
.value(directoryUrl
);
875 parentUrl
= directoryUrl
;
876 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
879 if (m_requestRole
[ExpandedParentsCountRole
]) {
880 // If the expanding of items is enabled, the call
881 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
882 // might result in emitting the same items twice due to the Keep-parameter.
883 // This case happens if an item gets expanded, collapsed and expanded again
884 // before the items could be loaded for the first expansion.
885 if (index(KUrl(items
.first().url())) >= 0) {
886 // The items are already part of the model.
890 if (directoryUrl
!= directory()) {
891 // To be able to compare whether the new items may be inserted as children
892 // of a parent item the pending items must be added to the model first.
893 dispatchPendingItemsToInsert();
896 // KDirLister keeps the children of items that got expanded once even if
897 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
898 // checked whether the parent for new items is still expanded.
899 const int parentIndex
= index(parentUrl
);
900 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
901 // The parent is not expanded.
906 QList
<ItemData
*> itemDataList
= createItemDataList(parentUrl
, items
);
908 if (!m_filter
.hasSetFilters()) {
909 m_pendingItemsToInsert
.append(itemDataList
);
911 // The name or type filter is active. Hide filtered items
912 // before inserting them into the model and remember
913 // the filtered items in m_filteredItems.
914 foreach (ItemData
* itemData
, itemDataList
) {
915 if (m_filter
.matches(itemData
->item
)) {
916 m_pendingItemsToInsert
.append(itemData
);
918 m_filteredItems
.insert(itemData
->item
, itemData
);
923 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer
->isActive()) {
924 // Assure that items get dispatched if no completed() or canceled() signal is
925 // emitted during the maximum update interval.
926 m_maximumUpdateIntervalTimer
->start();
930 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
932 dispatchPendingItemsToInsert();
934 QVector
<int> indexesToRemove
;
935 indexesToRemove
.reserve(items
.count());
937 foreach (const KFileItem
& item
, items
) {
938 const int indexForItem
= index(item
);
939 if (indexForItem
>= 0) {
940 indexesToRemove
.append(indexForItem
);
942 // Probably the item has been filtered.
943 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(item
);
944 if (it
!= m_filteredItems
.end()) {
946 m_filteredItems
.erase(it
);
951 std::sort(indexesToRemove
.begin(), indexesToRemove
.end());
953 if (m_requestRole
[ExpandedParentsCountRole
] && !m_expandedDirs
.isEmpty()) {
954 // Assure that removing a parent item also results in removing all children
955 QVector
<int> indexesToRemoveWithChildren
;
956 indexesToRemoveWithChildren
.reserve(m_itemData
.count());
958 const int itemCount
= m_itemData
.count();
959 foreach (int index
, indexesToRemove
) {
960 indexesToRemoveWithChildren
.append(index
);
962 const int parentLevel
= expandedParentsCount(index
);
963 int childIndex
= index
+ 1;
964 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
965 indexesToRemoveWithChildren
.append(childIndex
);
970 indexesToRemove
= indexesToRemoveWithChildren
;
973 const KItemRangeList itemRanges
= KItemRangeList::fromSortedContainer(indexesToRemove
);
974 removeFilteredChildren(itemRanges
);
975 removeItems(itemRanges
, DeleteItemData
);
978 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
980 Q_ASSERT(!items
.isEmpty());
981 #ifdef KFILEITEMMODEL_DEBUG
982 kDebug() << "Refreshing" << items
.count() << "items";
985 // Get the indexes of all items that have been refreshed
987 indexes
.reserve(items
.count());
989 QSet
<QByteArray
> changedRoles
;
991 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
992 while (it
.hasNext()) {
993 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
994 const KFileItem
& oldItem
= itemPair
.first
;
995 const KFileItem
& newItem
= itemPair
.second
;
996 const int indexForItem
= index(oldItem
);
997 if (indexForItem
>= 0) {
998 m_itemData
[indexForItem
]->item
= newItem
;
1000 // Keep old values as long as possible if they could not retrieved synchronously yet.
1001 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
1002 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
, m_itemData
.at(indexForItem
)->parent
));
1003 QHash
<QByteArray
, QVariant
>& values
= m_itemData
[indexForItem
]->values
;
1004 while (it
.hasNext()) {
1006 const QByteArray
& role
= it
.key();
1007 if (values
.value(role
) != it
.value()) {
1008 values
.insert(role
, it
.value());
1009 changedRoles
.insert(role
);
1013 m_items
.remove(oldItem
.url());
1014 m_items
.insert(newItem
.url(), indexForItem
);
1015 indexes
.append(indexForItem
);
1017 // Check if 'oldItem' is one of the filtered items.
1018 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(oldItem
);
1019 if (it
!= m_filteredItems
.end()) {
1020 ItemData
* itemData
= it
.value();
1021 itemData
->item
= newItem
;
1023 // The data stored in 'values' might have changed. Therefore, we clear
1024 // 'values' and re-populate it the next time it is requested via data(int).
1025 itemData
->values
.clear();
1027 m_filteredItems
.erase(it
);
1028 m_filteredItems
.insert(newItem
, itemData
);
1033 // If the changed items have been created recently, they might not be in m_items yet.
1034 // In that case, the list 'indexes' might be empty.
1035 if (indexes
.isEmpty()) {
1039 // Extract the item-ranges out of the changed indexes
1041 const KItemRangeList itemRangeList
= KItemRangeList::fromSortedContainer(indexes
);
1042 emitItemsChangedAndTriggerResorting(itemRangeList
, changedRoles
);
1045 void KFileItemModel::slotClear()
1047 #ifdef KFILEITEMMODEL_DEBUG
1048 kDebug() << "Clearing all items";
1051 qDeleteAll(m_filteredItems
.values());
1052 m_filteredItems
.clear();
1055 m_maximumUpdateIntervalTimer
->stop();
1056 m_resortAllItemsTimer
->stop();
1058 qDeleteAll(m_pendingItemsToInsert
);
1059 m_pendingItemsToInsert
.clear();
1061 const int removedCount
= m_itemData
.count();
1062 if (removedCount
> 0) {
1063 qDeleteAll(m_itemData
);
1066 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
1069 m_expandedDirs
.clear();
1072 void KFileItemModel::slotNaturalSortingChanged()
1074 m_naturalSorting
= KGlobalSettings::naturalSorting();
1078 void KFileItemModel::dispatchPendingItemsToInsert()
1080 if (!m_pendingItemsToInsert
.isEmpty()) {
1081 insertItems(m_pendingItemsToInsert
);
1082 m_pendingItemsToInsert
.clear();
1086 void KFileItemModel::insertItems(QList
<ItemData
*>& newItems
)
1088 if (newItems
.isEmpty()) {
1092 #ifdef KFILEITEMMODEL_DEBUG
1093 QElapsedTimer timer
;
1095 kDebug() << "===========================================================";
1096 kDebug() << "Inserting" << newItems
.count() << "items";
1100 prepareItemsForSorting(newItems
);
1102 if (m_sortRole
== NameRole
&& m_naturalSorting
) {
1103 // Natural sorting of items can be very slow. However, it becomes much
1104 // faster if the input sequence is already mostly sorted. Therefore, we
1105 // first sort 'newItems' according to the QStrings returned by
1106 // KFileItem::text() using QString::operator<(), which is quite fast.
1107 parallelMergeSort(newItems
.begin(), newItems
.end(), nameLessThan
, QThread::idealThreadCount());
1110 sort(newItems
.begin(), newItems
.end());
1112 #ifdef KFILEITEMMODEL_DEBUG
1113 kDebug() << "[TIME] Sorting:" << timer
.elapsed();
1116 KItemRangeList itemRanges
;
1117 const int existingItemCount
= m_itemData
.count();
1118 const int newItemCount
= newItems
.count();
1119 const int totalItemCount
= existingItemCount
+ newItemCount
;
1121 if (existingItemCount
== 0) {
1122 // Optimization for the common special case that there are no
1123 // items in the model yet. Happens, e.g., when entering a folder.
1124 m_itemData
= newItems
;
1125 itemRanges
<< KItemRange(0, newItemCount
);
1127 m_itemData
.reserve(totalItemCount
);
1128 for (int i
= existingItemCount
; i
< totalItemCount
; ++i
) {
1129 m_itemData
.append(0);
1132 // We build the new list m_itemData in reverse order to minimize
1133 // the number of moves and guarantee O(N) complexity.
1134 int targetIndex
= totalItemCount
- 1;
1135 int sourceIndexExistingItems
= existingItemCount
- 1;
1136 int sourceIndexNewItems
= newItemCount
- 1;
1140 while (sourceIndexNewItems
>= 0) {
1141 ItemData
* newItem
= newItems
.at(sourceIndexNewItems
);
1142 if (sourceIndexExistingItems
>= 0 && lessThan(newItem
, m_itemData
.at(sourceIndexExistingItems
))) {
1143 // Move an existing item to its new position. If any new items
1144 // are behind it, push the item range to itemRanges.
1145 if (rangeCount
> 0) {
1146 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1150 m_itemData
[targetIndex
] = m_itemData
.at(sourceIndexExistingItems
);
1151 --sourceIndexExistingItems
;
1153 // Insert a new item into the list.
1155 m_itemData
[targetIndex
] = newItem
;
1156 --sourceIndexNewItems
;
1161 // Push the final item range to itemRanges.
1162 if (rangeCount
> 0) {
1163 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1166 // Note that itemRanges is still sorted in reverse order.
1167 std::reverse(itemRanges
.begin(), itemRanges
.end());
1170 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1171 // It will be re-populated with the updated indices if index(const KUrl&) is called.
1174 emit
itemsInserted(itemRanges
);
1176 #ifdef KFILEITEMMODEL_DEBUG
1177 kDebug() << "[TIME] Inserting of" << newItems
.count() << "items:" << timer
.elapsed();
1181 void KFileItemModel::removeItems(const KItemRangeList
& itemRanges
, RemoveItemsBehavior behavior
)
1183 if (itemRanges
.isEmpty()) {
1189 // Step 1: Remove the items from m_itemData, and free the ItemData.
1190 int removedItemsCount
= 0;
1191 foreach (const KItemRange
& range
, itemRanges
) {
1192 removedItemsCount
+= range
.count
;
1194 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
1195 if (behavior
== DeleteItemData
) {
1196 delete m_itemData
.at(index
);
1199 m_itemData
[index
] = 0;
1203 // Step 2: Remove the ItemData pointers from the list m_itemData.
1204 int target
= itemRanges
.at(0).index
;
1205 int source
= itemRanges
.at(0).index
+ itemRanges
.at(0).count
;
1208 const int oldItemDataCount
= m_itemData
.count();
1209 while (source
< oldItemDataCount
) {
1210 m_itemData
[target
] = m_itemData
[source
];
1214 if (nextRange
< itemRanges
.count() && source
== itemRanges
.at(nextRange
).index
) {
1215 // Skip the items in the next removed range.
1216 source
+= itemRanges
.at(nextRange
).count
;
1221 m_itemData
.erase(m_itemData
.end() - removedItemsCount
, m_itemData
.end());
1223 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1224 // It will be re-populated with the updated indices if index(const KUrl&) is called.
1227 emit
itemsRemoved(itemRanges
);
1230 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const KUrl
& parentUrl
, const KFileItemList
& items
) const
1232 if (m_sortRole
== TypeRole
) {
1233 // Try to resolve the MIME-types synchronously to prevent a reordering of
1234 // the items when sorting by type (per default MIME-types are resolved
1235 // asynchronously by KFileItemModelRolesUpdater).
1236 determineMimeTypes(items
, 200);
1239 const int parentIndex
= index(parentUrl
);
1240 ItemData
* parentItem
= parentIndex
< 0 ? 0 : m_itemData
.at(parentIndex
);
1242 QList
<ItemData
*> itemDataList
;
1243 itemDataList
.reserve(items
.count());
1245 foreach (const KFileItem
& item
, items
) {
1246 ItemData
* itemData
= new ItemData();
1247 itemData
->item
= item
;
1248 itemData
->parent
= parentItem
;
1249 itemDataList
.append(itemData
);
1252 return itemDataList
;
1255 void KFileItemModel::prepareItemsForSorting(QList
<ItemData
*>& itemDataList
)
1257 switch (m_sortRole
) {
1258 case PermissionsRole
:
1261 case DestinationRole
:
1263 // These roles can be determined with retrieveData, and they have to be stored
1264 // in the QHash "values" for the sorting.
1265 foreach (ItemData
* itemData
, itemDataList
) {
1266 if (itemData
->values
.isEmpty()) {
1267 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1273 // At least store the data including the file type for items with known MIME type.
1274 foreach (ItemData
* itemData
, itemDataList
) {
1275 if (itemData
->values
.isEmpty()) {
1276 const KFileItem item
= itemData
->item
;
1277 if (item
.isDir() || item
.isMimeTypeKnown()) {
1278 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1285 // The other roles are either resolved by KFileItemModelRolesUpdater
1286 // (this includes the SizeRole for directories), or they do not need
1287 // to be stored in the QHash "values" for sorting because the data can
1288 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1294 int KFileItemModel::expandedParentsCount(const ItemData
* data
)
1296 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1297 // if the corresponding item is expanded, and it is not a top-level item.
1298 const ItemData
* parent
= data
->parent
;
1300 if (parent
->parent
) {
1301 Q_ASSERT(parent
->values
.contains("expandedParentsCount"));
1302 return parent
->values
.value("expandedParentsCount").toInt() + 1;
1311 void KFileItemModel::removeExpandedItems()
1313 QVector
<int> indexesToRemove
;
1315 const int maxIndex
= m_itemData
.count() - 1;
1316 for (int i
= 0; i
<= maxIndex
; ++i
) {
1317 const ItemData
* itemData
= m_itemData
.at(i
);
1318 if (itemData
->parent
) {
1319 indexesToRemove
.append(i
);
1323 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove
), DeleteItemData
);
1324 m_expandedDirs
.clear();
1326 // Also remove all filtered items which have a parent.
1327 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
1328 const QHash
<KFileItem
, ItemData
*>::iterator end
= m_filteredItems
.end();
1331 if (it
.value()->parent
) {
1333 it
= m_filteredItems
.erase(it
);
1340 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList
& itemRanges
, const QSet
<QByteArray
>& changedRoles
)
1342 emit
itemsChanged(itemRanges
, changedRoles
);
1344 // Trigger a resorting if necessary. Note that this can happen even if the sort
1345 // role has not changed at all because the file name can be used as a fallback.
1346 if (changedRoles
.contains(sortRole()) || changedRoles
.contains(roleForType(NameRole
))) {
1347 foreach (const KItemRange
& range
, itemRanges
) {
1348 bool needsResorting
= false;
1350 const int first
= range
.index
;
1351 const int last
= range
.index
+ range
.count
- 1;
1353 // Resorting the model is necessary if
1354 // (a) The first item in the range is "lessThan" its predecessor,
1355 // (b) the successor of the last item is "lessThan" the last item, or
1356 // (c) the internal order of the items in the range is incorrect.
1358 && lessThan(m_itemData
.at(first
), m_itemData
.at(first
- 1))) {
1359 needsResorting
= true;
1360 } else if (last
< count() - 1
1361 && lessThan(m_itemData
.at(last
+ 1), m_itemData
.at(last
))) {
1362 needsResorting
= true;
1364 for (int index
= first
; index
< last
; ++index
) {
1365 if (lessThan(m_itemData
.at(index
+ 1), m_itemData
.at(index
))) {
1366 needsResorting
= true;
1372 if (needsResorting
) {
1373 m_resortAllItemsTimer
->start();
1379 if (groupedSorting() && changedRoles
.contains(sortRole())) {
1380 // The position is still correct, but the groups might have changed
1381 // if the changed item is either the first or the last item in a
1383 // In principle, we could try to find out if the item really is the
1384 // first or last one in its group and then update the groups
1385 // (possibly with a delayed timer to make sure that we don't
1386 // re-calculate the groups very often if items are updated one by
1387 // one), but starting m_resortAllItemsTimer is easier.
1388 m_resortAllItemsTimer
->start();
1392 void KFileItemModel::resetRoles()
1394 for (int i
= 0; i
< RolesCount
; ++i
) {
1395 m_requestRole
[i
] = false;
1399 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1401 static QHash
<QByteArray
, RoleType
> roles
;
1402 if (roles
.isEmpty()) {
1403 // Insert user visible roles that can be accessed with
1404 // KFileItemModel::roleInformation()
1406 const RoleInfoMap
* map
= rolesInfoMap(count
);
1407 for (int i
= 0; i
< count
; ++i
) {
1408 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1411 // Insert internal roles (take care to synchronize the implementation
1412 // with KFileItemModel::roleForType() in case if a change is done).
1413 roles
.insert("isDir", IsDirRole
);
1414 roles
.insert("isLink", IsLinkRole
);
1415 roles
.insert("isExpanded", IsExpandedRole
);
1416 roles
.insert("isExpandable", IsExpandableRole
);
1417 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1419 Q_ASSERT(roles
.count() == RolesCount
);
1422 return roles
.value(role
, NoRole
);
1425 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1427 static QHash
<RoleType
, QByteArray
> roles
;
1428 if (roles
.isEmpty()) {
1429 // Insert user visible roles that can be accessed with
1430 // KFileItemModel::roleInformation()
1432 const RoleInfoMap
* map
= rolesInfoMap(count
);
1433 for (int i
= 0; i
< count
; ++i
) {
1434 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1437 // Insert internal roles (take care to synchronize the implementation
1438 // with KFileItemModel::typeForRole() in case if a change is done).
1439 roles
.insert(IsDirRole
, "isDir");
1440 roles
.insert(IsLinkRole
, "isLink");
1441 roles
.insert(IsExpandedRole
, "isExpanded");
1442 roles
.insert(IsExpandableRole
, "isExpandable");
1443 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1445 Q_ASSERT(roles
.count() == RolesCount
);
1448 return roles
.value(roleType
);
1451 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
, const ItemData
* parent
) const
1453 // It is important to insert only roles that are fast to retrieve. E.g.
1454 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1455 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1456 QHash
<QByteArray
, QVariant
> data
;
1457 data
.insert(sharedValue("url"), item
.url());
1459 const bool isDir
= item
.isDir();
1460 if (m_requestRole
[IsDirRole
] && isDir
) {
1461 data
.insert(sharedValue("isDir"), true);
1464 if (m_requestRole
[IsLinkRole
] && item
.isLink()) {
1465 data
.insert(sharedValue("isLink"), true);
1468 if (m_requestRole
[NameRole
]) {
1469 data
.insert(sharedValue("text"), item
.text());
1472 if (m_requestRole
[SizeRole
] && !isDir
) {
1473 data
.insert(sharedValue("size"), item
.size());
1476 if (m_requestRole
[DateRole
]) {
1477 // Don't use KFileItem::timeString() as this is too expensive when
1478 // having several thousands of items. Instead the formatting of the
1479 // date-time will be done on-demand by the view when the date will be shown.
1480 const QDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
1481 data
.insert(sharedValue("date"), dateTime
);
1484 if (m_requestRole
[PermissionsRole
]) {
1485 data
.insert(sharedValue("permissions"), item
.permissionsString());
1488 if (m_requestRole
[OwnerRole
]) {
1489 data
.insert(sharedValue("owner"), item
.user());
1492 if (m_requestRole
[GroupRole
]) {
1493 data
.insert(sharedValue("group"), item
.group());
1496 if (m_requestRole
[DestinationRole
]) {
1497 QString destination
= item
.linkDest();
1498 if (destination
.isEmpty()) {
1499 destination
= QLatin1String("-");
1501 data
.insert(sharedValue("destination"), destination
);
1504 if (m_requestRole
[PathRole
]) {
1506 if (item
.url().scheme() == QLatin1String("trash")) {
1507 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1509 // For performance reasons cache the home-path in a static QString
1510 // (see QDir::homePath() for more details)
1511 static QString homePath
;
1512 if (homePath
.isEmpty()) {
1513 homePath
= QDir::homePath();
1516 path
= item
.localPath();
1517 if (path
.startsWith(homePath
)) {
1518 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1522 const int index
= path
.lastIndexOf(item
.text());
1523 path
= path
.mid(0, index
- 1);
1524 data
.insert(sharedValue("path"), path
);
1527 if (m_requestRole
[IsExpandableRole
] && isDir
) {
1528 data
.insert(sharedValue("isExpandable"), true);
1531 if (m_requestRole
[ExpandedParentsCountRole
]) {
1533 const int level
= expandedParentsCount(parent
) + 1;
1534 data
.insert(sharedValue("expandedParentsCount"), level
);
1538 if (item
.isMimeTypeKnown()) {
1539 data
.insert(sharedValue("iconName"), item
.iconName());
1541 if (m_requestRole
[TypeRole
]) {
1542 data
.insert(sharedValue("type"), item
.mimeComment());
1544 } else if (m_requestRole
[TypeRole
] && isDir
) {
1545 static const QString folderMimeType
= item
.mimeComment();
1546 data
.insert(sharedValue("type"), folderMimeType
);
1552 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
) const
1556 if (a
->parent
!= b
->parent
) {
1557 const int expansionLevelA
= expandedParentsCount(a
);
1558 const int expansionLevelB
= expandedParentsCount(b
);
1560 // If b has a higher expansion level than a, check if a is a parent
1561 // of b, and make sure that both expansion levels are equal otherwise.
1562 for (int i
= expansionLevelB
; i
> expansionLevelA
; --i
) {
1563 if (b
->parent
== a
) {
1569 // If a has a higher expansion level than a, check if b is a parent
1570 // of a, and make sure that both expansion levels are equal otherwise.
1571 for (int i
= expansionLevelA
; i
> expansionLevelB
; --i
) {
1572 if (a
->parent
== b
) {
1578 Q_ASSERT(expandedParentsCount(a
) == expandedParentsCount(b
));
1580 // Compare the last parents of a and b which are different.
1581 while (a
->parent
!= b
->parent
) {
1587 if (m_sortDirsFirst
|| m_sortRole
== SizeRole
) {
1588 const bool isDirA
= a
->item
.isDir();
1589 const bool isDirB
= b
->item
.isDir();
1590 if (isDirA
&& !isDirB
) {
1592 } else if (!isDirA
&& isDirB
) {
1597 result
= sortRoleCompare(a
, b
);
1599 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1603 * Helper class for KFileItemModel::sort().
1605 class KFileItemModelLessThan
1608 KFileItemModelLessThan(const KFileItemModel
* model
) :
1613 bool operator()(const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
) const
1615 return m_model
->lessThan(a
, b
);
1619 const KFileItemModel
* m_model
;
1622 void KFileItemModel::sort(QList
<KFileItemModel::ItemData
*>::iterator begin
,
1623 QList
<KFileItemModel::ItemData
*>::iterator end
) const
1625 KFileItemModelLessThan
lessThan(this);
1627 if (m_sortRole
== NameRole
) {
1628 // Sorting by name can be expensive, in particular if natural sorting is
1629 // enabled. Use all CPU cores to speed up the sorting process.
1630 static const int numberOfThreads
= QThread::idealThreadCount();
1631 parallelMergeSort(begin
, end
, lessThan
, numberOfThreads
);
1633 // Sorting by other roles is quite fast. Use only one thread to prevent
1634 // problems caused by non-reentrant comparison functions, see
1635 // https://bugs.kde.org/show_bug.cgi?id=312679
1636 mergeSort(begin
, end
, lessThan
);
1640 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
) const
1642 const KFileItem
& itemA
= a
->item
;
1643 const KFileItem
& itemB
= b
->item
;
1647 switch (m_sortRole
) {
1649 // The name role is handled as default fallback after the switch
1653 if (itemA
.isDir()) {
1654 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1655 Q_ASSERT(itemB
.isDir());
1657 const QVariant valueA
= a
->values
.value("size");
1658 const QVariant valueB
= b
->values
.value("size");
1659 if (valueA
.isNull() && valueB
.isNull()) {
1661 } else if (valueA
.isNull()) {
1663 } else if (valueB
.isNull()) {
1666 result
= valueA
.toInt() - valueB
.toInt();
1669 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1670 Q_ASSERT(!itemB
.isDir());
1671 const KIO::filesize_t sizeA
= itemA
.size();
1672 const KIO::filesize_t sizeB
= itemB
.size();
1673 if (sizeA
> sizeB
) {
1675 } else if (sizeA
< sizeB
) {
1685 const QDateTime dateTimeA
= itemA
.time(KFileItem::ModificationTime
);
1686 const QDateTime dateTimeB
= itemB
.time(KFileItem::ModificationTime
);
1687 if (dateTimeA
< dateTimeB
) {
1689 } else if (dateTimeA
> dateTimeB
) {
1696 result
= a
->values
.value("rating").toInt() - b
->values
.value("rating").toInt();
1700 case ImageSizeRole
: {
1701 // Alway use a natural comparing to interpret the numbers of a string like
1702 // "1600 x 1200" for having a correct sorting.
1703 result
= KStringHandler::naturalCompare(a
->values
.value("imageSize").toString(),
1704 b
->values
.value("imageSize").toString(),
1710 const QByteArray role
= roleForType(m_sortRole
);
1711 result
= QString::compare(a
->values
.value(role
).toString(),
1712 b
->values
.value(role
).toString());
1719 // The current sort role was sufficient to define an order
1723 // Fallback #1: Compare the text of the items
1724 result
= stringCompare(itemA
.text(), itemB
.text());
1729 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1730 result
= stringCompare(itemA
.name(m_caseSensitivity
== Qt::CaseInsensitive
),
1731 itemB
.name(m_caseSensitivity
== Qt::CaseInsensitive
));
1736 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1737 // equal. In this case a comparison of the URL is done which is unique in all cases
1738 // within KDirLister.
1739 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1742 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
) const
1744 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1745 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1746 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1747 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1749 if (m_caseSensitivity
== Qt::CaseInsensitive
) {
1750 const int result
= m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseInsensitive
)
1751 : QString::compare(a
, b
, Qt::CaseInsensitive
);
1753 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1754 // comparison, still a deterministic sort order is required. A case sensitive
1755 // comparison is done as fallback.
1760 return m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseSensitive
)
1761 : QString::compare(a
, b
, Qt::CaseSensitive
);
1764 bool KFileItemModel::useMaximumUpdateInterval() const
1766 return !m_dirLister
->url().isLocalFile();
1769 static bool localeAwareLessThan(const QChar
& c1
, const QChar
& c2
)
1771 return QString::localeAwareCompare(c1
, c2
) < 0;
1774 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1776 Q_ASSERT(!m_itemData
.isEmpty());
1778 const int maxIndex
= count() - 1;
1779 QList
<QPair
<int, QVariant
> > groups
;
1783 for (int i
= 0; i
<= maxIndex
; ++i
) {
1784 if (isChildItem(i
)) {
1788 const QString name
= m_itemData
.at(i
)->item
.text();
1790 // Use the first character of the name as group indication
1791 QChar newFirstChar
= name
.at(0).toUpper();
1792 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1793 newFirstChar
= name
.at(1).toUpper();
1796 if (firstChar
!= newFirstChar
) {
1797 QString newGroupValue
;
1798 if (newFirstChar
.isLetter()) {
1799 // Try to find a matching group in the range 'A' to 'Z'.
1800 static std::vector
<QChar
> lettersAtoZ
;
1801 if (lettersAtoZ
.empty()) {
1802 for (char c
= 'A'; c
<= 'Z'; ++c
) {
1803 lettersAtoZ
.push_back(QLatin1Char(c
));
1807 std::vector
<QChar
>::iterator it
= std::lower_bound(lettersAtoZ
.begin(), lettersAtoZ
.end(), newFirstChar
, localeAwareLessThan
);
1808 if (it
!= lettersAtoZ
.end()) {
1809 if (localeAwareLessThan(newFirstChar
, *it
) && it
!= lettersAtoZ
.begin()) {
1810 // newFirstChar belongs to the group preceding *it.
1811 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
1814 newGroupValue
= *it
;
1816 newGroupValue
= newFirstChar
;
1818 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
1819 // Apply group '0 - 9' for any name that starts with a digit
1820 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
1822 newGroupValue
= i18nc("@title:group", "Others");
1825 if (newGroupValue
!= groupValue
) {
1826 groupValue
= newGroupValue
;
1827 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1830 firstChar
= newFirstChar
;
1836 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
1838 Q_ASSERT(!m_itemData
.isEmpty());
1840 const int maxIndex
= count() - 1;
1841 QList
<QPair
<int, QVariant
> > groups
;
1844 for (int i
= 0; i
<= maxIndex
; ++i
) {
1845 if (isChildItem(i
)) {
1849 const KFileItem
& item
= m_itemData
.at(i
)->item
;
1850 const KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
1851 QString newGroupValue
;
1852 if (!item
.isNull() && item
.isDir()) {
1853 newGroupValue
= i18nc("@title:group Size", "Folders");
1854 } else if (fileSize
< 5 * 1024 * 1024) {
1855 newGroupValue
= i18nc("@title:group Size", "Small");
1856 } else if (fileSize
< 10 * 1024 * 1024) {
1857 newGroupValue
= i18nc("@title:group Size", "Medium");
1859 newGroupValue
= i18nc("@title:group Size", "Big");
1862 if (newGroupValue
!= groupValue
) {
1863 groupValue
= newGroupValue
;
1864 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1871 QList
<QPair
<int, QVariant
> > KFileItemModel::dateRoleGroups() const
1873 Q_ASSERT(!m_itemData
.isEmpty());
1875 const int maxIndex
= count() - 1;
1876 QList
<QPair
<int, QVariant
> > groups
;
1878 const QDate currentDate
= QDate::currentDate();
1880 QDate previousModifiedDate
;
1882 for (int i
= 0; i
<= maxIndex
; ++i
) {
1883 if (isChildItem(i
)) {
1887 const QDateTime modifiedTime
= m_itemData
.at(i
)->item
.time(KFileItem::ModificationTime
);
1888 const QDate modifiedDate
= modifiedTime
.date();
1889 if (modifiedDate
== previousModifiedDate
) {
1890 // The current item is in the same group as the previous item
1893 previousModifiedDate
= modifiedDate
;
1895 const int daysDistance
= modifiedDate
.daysTo(currentDate
);
1897 QString newGroupValue
;
1898 if (currentDate
.year() == modifiedDate
.year() && currentDate
.month() == modifiedDate
.month()) {
1899 switch (daysDistance
/ 7) {
1901 switch (daysDistance
) {
1902 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
1903 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
1904 default: newGroupValue
= modifiedTime
.toString(i18nc("@title:group The week day name: %A", "%A"));
1908 newGroupValue
= i18nc("@title:group Date", "One Week Ago");
1911 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
1914 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
1918 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
1924 const QDate lastMonthDate
= currentDate
.addMonths(-1);
1925 if (lastMonthDate
.year() == modifiedDate
.year() && lastMonthDate
.month() == modifiedDate
.month()) {
1926 if (daysDistance
== 1) {
1927 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Yesterday (%B, %Y)"));
1928 } else if (daysDistance
<= 7) {
1929 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)"));
1930 } else if (daysDistance
<= 7 * 2) {
1931 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)"));
1932 } else if (daysDistance
<= 7 * 3) {
1933 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)"));
1934 } else if (daysDistance
<= 7 * 4) {
1935 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)"));
1937 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"));
1940 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"));
1944 if (newGroupValue
!= groupValue
) {
1945 groupValue
= newGroupValue
;
1946 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1953 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
1955 Q_ASSERT(!m_itemData
.isEmpty());
1957 const int maxIndex
= count() - 1;
1958 QList
<QPair
<int, QVariant
> > groups
;
1960 QString permissionsString
;
1962 for (int i
= 0; i
<= maxIndex
; ++i
) {
1963 if (isChildItem(i
)) {
1967 const ItemData
* itemData
= m_itemData
.at(i
);
1968 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
1969 if (newPermissionsString
== permissionsString
) {
1972 permissionsString
= newPermissionsString
;
1974 const QFileInfo
info(itemData
->item
.url().toLocalFile());
1978 if (info
.permission(QFile::ReadUser
)) {
1979 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1981 if (info
.permission(QFile::WriteUser
)) {
1982 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1984 if (info
.permission(QFile::ExeUser
)) {
1985 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1987 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
1991 if (info
.permission(QFile::ReadGroup
)) {
1992 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1994 if (info
.permission(QFile::WriteGroup
)) {
1995 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1997 if (info
.permission(QFile::ExeGroup
)) {
1998 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2000 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
2002 // Set others string
2004 if (info
.permission(QFile::ReadOther
)) {
2005 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2007 if (info
.permission(QFile::WriteOther
)) {
2008 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2010 if (info
.permission(QFile::ExeOther
)) {
2011 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2013 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
2015 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
2016 if (newGroupValue
!= groupValue
) {
2017 groupValue
= newGroupValue
;
2018 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2025 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
2027 Q_ASSERT(!m_itemData
.isEmpty());
2029 const int maxIndex
= count() - 1;
2030 QList
<QPair
<int, QVariant
> > groups
;
2032 int groupValue
= -1;
2033 for (int i
= 0; i
<= maxIndex
; ++i
) {
2034 if (isChildItem(i
)) {
2037 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
2038 if (newGroupValue
!= groupValue
) {
2039 groupValue
= newGroupValue
;
2040 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2047 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
2049 Q_ASSERT(!m_itemData
.isEmpty());
2051 const int maxIndex
= count() - 1;
2052 QList
<QPair
<int, QVariant
> > groups
;
2054 bool isFirstGroupValue
= true;
2056 for (int i
= 0; i
<= maxIndex
; ++i
) {
2057 if (isChildItem(i
)) {
2060 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
2061 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
2062 groupValue
= newGroupValue
;
2063 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2064 isFirstGroupValue
= false;
2071 void KFileItemModel::emitSortProgress(int resolvedCount
)
2073 // Be tolerant against a resolvedCount with a wrong range.
2074 // Although there should not be a case where KFileItemModelRolesUpdater
2075 // (= caller) provides a wrong range, it is important to emit
2076 // a useful progress information even if there is an unexpected
2077 // implementation issue.
2079 const int itemCount
= count();
2080 if (resolvedCount
>= itemCount
) {
2081 m_sortingProgressPercent
= -1;
2082 if (m_resortAllItemsTimer
->isActive()) {
2083 m_resortAllItemsTimer
->stop();
2087 emit
directorySortingProgress(100);
2088 } else if (itemCount
> 0) {
2089 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
2091 const int progress
= resolvedCount
* 100 / itemCount
;
2092 if (m_sortingProgressPercent
!= progress
) {
2093 m_sortingProgressPercent
= progress
;
2094 emit
directorySortingProgress(progress
);
2099 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
2101 static const RoleInfoMap rolesInfoMap
[] = {
2102 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
2103 { 0, NoRole
, 0, 0, 0, 0, false, false },
2104 { "text", NameRole
, I18N_NOOP2_NOSTRIP("@label", "Name"), 0, 0, false, false },
2105 { "size", SizeRole
, I18N_NOOP2_NOSTRIP("@label", "Size"), 0, 0, false, false },
2106 { "date", DateRole
, I18N_NOOP2_NOSTRIP("@label", "Date"), 0, 0, false, false },
2107 { "type", TypeRole
, I18N_NOOP2_NOSTRIP("@label", "Type"), 0, 0, false, false },
2108 { "rating", RatingRole
, I18N_NOOP2_NOSTRIP("@label", "Rating"), 0, 0, true, false },
2109 { "tags", TagsRole
, I18N_NOOP2_NOSTRIP("@label", "Tags"), 0, 0, true, false },
2110 { "comment", CommentRole
, I18N_NOOP2_NOSTRIP("@label", "Comment"), 0, 0, true, false },
2111 { "wordCount", WordCountRole
, I18N_NOOP2_NOSTRIP("@label", "Word Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
2112 { "lineCount", LineCountRole
, I18N_NOOP2_NOSTRIP("@label", "Line Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
2113 { "imageSize", ImageSizeRole
, I18N_NOOP2_NOSTRIP("@label", "Image Size"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
2114 { "orientation", OrientationRole
, I18N_NOOP2_NOSTRIP("@label", "Orientation"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
2115 { "artist", ArtistRole
, I18N_NOOP2_NOSTRIP("@label", "Artist"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
2116 { "album", AlbumRole
, I18N_NOOP2_NOSTRIP("@label", "Album"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
2117 { "duration", DurationRole
, I18N_NOOP2_NOSTRIP("@label", "Duration"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
2118 { "track", TrackRole
, I18N_NOOP2_NOSTRIP("@label", "Track"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
2119 { "path", PathRole
, I18N_NOOP2_NOSTRIP("@label", "Path"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2120 { "destination", DestinationRole
, I18N_NOOP2_NOSTRIP("@label", "Link Destination"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2121 { "copiedFrom", CopiedFromRole
, I18N_NOOP2_NOSTRIP("@label", "Copied From"), I18N_NOOP2_NOSTRIP("@label", "Other"), true, false },
2122 { "permissions", PermissionsRole
, I18N_NOOP2_NOSTRIP("@label", "Permissions"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2123 { "owner", OwnerRole
, I18N_NOOP2_NOSTRIP("@label", "Owner"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2124 { "group", GroupRole
, I18N_NOOP2_NOSTRIP("@label", "User Group"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2127 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
2128 return rolesInfoMap
;
2131 void KFileItemModel::determineMimeTypes(const KFileItemList
& items
, int timeout
)
2133 QElapsedTimer timer
;
2135 foreach (const KFileItem
& item
, items
) { // krazy:exclude=foreach
2136 // Only determine mime types for files here. For directories,
2137 // KFileItem::determineMimeType() reads the .directory file inside to
2138 // load the icon, but this is not necessary at all if we just need the
2139 // type. Some special code for setting the correct mime type for
2140 // directories is in retrieveData().
2141 if (!item
.isDir()) {
2142 item
.determineMimeType();
2145 if (timer
.elapsed() > timeout
) {
2146 // Don't block the user interface, let the remaining items
2147 // be resolved asynchronously.
2153 QByteArray
KFileItemModel::sharedValue(const QByteArray
& value
)
2155 static QSet
<QByteArray
> pool
;
2156 const QSet
<QByteArray
>::const_iterator it
= pool
.constFind(value
);
2158 if (it
!= pool
.constEnd()) {
2166 bool KFileItemModel::isConsistent() const
2168 // m_items may contain less items than m_itemData because m_items
2169 // is populated lazily, see KFileItemModel::index(const KUrl& url).
2170 if (m_items
.count() > m_itemData
.count()) {
2174 for (int i
= 0; i
< count(); ++i
) {
2175 // Check if m_items and m_itemData are consistent.
2176 const KFileItem item
= fileItem(i
);
2177 if (item
.isNull()) {
2178 qWarning() << "Item" << i
<< "is null";
2182 const int itemIndex
= index(item
);
2183 if (itemIndex
!= i
) {
2184 qWarning() << "Item" << i
<< "has a wrong index:" << itemIndex
;
2188 // Check if the items are sorted correctly.
2189 if (i
> 0 && !lessThan(m_itemData
.at(i
- 1), m_itemData
.at(i
))) {
2190 qWarning() << "The order of items" << i
- 1 << "and" << i
<< "is wrong:"
2191 << fileItem(i
- 1) << fileItem(i
);
2195 // Check if all parent-child relationships are consistent.
2196 const ItemData
* data
= m_itemData
.at(i
);
2197 const ItemData
* parent
= data
->parent
;
2199 if (expandedParentsCount(data
) != expandedParentsCount(parent
) + 1) {
2200 qWarning() << "expandedParentsCount is inconsistent for parent" << parent
->item
<< "and child" << data
->item
;
2204 const int parentIndex
= index(parent
->item
);
2205 if (parentIndex
>= i
) {
2206 qWarning() << "Index" << parentIndex
<< "of parent" << parent
->item
<< "is not smaller than index" << i
<< "of child" << data
->item
;
2215 #include "kfileitemmodel.moc"