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 "dolphin_generalsettings.h"
26 #include <KLocalizedString>
27 #include <KUrlMimeData>
29 #include "dolphindebug.h"
31 #include "private/kfileitemmodelsortalgorithm.h"
32 #include "private/kfileitemmodeldirlister.h"
34 #include <QElapsedTimer>
39 // #define KFILEITEMMODEL_DEBUG
41 KFileItemModel::KFileItemModel(QObject
* parent
) :
42 KItemModelBase("text", parent
),
44 m_sortDirsFirst(true),
46 m_sortingProgressPercent(-1),
53 m_maximumUpdateIntervalTimer(nullptr),
54 m_resortAllItemsTimer(nullptr),
55 m_pendingItemsToInsert(),
60 m_collator
.setNumericMode(true);
62 loadSortingSettings();
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
, &KFileItemModelDirLister::percent
, this, &KFileItemModel::directoryLoadingProgress
);
82 connect(m_dirLister
, static_cast<void(KFileItemModelDirLister::*)(const QUrl
&, const QUrl
&)>(&KFileItemModelDirLister::redirection
), this, &KFileItemModel::directoryRedirection
);
83 connect(m_dirLister
, &KFileItemModelDirLister::urlIsFileError
, this, &KFileItemModel::urlIsFileError
);
85 // Apply default roles that should be determined
87 m_requestRole
[NameRole
] = true;
88 m_requestRole
[IsDirRole
] = true;
89 m_requestRole
[IsLinkRole
] = true;
90 m_roles
.insert("text");
91 m_roles
.insert("isDir");
92 m_roles
.insert("isLink");
93 m_roles
.insert("isHidden");
95 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
96 // before the completed() or canceled() signal has been emitted.
97 m_maximumUpdateIntervalTimer
= new QTimer(this);
98 m_maximumUpdateIntervalTimer
->setInterval(2000);
99 m_maximumUpdateIntervalTimer
->setSingleShot(true);
100 connect(m_maximumUpdateIntervalTimer
, &QTimer::timeout
, this, &KFileItemModel::dispatchPendingItemsToInsert
);
102 // When changing the value of an item which represents the sort-role a resorting must be
103 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
104 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
105 // resorting is postponed until the timer has been exceeded.
106 m_resortAllItemsTimer
= new QTimer(this);
107 m_resortAllItemsTimer
->setInterval(500);
108 m_resortAllItemsTimer
->setSingleShot(true);
109 connect(m_resortAllItemsTimer
, &QTimer::timeout
, this, &KFileItemModel::resortAllItems
);
111 connect(GeneralSettings::self(), &GeneralSettings::sortingChoiceChanged
, this, &KFileItemModel::slotSortingChoiceChanged
);
114 KFileItemModel::~KFileItemModel()
116 qDeleteAll(m_itemData
);
117 qDeleteAll(m_filteredItems
);
118 qDeleteAll(m_pendingItemsToInsert
);
121 void KFileItemModel::loadDirectory(const QUrl
&url
)
123 m_dirLister
->openUrl(url
);
126 void KFileItemModel::refreshDirectory(const QUrl
&url
)
128 // Refresh all expanded directories first (Bug 295300)
129 QHashIterator
<QUrl
, QUrl
> expandedDirs(m_expandedDirs
);
130 while (expandedDirs
.hasNext()) {
132 m_dirLister
->openUrl(expandedDirs
.value(), KDirLister::Reload
);
135 m_dirLister
->openUrl(url
, KDirLister::Reload
);
138 QUrl
KFileItemModel::directory() const
140 return m_dirLister
->url();
143 void KFileItemModel::cancelDirectoryLoading()
148 int KFileItemModel::count() const
150 return m_itemData
.count();
153 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
155 if (index
>= 0 && index
< count()) {
156 ItemData
* data
= m_itemData
.at(index
);
157 if (data
->values
.isEmpty()) {
158 data
->values
= retrieveData(data
->item
, data
->parent
);
163 return QHash
<QByteArray
, QVariant
>();
166 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
168 if (index
< 0 || index
>= count()) {
172 QHash
<QByteArray
, QVariant
> currentValues
= data(index
);
174 // Determine which roles have been changed
175 QSet
<QByteArray
> changedRoles
;
176 QHashIterator
<QByteArray
, QVariant
> it(values
);
177 while (it
.hasNext()) {
179 const QByteArray role
= sharedValue(it
.key());
180 const QVariant value
= it
.value();
182 if (currentValues
[role
] != value
) {
183 currentValues
[role
] = value
;
184 changedRoles
.insert(role
);
188 if (changedRoles
.isEmpty()) {
192 m_itemData
[index
]->values
= currentValues
;
193 if (changedRoles
.contains("text")) {
194 QUrl url
= m_itemData
[index
]->item
.url();
195 url
= url
.adjusted(QUrl::RemoveFilename
);
196 url
.setPath(url
.path() + currentValues
["text"].toString());
197 m_itemData
[index
]->item
.setUrl(url
);
200 emitItemsChangedAndTriggerResorting(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
205 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
207 if (dirsFirst
!= m_sortDirsFirst
) {
208 m_sortDirsFirst
= dirsFirst
;
213 bool KFileItemModel::sortDirectoriesFirst() const
215 return m_sortDirsFirst
;
218 void KFileItemModel::setShowHiddenFiles(bool show
)
220 m_dirLister
->setShowingDotFiles(show
);
221 m_dirLister
->emitChanges();
223 dispatchPendingItemsToInsert();
227 bool KFileItemModel::showHiddenFiles() const
229 return m_dirLister
->showingDotFiles();
232 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
234 m_dirLister
->setDirOnlyMode(enabled
);
237 bool KFileItemModel::showDirectoriesOnly() const
239 return m_dirLister
->dirOnlyMode();
242 QMimeData
* KFileItemModel::createMimeData(const KItemSet
& indexes
) const
244 QMimeData
* data
= new QMimeData();
246 // The following code has been taken from KDirModel::mimeData()
247 // (kdelibs/kio/kio/kdirmodel.cpp)
248 // Copyright (C) 2006 David Faure <faure@kde.org>
250 QList
<QUrl
> mostLocalUrls
;
251 const ItemData
* lastAddedItem
= nullptr;
253 for (int index
: indexes
) {
254 const ItemData
* itemData
= m_itemData
.at(index
);
255 const ItemData
* parent
= itemData
->parent
;
257 while (parent
&& parent
!= lastAddedItem
) {
258 parent
= parent
->parent
;
261 if (parent
&& parent
== lastAddedItem
) {
262 // A parent of 'itemData' has been added already.
266 lastAddedItem
= itemData
;
267 const KFileItem
& item
= itemData
->item
;
268 if (!item
.isNull()) {
272 mostLocalUrls
<< item
.mostLocalUrl(isLocal
);
276 KUrlMimeData::setUrls(urls
, mostLocalUrls
, data
);
280 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
282 startFromIndex
= qMax(0, startFromIndex
);
283 for (int i
= startFromIndex
; i
< count(); ++i
) {
284 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
288 for (int i
= 0; i
< startFromIndex
; ++i
) {
289 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
296 bool KFileItemModel::supportsDropping(int index
) const
298 const KFileItem item
= fileItem(index
);
299 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
302 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
304 static QHash
<QByteArray
, QString
> description
;
305 if (description
.isEmpty()) {
307 const RoleInfoMap
* map
= rolesInfoMap(count
);
308 for (int i
= 0; i
< count
; ++i
) {
309 description
.insert(map
[i
].role
, i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
));
313 return description
.value(role
);
316 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
318 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
319 #ifdef KFILEITEMMODEL_DEBUG
323 switch (typeForRole(sortRole())) {
324 case NameRole
: m_groups
= nameRoleGroups(); break;
325 case SizeRole
: m_groups
= sizeRoleGroups(); break;
326 case ModificationTimeRole
:
327 m_groups
= timeRoleGroups([](const ItemData
*item
) {
328 return item
->item
.time(KFileItem::ModificationTime
);
331 case CreationTimeRole
:
332 m_groups
= timeRoleGroups([](const ItemData
*item
) {
333 return item
->item
.time(KFileItem::CreationTime
);
337 m_groups
= timeRoleGroups([](const ItemData
*item
) {
338 return item
->item
.time(KFileItem::AccessTime
);
341 case DeletionTimeRole
:
342 m_groups
= timeRoleGroups([](const ItemData
*item
) {
343 return item
->values
.value("deletiontime").toDateTime();
346 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
347 case RatingRole
: m_groups
= ratingRoleGroups(); break;
348 default: m_groups
= genericStringRoleGroups(sortRole()); break;
351 #ifdef KFILEITEMMODEL_DEBUG
352 qCDebug(DolphinDebug
) << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
359 KFileItem
KFileItemModel::fileItem(int index
) const
361 if (index
>= 0 && index
< count()) {
362 return m_itemData
.at(index
)->item
;
368 KFileItem
KFileItemModel::fileItem(const QUrl
&url
) const
370 const int indexForUrl
= index(url
);
371 if (indexForUrl
>= 0) {
372 return m_itemData
.at(indexForUrl
)->item
;
377 int KFileItemModel::index(const KFileItem
& item
) const
379 return index(item
.url());
382 int KFileItemModel::index(const QUrl
& url
) const
384 const QUrl urlToFind
= url
.adjusted(QUrl::StripTrailingSlash
);
386 const int itemCount
= m_itemData
.count();
387 int itemsInHash
= m_items
.count();
389 int index
= m_items
.value(urlToFind
, -1);
390 while (index
< 0 && itemsInHash
< itemCount
) {
391 // Not all URLs are stored yet in m_items. We grow m_items until either
392 // urlToFind is found, or all URLs have been stored in m_items.
393 // Note that we do not add the URLs to m_items one by one, but in
394 // larger blocks. After each block, we check if urlToFind is in
395 // m_items. We could in principle compare urlToFind with each URL while
396 // we are going through m_itemData, but comparing two QUrls will,
397 // unlike calling qHash for the URLs, trigger a parsing of the URLs
398 // which costs both CPU cycles and memory.
399 const int blockSize
= 1000;
400 const int currentBlockEnd
= qMin(itemsInHash
+ blockSize
, itemCount
);
401 for (int i
= itemsInHash
; i
< currentBlockEnd
; ++i
) {
402 const QUrl nextUrl
= m_itemData
.at(i
)->item
.url();
403 m_items
.insert(nextUrl
, i
);
406 itemsInHash
= currentBlockEnd
;
407 index
= m_items
.value(urlToFind
, -1);
411 // The item could not be found, even though all items from m_itemData
412 // should be in m_items now. We print some diagnostic information which
413 // might help to find the cause of the problem, but only once. This
414 // prevents that obtaining and printing the debugging information
415 // wastes CPU cycles and floods the shell or .xsession-errors.
416 static bool printDebugInfo
= true;
418 if (m_items
.count() != m_itemData
.count() && printDebugInfo
) {
419 printDebugInfo
= false;
421 qCWarning(DolphinDebug
) << "The model is in an inconsistent state.";
422 qCWarning(DolphinDebug
) << "m_items.count() ==" << m_items
.count();
423 qCWarning(DolphinDebug
) << "m_itemData.count() ==" << m_itemData
.count();
425 // Check if there are multiple items with the same URL.
426 QMultiHash
<QUrl
, int> indexesForUrl
;
427 for (int i
= 0; i
< m_itemData
.count(); ++i
) {
428 indexesForUrl
.insert(m_itemData
.at(i
)->item
.url(), i
);
431 foreach (const QUrl
& url
, indexesForUrl
.uniqueKeys()) {
432 if (indexesForUrl
.count(url
) > 1) {
433 qCWarning(DolphinDebug
) << "Multiple items found with the URL" << url
;
435 auto it
= indexesForUrl
.find(url
);
436 while (it
!= indexesForUrl
.end() && it
.key() == url
) {
437 const ItemData
* data
= m_itemData
.at(it
.value());
438 qCWarning(DolphinDebug
) << "index" << it
.value() << ":" << data
->item
;
440 qCWarning(DolphinDebug
) << "parent" << data
->parent
->item
;
452 KFileItem
KFileItemModel::rootItem() const
454 return m_dirLister
->rootItem();
457 void KFileItemModel::clear()
462 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
464 if (m_roles
== roles
) {
468 const QSet
<QByteArray
> changedRoles
= (roles
- m_roles
) + (m_roles
- roles
);
472 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
473 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
474 if (supportedExpanding
&& !willSupportExpanding
) {
475 // No expanding is supported anymore. Take care to delete all items that have an expansion level
476 // that is not 0 (and hence are part of an expanded item).
477 removeExpandedItems();
484 QSetIterator
<QByteArray
> it(roles
);
485 while (it
.hasNext()) {
486 const QByteArray
& role
= it
.next();
487 m_requestRole
[typeForRole(role
)] = true;
491 // Update m_data with the changed requested roles
492 const int maxIndex
= count() - 1;
493 for (int i
= 0; i
<= maxIndex
; ++i
) {
494 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
, m_itemData
.at(i
)->parent
);
497 emit
itemsChanged(KItemRangeList() << KItemRange(0, count()), changedRoles
);
500 // Clear the 'values' of all filtered items. They will be re-populated with the
501 // correct roles the next time 'values' will be accessed via data(int).
502 QHash
<KFileItem
, ItemData
*>::iterator filteredIt
= m_filteredItems
.begin();
503 const QHash
<KFileItem
, ItemData
*>::iterator filteredEnd
= m_filteredItems
.end();
504 while (filteredIt
!= filteredEnd
) {
505 (*filteredIt
)->values
.clear();
510 QSet
<QByteArray
> KFileItemModel::roles() const
515 bool KFileItemModel::setExpanded(int index
, bool expanded
)
517 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
521 QHash
<QByteArray
, QVariant
> values
;
522 values
.insert(sharedValue("isExpanded"), expanded
);
523 if (!setData(index
, values
)) {
527 const KFileItem item
= m_itemData
.at(index
)->item
;
528 const QUrl url
= item
.url();
529 const QUrl targetUrl
= item
.targetUrl();
531 m_expandedDirs
.insert(targetUrl
, url
);
532 m_dirLister
->openUrl(url
, KDirLister::Keep
);
534 const QVariantList previouslyExpandedChildren
= m_itemData
.at(index
)->values
.value("previouslyExpandedChildren").value
<QVariantList
>();
535 foreach (const QVariant
& var
, previouslyExpandedChildren
) {
536 m_urlsToExpand
.insert(var
.toUrl());
539 // Note that there might be (indirect) children of the folder which is to be collapsed in
540 // m_pendingItemsToInsert. To prevent that they will be inserted into the model later,
541 // possibly without a parent, which might result in a crash, we insert all pending items
542 // right now. All new items which would be without a parent will then be removed.
543 dispatchPendingItemsToInsert();
545 // Check if the index of the collapsed folder has changed. If that is the case, then items
546 // were inserted before the collapsed folder, and its index needs to be updated.
547 if (m_itemData
.at(index
)->item
!= item
) {
548 index
= this->index(item
);
551 m_expandedDirs
.remove(targetUrl
);
552 m_dirLister
->stop(url
);
554 const int parentLevel
= expandedParentsCount(index
);
555 const int itemCount
= m_itemData
.count();
556 const int firstChildIndex
= index
+ 1;
558 QVariantList expandedChildren
;
560 int childIndex
= firstChildIndex
;
561 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
562 ItemData
* itemData
= m_itemData
.at(childIndex
);
563 if (itemData
->values
.value("isExpanded").toBool()) {
564 const QUrl targetUrl
= itemData
->item
.targetUrl();
565 const QUrl url
= itemData
->item
.url();
566 m_expandedDirs
.remove(targetUrl
);
567 m_dirLister
->stop(url
); // TODO: try to unit-test this, see https://bugs.kde.org/show_bug.cgi?id=332102#c11
568 expandedChildren
.append(targetUrl
);
572 const int childrenCount
= childIndex
- firstChildIndex
;
574 removeFilteredChildren(KItemRangeList() << KItemRange(index
, 1 + childrenCount
));
575 removeItems(KItemRangeList() << KItemRange(firstChildIndex
, childrenCount
), DeleteItemData
);
577 m_itemData
.at(index
)->values
.insert("previouslyExpandedChildren", expandedChildren
);
583 bool KFileItemModel::isExpanded(int index
) const
585 if (index
>= 0 && index
< count()) {
586 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
591 bool KFileItemModel::isExpandable(int index
) const
593 if (index
>= 0 && index
< count()) {
594 // Call data (instead of accessing m_itemData directly)
595 // to ensure that the value is initialized.
596 return data(index
).value("isExpandable").toBool();
601 int KFileItemModel::expandedParentsCount(int index
) const
603 if (index
>= 0 && index
< count()) {
604 return expandedParentsCount(m_itemData
.at(index
));
609 QSet
<QUrl
> KFileItemModel::expandedDirectories() const
612 const auto dirs
= m_expandedDirs
;
613 for (const auto &dir
: dirs
) {
619 void KFileItemModel::restoreExpandedDirectories(const QSet
<QUrl
> &urls
)
621 m_urlsToExpand
= urls
;
624 void KFileItemModel::expandParentDirectories(const QUrl
&url
)
627 // Assure that each sub-path of the URL that should be
628 // expanded is added to m_urlsToExpand. KDirLister
629 // does not care whether the parent-URL has already been
631 QUrl urlToExpand
= m_dirLister
->url();
632 const int pos
= urlToExpand
.path().length();
634 // first subdir can be empty, if m_dirLister->url().path() does not end with '/'
635 // this happens if baseUrl is not root but a home directory, see FoldersPanel,
636 // so using QString::SkipEmptyParts
637 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator(), QString::SkipEmptyParts
);
638 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
639 QString path
= urlToExpand
.path();
640 if (!path
.endsWith(QLatin1Char('/'))) {
641 path
.append(QLatin1Char('/'));
643 urlToExpand
.setPath(path
+ subDirs
.at(i
));
644 m_urlsToExpand
.insert(urlToExpand
);
647 // KDirLister::open() must called at least once to trigger an initial
648 // loading. The pending URLs that must be restored are handled
649 // in slotCompleted().
650 QSetIterator
<QUrl
> it2(m_urlsToExpand
);
651 while (it2
.hasNext()) {
652 const int idx
= index(it2
.next());
653 if (idx
>= 0 && !isExpanded(idx
)) {
654 setExpanded(idx
, true);
660 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
662 if (m_filter
.pattern() != nameFilter
) {
663 dispatchPendingItemsToInsert();
664 m_filter
.setPattern(nameFilter
);
669 QString
KFileItemModel::nameFilter() const
671 return m_filter
.pattern();
674 void KFileItemModel::setMimeTypeFilters(const QStringList
& filters
)
676 if (m_filter
.mimeTypes() != filters
) {
677 dispatchPendingItemsToInsert();
678 m_filter
.setMimeTypes(filters
);
683 QStringList
KFileItemModel::mimeTypeFilters() const
685 return m_filter
.mimeTypes();
689 void KFileItemModel::applyFilters()
691 // Check which shown items from m_itemData must get
692 // hidden and hence moved to m_filteredItems.
693 QVector
<int> newFilteredIndexes
;
695 const int itemCount
= m_itemData
.count();
696 for (int index
= 0; index
< itemCount
; ++index
) {
697 ItemData
* itemData
= m_itemData
.at(index
);
699 // Only filter non-expanded items as child items may never
700 // exist without a parent item
701 if (!itemData
->values
.value("isExpanded").toBool()) {
702 const KFileItem item
= itemData
->item
;
703 if (!m_filter
.matches(item
)) {
704 newFilteredIndexes
.append(index
);
705 m_filteredItems
.insert(item
, itemData
);
710 const KItemRangeList removedRanges
= KItemRangeList::fromSortedContainer(newFilteredIndexes
);
711 removeItems(removedRanges
, KeepItemData
);
713 // Check which hidden items from m_filteredItems should
714 // get visible again and hence removed from m_filteredItems.
715 QList
<ItemData
*> newVisibleItems
;
717 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
718 while (it
!= m_filteredItems
.end()) {
719 if (m_filter
.matches(it
.key())) {
720 newVisibleItems
.append(it
.value());
721 it
= m_filteredItems
.erase(it
);
727 insertItems(newVisibleItems
);
730 void KFileItemModel::removeFilteredChildren(const KItemRangeList
& itemRanges
)
732 if (m_filteredItems
.isEmpty() || !m_requestRole
[ExpandedParentsCountRole
]) {
733 // There are either no filtered items, or it is not possible to expand
734 // folders -> there cannot be any filtered children.
738 QSet
<ItemData
*> parents
;
739 foreach (const KItemRange
& range
, itemRanges
) {
740 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
741 parents
.insert(m_itemData
.at(index
));
745 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
746 while (it
!= m_filteredItems
.end()) {
747 if (parents
.contains(it
.value()->parent
)) {
749 it
= m_filteredItems
.erase(it
);
756 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
758 static QList
<RoleInfo
> rolesInfo
;
759 if (rolesInfo
.isEmpty()) {
761 const RoleInfoMap
* map
= rolesInfoMap(count
);
762 for (int i
= 0; i
< count
; ++i
) {
763 if (map
[i
].roleType
!= NoRole
) {
765 info
.role
= map
[i
].role
;
766 info
.translation
= i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
);
767 if (map
[i
].groupTranslation
) {
768 info
.group
= i18nc(map
[i
].groupTranslationContext
, map
[i
].groupTranslation
);
770 // For top level roles, groupTranslation is 0. We must make sure that
771 // info.group is an empty string then because the code that generates
772 // menus tries to put the actions into sub menus otherwise.
773 info
.group
= QString();
775 info
.requiresBaloo
= map
[i
].requiresBaloo
;
776 info
.requiresIndexer
= map
[i
].requiresIndexer
;
777 rolesInfo
.append(info
);
785 void KFileItemModel::onGroupedSortingChanged(bool current
)
791 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
794 m_sortRole
= typeForRole(current
);
796 if (!m_requestRole
[m_sortRole
]) {
797 QSet
<QByteArray
> newRoles
= m_roles
;
805 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
812 void KFileItemModel::loadSortingSettings()
814 using Choice
= GeneralSettings::EnumSortingChoice
;
815 switch (GeneralSettings::sortingChoice()) {
816 case Choice::NaturalSorting
:
817 m_naturalSorting
= true;
818 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
820 case Choice::CaseSensitiveSorting
:
821 m_naturalSorting
= false;
822 m_collator
.setCaseSensitivity(Qt::CaseSensitive
);
824 case Choice::CaseInsensitiveSorting
:
825 m_naturalSorting
= false;
826 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
833 void KFileItemModel::resortAllItems()
835 m_resortAllItemsTimer
->stop();
837 const int itemCount
= count();
838 if (itemCount
<= 0) {
842 #ifdef KFILEITEMMODEL_DEBUG
845 qCDebug(DolphinDebug
) << "===========================================================";
846 qCDebug(DolphinDebug
) << "Resorting" << itemCount
<< "items";
849 // Remember the order of the current URLs so
850 // that it can be determined which indexes have
851 // been moved because of the resorting.
853 oldUrls
.reserve(itemCount
);
854 foreach (const ItemData
* itemData
, m_itemData
) {
855 oldUrls
.append(itemData
->item
.url());
859 m_items
.reserve(itemCount
);
862 sort(m_itemData
.begin(), m_itemData
.end());
863 for (int i
= 0; i
< itemCount
; ++i
) {
864 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
867 // Determine the first index that has been moved.
868 int firstMovedIndex
= 0;
869 while (firstMovedIndex
< itemCount
870 && firstMovedIndex
== m_items
.value(oldUrls
.at(firstMovedIndex
))) {
874 const bool itemsHaveMoved
= firstMovedIndex
< itemCount
;
875 if (itemsHaveMoved
) {
878 int lastMovedIndex
= itemCount
- 1;
879 while (lastMovedIndex
> firstMovedIndex
880 && lastMovedIndex
== m_items
.value(oldUrls
.at(lastMovedIndex
))) {
884 Q_ASSERT(firstMovedIndex
<= lastMovedIndex
);
886 // Create a list movedToIndexes, which has the property that
887 // movedToIndexes[i] is the new index of the item with the old index
888 // firstMovedIndex + i.
889 const int movedItemsCount
= lastMovedIndex
- firstMovedIndex
+ 1;
890 QList
<int> movedToIndexes
;
891 movedToIndexes
.reserve(movedItemsCount
);
892 for (int i
= firstMovedIndex
; i
<= lastMovedIndex
; ++i
) {
893 const int newIndex
= m_items
.value(oldUrls
.at(i
));
894 movedToIndexes
.append(newIndex
);
897 emit
itemsMoved(KItemRange(firstMovedIndex
, movedItemsCount
), movedToIndexes
);
898 } else if (groupedSorting()) {
899 // The groups might have changed even if the order of the items has not.
900 const QList
<QPair
<int, QVariant
> > oldGroups
= m_groups
;
902 if (groups() != oldGroups
) {
903 emit
groupsChanged();
907 #ifdef KFILEITEMMODEL_DEBUG
908 qCDebug(DolphinDebug
) << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
912 void KFileItemModel::slotCompleted()
914 dispatchPendingItemsToInsert();
916 if (!m_urlsToExpand
.isEmpty()) {
917 // Try to find a URL that can be expanded.
918 // Note that the parent folder must be expanded before any of its subfolders become visible.
919 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
920 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
921 foreach (const QUrl
& url
, m_urlsToExpand
) {
922 const int indexForUrl
= index(url
);
923 if (indexForUrl
>= 0) {
924 m_urlsToExpand
.remove(url
);
925 if (setExpanded(indexForUrl
, true)) {
926 // The dir lister has been triggered. This slot will be called
927 // again after the directory has been expanded.
933 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
934 // if these URLs have been deleted in the meantime.
935 m_urlsToExpand
.clear();
938 emit
directoryLoadingCompleted();
941 void KFileItemModel::slotCanceled()
943 m_maximumUpdateIntervalTimer
->stop();
944 dispatchPendingItemsToInsert();
946 emit
directoryLoadingCanceled();
949 void KFileItemModel::slotItemsAdded(const QUrl
&directoryUrl
, const KFileItemList
& items
)
951 Q_ASSERT(!items
.isEmpty());
954 if (m_expandedDirs
.contains(directoryUrl
)) {
955 parentUrl
= m_expandedDirs
.value(directoryUrl
);
957 parentUrl
= directoryUrl
.adjusted(QUrl::StripTrailingSlash
);
960 if (m_requestRole
[ExpandedParentsCountRole
]) {
961 // If the expanding of items is enabled, the call
962 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
963 // might result in emitting the same items twice due to the Keep-parameter.
964 // This case happens if an item gets expanded, collapsed and expanded again
965 // before the items could be loaded for the first expansion.
966 if (index(items
.first().url()) >= 0) {
967 // The items are already part of the model.
971 if (directoryUrl
!= directory()) {
972 // To be able to compare whether the new items may be inserted as children
973 // of a parent item the pending items must be added to the model first.
974 dispatchPendingItemsToInsert();
977 // KDirLister keeps the children of items that got expanded once even if
978 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
979 // checked whether the parent for new items is still expanded.
980 const int parentIndex
= index(parentUrl
);
981 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
982 // The parent is not expanded.
987 QList
<ItemData
*> itemDataList
= createItemDataList(parentUrl
, items
);
989 if (!m_filter
.hasSetFilters()) {
990 m_pendingItemsToInsert
.append(itemDataList
);
992 // The name or type filter is active. Hide filtered items
993 // before inserting them into the model and remember
994 // the filtered items in m_filteredItems.
995 foreach (ItemData
* itemData
, itemDataList
) {
996 if (m_filter
.matches(itemData
->item
)) {
997 m_pendingItemsToInsert
.append(itemData
);
999 m_filteredItems
.insert(itemData
->item
, itemData
);
1004 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer
->isActive()) {
1005 // Assure that items get dispatched if no completed() or canceled() signal is
1006 // emitted during the maximum update interval.
1007 m_maximumUpdateIntervalTimer
->start();
1011 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
1013 dispatchPendingItemsToInsert();
1015 QVector
<int> indexesToRemove
;
1016 indexesToRemove
.reserve(items
.count());
1018 foreach (const KFileItem
& item
, items
) {
1019 const int indexForItem
= index(item
);
1020 if (indexForItem
>= 0) {
1021 indexesToRemove
.append(indexForItem
);
1023 // Probably the item has been filtered.
1024 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(item
);
1025 if (it
!= m_filteredItems
.end()) {
1027 m_filteredItems
.erase(it
);
1032 std::sort(indexesToRemove
.begin(), indexesToRemove
.end());
1034 if (m_requestRole
[ExpandedParentsCountRole
] && !m_expandedDirs
.isEmpty()) {
1035 // Assure that removing a parent item also results in removing all children
1036 QVector
<int> indexesToRemoveWithChildren
;
1037 indexesToRemoveWithChildren
.reserve(m_itemData
.count());
1039 const int itemCount
= m_itemData
.count();
1040 foreach (int index
, indexesToRemove
) {
1041 indexesToRemoveWithChildren
.append(index
);
1043 const int parentLevel
= expandedParentsCount(index
);
1044 int childIndex
= index
+ 1;
1045 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
1046 indexesToRemoveWithChildren
.append(childIndex
);
1051 indexesToRemove
= indexesToRemoveWithChildren
;
1054 const KItemRangeList itemRanges
= KItemRangeList::fromSortedContainer(indexesToRemove
);
1055 removeFilteredChildren(itemRanges
);
1056 removeItems(itemRanges
, DeleteItemData
);
1059 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
1061 Q_ASSERT(!items
.isEmpty());
1062 #ifdef KFILEITEMMODEL_DEBUG
1063 qCDebug(DolphinDebug
) << "Refreshing" << items
.count() << "items";
1066 // Get the indexes of all items that have been refreshed
1068 indexes
.reserve(items
.count());
1070 QSet
<QByteArray
> changedRoles
;
1072 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
1073 while (it
.hasNext()) {
1074 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
1075 const KFileItem
& oldItem
= itemPair
.first
;
1076 const KFileItem
& newItem
= itemPair
.second
;
1077 const int indexForItem
= index(oldItem
);
1078 if (indexForItem
>= 0) {
1079 m_itemData
[indexForItem
]->item
= newItem
;
1081 // Keep old values as long as possible if they could not retrieved synchronously yet.
1082 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
1083 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
, m_itemData
.at(indexForItem
)->parent
));
1084 QHash
<QByteArray
, QVariant
>& values
= m_itemData
[indexForItem
]->values
;
1085 while (it
.hasNext()) {
1087 const QByteArray
& role
= it
.key();
1088 if (values
.value(role
) != it
.value()) {
1089 values
.insert(role
, it
.value());
1090 changedRoles
.insert(role
);
1094 m_items
.remove(oldItem
.url());
1095 m_items
.insert(newItem
.url(), indexForItem
);
1096 indexes
.append(indexForItem
);
1098 // Check if 'oldItem' is one of the filtered items.
1099 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(oldItem
);
1100 if (it
!= m_filteredItems
.end()) {
1101 ItemData
* itemData
= it
.value();
1102 itemData
->item
= newItem
;
1104 // The data stored in 'values' might have changed. Therefore, we clear
1105 // 'values' and re-populate it the next time it is requested via data(int).
1106 itemData
->values
.clear();
1108 m_filteredItems
.erase(it
);
1109 m_filteredItems
.insert(newItem
, itemData
);
1114 // If the changed items have been created recently, they might not be in m_items yet.
1115 // In that case, the list 'indexes' might be empty.
1116 if (indexes
.isEmpty()) {
1120 // Extract the item-ranges out of the changed indexes
1122 const KItemRangeList itemRangeList
= KItemRangeList::fromSortedContainer(indexes
);
1123 emitItemsChangedAndTriggerResorting(itemRangeList
, changedRoles
);
1126 void KFileItemModel::slotClear()
1128 #ifdef KFILEITEMMODEL_DEBUG
1129 qCDebug(DolphinDebug
) << "Clearing all items";
1132 qDeleteAll(m_filteredItems
);
1133 m_filteredItems
.clear();
1136 m_maximumUpdateIntervalTimer
->stop();
1137 m_resortAllItemsTimer
->stop();
1139 qDeleteAll(m_pendingItemsToInsert
);
1140 m_pendingItemsToInsert
.clear();
1142 const int removedCount
= m_itemData
.count();
1143 if (removedCount
> 0) {
1144 qDeleteAll(m_itemData
);
1147 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
1150 m_expandedDirs
.clear();
1153 void KFileItemModel::slotSortingChoiceChanged()
1155 loadSortingSettings();
1159 void KFileItemModel::dispatchPendingItemsToInsert()
1161 if (!m_pendingItemsToInsert
.isEmpty()) {
1162 insertItems(m_pendingItemsToInsert
);
1163 m_pendingItemsToInsert
.clear();
1167 void KFileItemModel::insertItems(QList
<ItemData
*>& newItems
)
1169 if (newItems
.isEmpty()) {
1173 #ifdef KFILEITEMMODEL_DEBUG
1174 QElapsedTimer timer
;
1176 qCDebug(DolphinDebug
) << "===========================================================";
1177 qCDebug(DolphinDebug
) << "Inserting" << newItems
.count() << "items";
1181 prepareItemsForSorting(newItems
);
1183 if (m_sortRole
== NameRole
&& m_naturalSorting
) {
1184 // Natural sorting of items can be very slow. However, it becomes much
1185 // faster if the input sequence is already mostly sorted. Therefore, we
1186 // first sort 'newItems' according to the QStrings returned by
1187 // KFileItem::text() using QString::operator<(), which is quite fast.
1188 parallelMergeSort(newItems
.begin(), newItems
.end(), nameLessThan
, QThread::idealThreadCount());
1191 sort(newItems
.begin(), newItems
.end());
1193 #ifdef KFILEITEMMODEL_DEBUG
1194 qCDebug(DolphinDebug
) << "[TIME] Sorting:" << timer
.elapsed();
1197 KItemRangeList itemRanges
;
1198 const int existingItemCount
= m_itemData
.count();
1199 const int newItemCount
= newItems
.count();
1200 const int totalItemCount
= existingItemCount
+ newItemCount
;
1202 if (existingItemCount
== 0) {
1203 // Optimization for the common special case that there are no
1204 // items in the model yet. Happens, e.g., when entering a folder.
1205 m_itemData
= newItems
;
1206 itemRanges
<< KItemRange(0, newItemCount
);
1208 m_itemData
.reserve(totalItemCount
);
1209 for (int i
= existingItemCount
; i
< totalItemCount
; ++i
) {
1210 m_itemData
.append(0);
1213 // We build the new list m_itemData in reverse order to minimize
1214 // the number of moves and guarantee O(N) complexity.
1215 int targetIndex
= totalItemCount
- 1;
1216 int sourceIndexExistingItems
= existingItemCount
- 1;
1217 int sourceIndexNewItems
= newItemCount
- 1;
1221 while (sourceIndexNewItems
>= 0) {
1222 ItemData
* newItem
= newItems
.at(sourceIndexNewItems
);
1223 if (sourceIndexExistingItems
>= 0 && lessThan(newItem
, m_itemData
.at(sourceIndexExistingItems
), m_collator
)) {
1224 // Move an existing item to its new position. If any new items
1225 // are behind it, push the item range to itemRanges.
1226 if (rangeCount
> 0) {
1227 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1231 m_itemData
[targetIndex
] = m_itemData
.at(sourceIndexExistingItems
);
1232 --sourceIndexExistingItems
;
1234 // Insert a new item into the list.
1236 m_itemData
[targetIndex
] = newItem
;
1237 --sourceIndexNewItems
;
1242 // Push the final item range to itemRanges.
1243 if (rangeCount
> 0) {
1244 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1247 // Note that itemRanges is still sorted in reverse order.
1248 std::reverse(itemRanges
.begin(), itemRanges
.end());
1251 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1252 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1255 emit
itemsInserted(itemRanges
);
1257 #ifdef KFILEITEMMODEL_DEBUG
1258 qCDebug(DolphinDebug
) << "[TIME] Inserting of" << newItems
.count() << "items:" << timer
.elapsed();
1262 void KFileItemModel::removeItems(const KItemRangeList
& itemRanges
, RemoveItemsBehavior behavior
)
1264 if (itemRanges
.isEmpty()) {
1270 // Step 1: Remove the items from m_itemData, and free the ItemData.
1271 int removedItemsCount
= 0;
1272 foreach (const KItemRange
& range
, itemRanges
) {
1273 removedItemsCount
+= range
.count
;
1275 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
1276 if (behavior
== DeleteItemData
) {
1277 delete m_itemData
.at(index
);
1280 m_itemData
[index
] = 0;
1284 // Step 2: Remove the ItemData pointers from the list m_itemData.
1285 int target
= itemRanges
.at(0).index
;
1286 int source
= itemRanges
.at(0).index
+ itemRanges
.at(0).count
;
1289 const int oldItemDataCount
= m_itemData
.count();
1290 while (source
< oldItemDataCount
) {
1291 m_itemData
[target
] = m_itemData
[source
];
1295 if (nextRange
< itemRanges
.count() && source
== itemRanges
.at(nextRange
).index
) {
1296 // Skip the items in the next removed range.
1297 source
+= itemRanges
.at(nextRange
).count
;
1302 m_itemData
.erase(m_itemData
.end() - removedItemsCount
, m_itemData
.end());
1304 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1305 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1308 emit
itemsRemoved(itemRanges
);
1311 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const QUrl
& parentUrl
, const KFileItemList
& items
) const
1313 if (m_sortRole
== TypeRole
) {
1314 // Try to resolve the MIME-types synchronously to prevent a reordering of
1315 // the items when sorting by type (per default MIME-types are resolved
1316 // asynchronously by KFileItemModelRolesUpdater).
1317 determineMimeTypes(items
, 200);
1320 const int parentIndex
= index(parentUrl
);
1321 ItemData
* parentItem
= parentIndex
< 0 ? 0 : m_itemData
.at(parentIndex
);
1323 QList
<ItemData
*> itemDataList
;
1324 itemDataList
.reserve(items
.count());
1326 foreach (const KFileItem
& item
, items
) {
1327 ItemData
* itemData
= new ItemData();
1328 itemData
->item
= item
;
1329 itemData
->parent
= parentItem
;
1330 itemDataList
.append(itemData
);
1333 return itemDataList
;
1336 void KFileItemModel::prepareItemsForSorting(QList
<ItemData
*>& itemDataList
)
1338 switch (m_sortRole
) {
1339 case PermissionsRole
:
1342 case DestinationRole
:
1344 case DeletionTimeRole
:
1345 // These roles can be determined with retrieveData, and they have to be stored
1346 // in the QHash "values" for the sorting.
1347 foreach (ItemData
* itemData
, itemDataList
) {
1348 if (itemData
->values
.isEmpty()) {
1349 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1355 // At least store the data including the file type for items with known MIME type.
1356 foreach (ItemData
* itemData
, itemDataList
) {
1357 if (itemData
->values
.isEmpty()) {
1358 const KFileItem item
= itemData
->item
;
1359 if (item
.isDir() || item
.isMimeTypeKnown()) {
1360 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1367 // The other roles are either resolved by KFileItemModelRolesUpdater
1368 // (this includes the SizeRole for directories), or they do not need
1369 // to be stored in the QHash "values" for sorting because the data can
1370 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1376 int KFileItemModel::expandedParentsCount(const ItemData
* data
)
1378 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1379 // if the corresponding item is expanded, and it is not a top-level item.
1380 const ItemData
* parent
= data
->parent
;
1382 if (parent
->parent
) {
1383 Q_ASSERT(parent
->values
.contains("expandedParentsCount"));
1384 return parent
->values
.value("expandedParentsCount").toInt() + 1;
1393 void KFileItemModel::removeExpandedItems()
1395 QVector
<int> indexesToRemove
;
1397 const int maxIndex
= m_itemData
.count() - 1;
1398 for (int i
= 0; i
<= maxIndex
; ++i
) {
1399 const ItemData
* itemData
= m_itemData
.at(i
);
1400 if (itemData
->parent
) {
1401 indexesToRemove
.append(i
);
1405 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove
), DeleteItemData
);
1406 m_expandedDirs
.clear();
1408 // Also remove all filtered items which have a parent.
1409 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
1410 const QHash
<KFileItem
, ItemData
*>::iterator end
= m_filteredItems
.end();
1413 if (it
.value()->parent
) {
1415 it
= m_filteredItems
.erase(it
);
1422 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList
& itemRanges
, const QSet
<QByteArray
>& changedRoles
)
1424 emit
itemsChanged(itemRanges
, changedRoles
);
1426 // Trigger a resorting if necessary. Note that this can happen even if the sort
1427 // role has not changed at all because the file name can be used as a fallback.
1428 if (changedRoles
.contains(sortRole()) || changedRoles
.contains(roleForType(NameRole
))) {
1429 foreach (const KItemRange
& range
, itemRanges
) {
1430 bool needsResorting
= false;
1432 const int first
= range
.index
;
1433 const int last
= range
.index
+ range
.count
- 1;
1435 // Resorting the model is necessary if
1436 // (a) The first item in the range is "lessThan" its predecessor,
1437 // (b) the successor of the last item is "lessThan" the last item, or
1438 // (c) the internal order of the items in the range is incorrect.
1440 && lessThan(m_itemData
.at(first
), m_itemData
.at(first
- 1), m_collator
)) {
1441 needsResorting
= true;
1442 } else if (last
< count() - 1
1443 && lessThan(m_itemData
.at(last
+ 1), m_itemData
.at(last
), m_collator
)) {
1444 needsResorting
= true;
1446 for (int index
= first
; index
< last
; ++index
) {
1447 if (lessThan(m_itemData
.at(index
+ 1), m_itemData
.at(index
), m_collator
)) {
1448 needsResorting
= true;
1454 if (needsResorting
) {
1455 m_resortAllItemsTimer
->start();
1461 if (groupedSorting() && changedRoles
.contains(sortRole())) {
1462 // The position is still correct, but the groups might have changed
1463 // if the changed item is either the first or the last item in a
1465 // In principle, we could try to find out if the item really is the
1466 // first or last one in its group and then update the groups
1467 // (possibly with a delayed timer to make sure that we don't
1468 // re-calculate the groups very often if items are updated one by
1469 // one), but starting m_resortAllItemsTimer is easier.
1470 m_resortAllItemsTimer
->start();
1474 void KFileItemModel::resetRoles()
1476 for (int i
= 0; i
< RolesCount
; ++i
) {
1477 m_requestRole
[i
] = false;
1481 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1483 static QHash
<QByteArray
, RoleType
> roles
;
1484 if (roles
.isEmpty()) {
1485 // Insert user visible roles that can be accessed with
1486 // KFileItemModel::roleInformation()
1488 const RoleInfoMap
* map
= rolesInfoMap(count
);
1489 for (int i
= 0; i
< count
; ++i
) {
1490 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1493 // Insert internal roles (take care to synchronize the implementation
1494 // with KFileItemModel::roleForType() in case if a change is done).
1495 roles
.insert("isDir", IsDirRole
);
1496 roles
.insert("isLink", IsLinkRole
);
1497 roles
.insert("isHidden", IsHiddenRole
);
1498 roles
.insert("isExpanded", IsExpandedRole
);
1499 roles
.insert("isExpandable", IsExpandableRole
);
1500 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1502 Q_ASSERT(roles
.count() == RolesCount
);
1505 return roles
.value(role
, NoRole
);
1508 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1510 static QHash
<RoleType
, QByteArray
> roles
;
1511 if (roles
.isEmpty()) {
1512 // Insert user visible roles that can be accessed with
1513 // KFileItemModel::roleInformation()
1515 const RoleInfoMap
* map
= rolesInfoMap(count
);
1516 for (int i
= 0; i
< count
; ++i
) {
1517 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1520 // Insert internal roles (take care to synchronize the implementation
1521 // with KFileItemModel::typeForRole() in case if a change is done).
1522 roles
.insert(IsDirRole
, "isDir");
1523 roles
.insert(IsLinkRole
, "isLink");
1524 roles
.insert(IsHiddenRole
, "isHidden");
1525 roles
.insert(IsExpandedRole
, "isExpanded");
1526 roles
.insert(IsExpandableRole
, "isExpandable");
1527 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1529 Q_ASSERT(roles
.count() == RolesCount
);
1532 return roles
.value(roleType
);
1535 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
, const ItemData
* parent
) const
1537 // It is important to insert only roles that are fast to retrieve. E.g.
1538 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1539 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1540 QHash
<QByteArray
, QVariant
> data
;
1541 data
.insert(sharedValue("url"), item
.url());
1543 const bool isDir
= item
.isDir();
1544 if (m_requestRole
[IsDirRole
] && isDir
) {
1545 data
.insert(sharedValue("isDir"), true);
1548 if (m_requestRole
[IsLinkRole
] && item
.isLink()) {
1549 data
.insert(sharedValue("isLink"), true);
1552 if (m_requestRole
[IsHiddenRole
] && item
.isHidden()) {
1553 data
.insert(sharedValue("isHidden"), true);
1556 if (m_requestRole
[NameRole
]) {
1557 data
.insert(sharedValue("text"), item
.text());
1560 if (m_requestRole
[SizeRole
] && !isDir
) {
1561 data
.insert(sharedValue("size"), item
.size());
1564 if (m_requestRole
[ModificationTimeRole
]) {
1565 // Don't use KFileItem::timeString() as this is too expensive when
1566 // having several thousands of items. Instead the formatting of the
1567 // date-time will be done on-demand by the view when the date will be shown.
1568 const QDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
1569 data
.insert(sharedValue("modificationtime"), dateTime
);
1572 if (m_requestRole
[CreationTimeRole
]) {
1573 // Don't use KFileItem::timeString() as this is too expensive when
1574 // having several thousands of items. Instead the formatting of the
1575 // date-time will be done on-demand by the view when the date will be shown.
1576 const QDateTime dateTime
= item
.time(KFileItem::CreationTime
);
1577 data
.insert(sharedValue("creationtime"), dateTime
);
1580 if (m_requestRole
[AccessTimeRole
]) {
1581 // Don't use KFileItem::timeString() as this is too expensive when
1582 // having several thousands of items. Instead the formatting of the
1583 // date-time will be done on-demand by the view when the date will be shown.
1584 const QDateTime dateTime
= item
.time(KFileItem::AccessTime
);
1585 data
.insert(sharedValue("accesstime"), dateTime
);
1588 if (m_requestRole
[PermissionsRole
]) {
1589 data
.insert(sharedValue("permissions"), item
.permissionsString());
1592 if (m_requestRole
[OwnerRole
]) {
1593 data
.insert(sharedValue("owner"), item
.user());
1596 if (m_requestRole
[GroupRole
]) {
1597 data
.insert(sharedValue("group"), item
.group());
1600 if (m_requestRole
[DestinationRole
]) {
1601 QString destination
= item
.linkDest();
1602 if (destination
.isEmpty()) {
1603 destination
= QStringLiteral("-");
1605 data
.insert(sharedValue("destination"), destination
);
1608 if (m_requestRole
[PathRole
]) {
1610 if (item
.url().scheme() == QLatin1String("trash")) {
1611 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1613 // For performance reasons cache the home-path in a static QString
1614 // (see QDir::homePath() for more details)
1615 static QString homePath
;
1616 if (homePath
.isEmpty()) {
1617 homePath
= QDir::homePath();
1620 path
= item
.localPath();
1621 if (path
.startsWith(homePath
)) {
1622 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1626 const int index
= path
.lastIndexOf(item
.text());
1627 path
= path
.mid(0, index
- 1);
1628 data
.insert(sharedValue("path"), path
);
1631 if (m_requestRole
[DeletionTimeRole
]) {
1632 QDateTime deletionTime
;
1633 if (item
.url().scheme() == QLatin1String("trash")) {
1634 deletionTime
= QDateTime::fromString(item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
+ 1), Qt::ISODate
);
1636 data
.insert(sharedValue("deletiontime"), deletionTime
);
1639 if (m_requestRole
[IsExpandableRole
] && isDir
) {
1640 data
.insert(sharedValue("isExpandable"), true);
1643 if (m_requestRole
[ExpandedParentsCountRole
]) {
1645 const int level
= expandedParentsCount(parent
) + 1;
1646 data
.insert(sharedValue("expandedParentsCount"), level
);
1650 if (item
.isMimeTypeKnown()) {
1651 data
.insert(sharedValue("iconName"), item
.iconName());
1653 if (m_requestRole
[TypeRole
]) {
1654 data
.insert(sharedValue("type"), item
.mimeComment());
1656 } else if (m_requestRole
[TypeRole
] && isDir
) {
1657 static const QString folderMimeType
= item
.mimeComment();
1658 data
.insert(sharedValue("type"), folderMimeType
);
1664 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const
1668 if (a
->parent
!= b
->parent
) {
1669 const int expansionLevelA
= expandedParentsCount(a
);
1670 const int expansionLevelB
= expandedParentsCount(b
);
1672 // If b has a higher expansion level than a, check if a is a parent
1673 // of b, and make sure that both expansion levels are equal otherwise.
1674 for (int i
= expansionLevelB
; i
> expansionLevelA
; --i
) {
1675 if (b
->parent
== a
) {
1681 // If a has a higher expansion level than a, check if b is a parent
1682 // of a, and make sure that both expansion levels are equal otherwise.
1683 for (int i
= expansionLevelA
; i
> expansionLevelB
; --i
) {
1684 if (a
->parent
== b
) {
1690 Q_ASSERT(expandedParentsCount(a
) == expandedParentsCount(b
));
1692 // Compare the last parents of a and b which are different.
1693 while (a
->parent
!= b
->parent
) {
1699 if (m_sortDirsFirst
|| m_sortRole
== SizeRole
) {
1700 const bool isDirA
= a
->item
.isDir();
1701 const bool isDirB
= b
->item
.isDir();
1702 if (isDirA
&& !isDirB
) {
1704 } else if (!isDirA
&& isDirB
) {
1709 result
= sortRoleCompare(a
, b
, collator
);
1711 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1715 * Helper class for KFileItemModel::sort().
1717 class KFileItemModelLessThan
1720 KFileItemModelLessThan(const KFileItemModel
* model
, const QCollator
& collator
) :
1722 m_collator(collator
)
1726 KFileItemModelLessThan(const KFileItemModelLessThan
& other
) :
1727 m_model(other
.m_model
),
1730 m_collator
.setCaseSensitivity(other
.m_collator
.caseSensitivity());
1731 m_collator
.setIgnorePunctuation(other
.m_collator
.ignorePunctuation());
1732 m_collator
.setLocale(other
.m_collator
.locale());
1733 m_collator
.setNumericMode(other
.m_collator
.numericMode());
1736 ~KFileItemModelLessThan() = default;
1737 //We do not delete m_model as the pointer was passed from outside ant it will be deleted elsewhere.
1739 KFileItemModelLessThan
& operator=(const KFileItemModelLessThan
& other
)
1741 m_model
= other
.m_model
;
1742 m_collator
= other
.m_collator
;
1746 bool operator()(const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
) const
1748 return m_model
->lessThan(a
, b
, m_collator
);
1752 const KFileItemModel
* m_model
;
1753 QCollator m_collator
;
1756 void KFileItemModel::sort(QList
<KFileItemModel::ItemData
*>::iterator begin
,
1757 QList
<KFileItemModel::ItemData
*>::iterator end
) const
1759 KFileItemModelLessThan
lessThan(this, m_collator
);
1761 if (m_sortRole
== NameRole
) {
1762 // Sorting by name can be expensive, in particular if natural sorting is
1763 // enabled. Use all CPU cores to speed up the sorting process.
1764 static const int numberOfThreads
= QThread::idealThreadCount();
1765 parallelMergeSort(begin
, end
, lessThan
, numberOfThreads
);
1767 // Sorting by other roles is quite fast. Use only one thread to prevent
1768 // problems caused by non-reentrant comparison functions, see
1769 // https://bugs.kde.org/show_bug.cgi?id=312679
1770 mergeSort(begin
, end
, lessThan
);
1774 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const
1776 const KFileItem
& itemA
= a
->item
;
1777 const KFileItem
& itemB
= b
->item
;
1781 switch (m_sortRole
) {
1783 // The name role is handled as default fallback after the switch
1787 if (itemA
.isDir()) {
1788 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1789 Q_ASSERT(itemB
.isDir());
1791 const QVariant valueA
= a
->values
.value("size");
1792 const QVariant valueB
= b
->values
.value("size");
1793 if (valueA
.isNull() && valueB
.isNull()) {
1795 } else if (valueA
.isNull()) {
1797 } else if (valueB
.isNull()) {
1800 result
= valueA
.toInt() - valueB
.toInt();
1803 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1804 Q_ASSERT(!itemB
.isDir());
1805 const KIO::filesize_t sizeA
= itemA
.size();
1806 const KIO::filesize_t sizeB
= itemB
.size();
1807 if (sizeA
> sizeB
) {
1809 } else if (sizeA
< sizeB
) {
1818 case ModificationTimeRole
: {
1819 const QDateTime dateTimeA
= itemA
.time(KFileItem::ModificationTime
);
1820 const QDateTime dateTimeB
= itemB
.time(KFileItem::ModificationTime
);
1821 if (dateTimeA
< dateTimeB
) {
1823 } else if (dateTimeA
> dateTimeB
) {
1829 case CreationTimeRole
: {
1830 const QDateTime dateTimeA
= itemA
.time(KFileItem::CreationTime
);
1831 const QDateTime dateTimeB
= itemB
.time(KFileItem::CreationTime
);
1832 if (dateTimeA
< dateTimeB
) {
1834 } else if (dateTimeA
> dateTimeB
) {
1840 case DeletionTimeRole
: {
1841 const QDateTime dateTimeA
= a
->values
.value("deletiontime").toDateTime();
1842 const QDateTime dateTimeB
= b
->values
.value("deletiontime").toDateTime();
1843 if (dateTimeA
< dateTimeB
) {
1845 } else if (dateTimeA
> dateTimeB
) {
1852 result
= a
->values
.value("rating").toInt() - b
->values
.value("rating").toInt();
1856 case ImageSizeRole
: {
1857 // Alway use a natural comparing to interpret the numbers of a string like
1858 // "1600 x 1200" for having a correct sorting.
1859 result
= collator
.compare(a
->values
.value("imageSize").toString(),
1860 b
->values
.value("imageSize").toString());
1865 const QByteArray role
= roleForType(m_sortRole
);
1866 result
= QString::compare(a
->values
.value(role
).toString(),
1867 b
->values
.value(role
).toString());
1874 // The current sort role was sufficient to define an order
1878 // Fallback #1: Compare the text of the items
1879 result
= stringCompare(itemA
.text(), itemB
.text(), collator
);
1884 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1885 result
= stringCompare(itemA
.name(), itemB
.name(), collator
);
1890 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1891 // equal. In this case a comparison of the URL is done which is unique in all cases
1892 // within KDirLister.
1893 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1896 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
, const QCollator
& collator
) const
1898 if (m_naturalSorting
) {
1899 return collator
.compare(a
, b
);
1902 const int result
= QString::compare(a
, b
, collator
.caseSensitivity());
1903 if (result
!= 0 || collator
.caseSensitivity() == Qt::CaseSensitive
) {
1904 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1905 // comparison, still a deterministic sort order is required. A case sensitive
1906 // comparison is done as fallback.
1910 return QString::compare(a
, b
, Qt::CaseSensitive
);
1913 bool KFileItemModel::useMaximumUpdateInterval() const
1915 return !m_dirLister
->url().isLocalFile();
1918 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1920 Q_ASSERT(!m_itemData
.isEmpty());
1922 const int maxIndex
= count() - 1;
1923 QList
<QPair
<int, QVariant
> > groups
;
1927 for (int i
= 0; i
<= maxIndex
; ++i
) {
1928 if (isChildItem(i
)) {
1932 const QString name
= m_itemData
.at(i
)->item
.text();
1934 // Use the first character of the name as group indication
1935 QChar newFirstChar
= name
.at(0).toUpper();
1936 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1937 newFirstChar
= name
.at(1).toUpper();
1940 if (firstChar
!= newFirstChar
) {
1941 QString newGroupValue
;
1942 if (newFirstChar
.isLetter()) {
1943 // Try to find a matching group in the range 'A' to 'Z'.
1944 static std::vector
<QChar
> lettersAtoZ
;
1945 lettersAtoZ
.reserve('Z' - 'A' + 1);
1946 if (lettersAtoZ
.empty()) {
1947 for (char c
= 'A'; c
<= 'Z'; ++c
) {
1948 lettersAtoZ
.push_back(QLatin1Char(c
));
1952 auto localeAwareLessThan
= [this](QChar c1
, QChar c2
) -> bool {
1953 return m_collator
.compare(c1
, c2
) < 0;
1956 std::vector
<QChar
>::iterator it
= std::lower_bound(lettersAtoZ
.begin(), lettersAtoZ
.end(), newFirstChar
, localeAwareLessThan
);
1957 if (it
!= lettersAtoZ
.end()) {
1958 if (localeAwareLessThan(newFirstChar
, *it
) && it
!= lettersAtoZ
.begin()) {
1959 // newFirstChar belongs to the group preceding *it.
1960 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
1963 newGroupValue
= *it
;
1965 newGroupValue
= newFirstChar
;
1967 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
1968 // Apply group '0 - 9' for any name that starts with a digit
1969 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
1971 newGroupValue
= i18nc("@title:group", "Others");
1974 if (newGroupValue
!= groupValue
) {
1975 groupValue
= newGroupValue
;
1976 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1979 firstChar
= newFirstChar
;
1985 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
1987 Q_ASSERT(!m_itemData
.isEmpty());
1989 const int maxIndex
= count() - 1;
1990 QList
<QPair
<int, QVariant
> > groups
;
1993 for (int i
= 0; i
<= maxIndex
; ++i
) {
1994 if (isChildItem(i
)) {
1998 const KFileItem
& item
= m_itemData
.at(i
)->item
;
1999 const KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
2000 QString newGroupValue
;
2001 if (!item
.isNull() && item
.isDir()) {
2002 newGroupValue
= i18nc("@title:group Size", "Folders");
2003 } else if (fileSize
< 5 * 1024 * 1024) {
2004 newGroupValue
= i18nc("@title:group Size", "Small");
2005 } else if (fileSize
< 10 * 1024 * 1024) {
2006 newGroupValue
= i18nc("@title:group Size", "Medium");
2008 newGroupValue
= i18nc("@title:group Size", "Big");
2011 if (newGroupValue
!= groupValue
) {
2012 groupValue
= newGroupValue
;
2013 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2020 QList
<QPair
<int, QVariant
> > KFileItemModel::timeRoleGroups(std::function
<QDateTime(const ItemData
*)> fileTimeCb
) const
2022 Q_ASSERT(!m_itemData
.isEmpty());
2024 const int maxIndex
= count() - 1;
2025 QList
<QPair
<int, QVariant
> > groups
;
2027 const QDate currentDate
= QDate::currentDate();
2029 QDate previousFileDate
;
2031 for (int i
= 0; i
<= maxIndex
; ++i
) {
2032 if (isChildItem(i
)) {
2036 const QDateTime fileTime
= fileTimeCb(m_itemData
.at(i
));
2037 const QDate fileDate
= fileTime
.date();
2038 if (fileDate
== previousFileDate
) {
2039 // The current item is in the same group as the previous item
2042 previousFileDate
= fileDate
;
2044 const int daysDistance
= fileDate
.daysTo(currentDate
);
2046 QString newGroupValue
;
2047 if (currentDate
.year() == fileDate
.year() &&
2048 currentDate
.month() == fileDate
.month()) {
2050 switch (daysDistance
/ 7) {
2052 switch (daysDistance
) {
2053 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
2054 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
2056 newGroupValue
= fileTime
.toString(
2057 i18nc("@title:group Date: The week day name: dddd", "dddd"));
2058 newGroupValue
= i18nc("Can be used to script translation of \"dddd\""
2059 "with context @title:group Date", "%1", newGroupValue
);
2063 newGroupValue
= i18nc("@title:group Date", "One Week Ago");
2066 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
2069 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
2073 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
2079 const QDate lastMonthDate
= currentDate
.addMonths(-1);
2080 if (lastMonthDate
.year() == fileDate
.year() &&
2081 lastMonthDate
.month() == fileDate
.month()) {
2083 if (daysDistance
== 1) {
2084 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: "
2085 "MMMM is full month name in current locale, and yyyy is "
2086 "full year number", "'Yesterday' (MMMM, yyyy)"));
2087 newGroupValue
= i18nc("Can be used to script translation of "
2088 "\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date",
2089 "%1", newGroupValue
);
2090 } else if (daysDistance
<= 7) {
2091 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: "
2092 "The week day name: dddd, MMMM is full month name "
2093 "in current locale, and yyyy is full year number",
2094 "dddd (MMMM, yyyy)"));
2095 newGroupValue
= i18nc("Can be used to script translation of "
2096 "\"dddd (MMMM, yyyy)\" with context @title:group Date",
2097 "%1", newGroupValue
);
2098 } else if (daysDistance
<= 7 * 2) {
2099 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: "
2100 "MMMM is full month name in current locale, and yyyy is "
2101 "full year number", "'One Week Ago' (MMMM, yyyy)"));
2102 newGroupValue
= i18nc("Can be used to script translation of "
2103 "\"'One Week Ago' (MMMM, yyyy)\" with context @title:group Date",
2104 "%1", newGroupValue
);
2105 } else if (daysDistance
<= 7 * 3) {
2106 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: "
2107 "MMMM is full month name in current locale, and yyyy is "
2108 "full year number", "'Two Weeks Ago' (MMMM, yyyy)"));
2109 newGroupValue
= i18nc("Can be used to script translation of "
2110 "\"'Two Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2111 "%1", newGroupValue
);
2112 } else if (daysDistance
<= 7 * 4) {
2113 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: "
2114 "MMMM is full month name in current locale, and yyyy is "
2115 "full year number", "'Three Weeks Ago' (MMMM, yyyy)"));
2116 newGroupValue
= i18nc("Can be used to script translation of "
2117 "\"'Three Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2118 "%1", newGroupValue
);
2120 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: "
2121 "MMMM is full month name in current locale, and yyyy is "
2122 "full year number", "'Earlier on' MMMM, yyyy"));
2123 newGroupValue
= i18nc("Can be used to script translation of "
2124 "\"'Earlier on' MMMM, yyyy\" with context @title:group Date",
2125 "%1", newGroupValue
);
2128 newGroupValue
= fileTime
.toString(i18nc("@title:group "
2129 "The month and year: MMMM is full month name in current locale, "
2130 "and yyyy is full year number", "MMMM, yyyy"));
2131 newGroupValue
= i18nc("Can be used to script translation of "
2132 "\"MMMM, yyyy\" with context @title:group Date",
2133 "%1", newGroupValue
);
2137 if (newGroupValue
!= groupValue
) {
2138 groupValue
= newGroupValue
;
2139 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2146 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
2148 Q_ASSERT(!m_itemData
.isEmpty());
2150 const int maxIndex
= count() - 1;
2151 QList
<QPair
<int, QVariant
> > groups
;
2153 QString permissionsString
;
2155 for (int i
= 0; i
<= maxIndex
; ++i
) {
2156 if (isChildItem(i
)) {
2160 const ItemData
* itemData
= m_itemData
.at(i
);
2161 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
2162 if (newPermissionsString
== permissionsString
) {
2165 permissionsString
= newPermissionsString
;
2167 const QFileInfo
info(itemData
->item
.url().toLocalFile());
2171 if (info
.permission(QFile::ReadUser
)) {
2172 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2174 if (info
.permission(QFile::WriteUser
)) {
2175 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2177 if (info
.permission(QFile::ExeUser
)) {
2178 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2180 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
2184 if (info
.permission(QFile::ReadGroup
)) {
2185 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2187 if (info
.permission(QFile::WriteGroup
)) {
2188 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2190 if (info
.permission(QFile::ExeGroup
)) {
2191 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2193 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
2195 // Set others string
2197 if (info
.permission(QFile::ReadOther
)) {
2198 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2200 if (info
.permission(QFile::WriteOther
)) {
2201 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2203 if (info
.permission(QFile::ExeOther
)) {
2204 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2206 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
2208 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
2209 if (newGroupValue
!= groupValue
) {
2210 groupValue
= newGroupValue
;
2211 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2218 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
2220 Q_ASSERT(!m_itemData
.isEmpty());
2222 const int maxIndex
= count() - 1;
2223 QList
<QPair
<int, QVariant
> > groups
;
2225 int groupValue
= -1;
2226 for (int i
= 0; i
<= maxIndex
; ++i
) {
2227 if (isChildItem(i
)) {
2230 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
2231 if (newGroupValue
!= groupValue
) {
2232 groupValue
= newGroupValue
;
2233 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2240 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
2242 Q_ASSERT(!m_itemData
.isEmpty());
2244 const int maxIndex
= count() - 1;
2245 QList
<QPair
<int, QVariant
> > groups
;
2247 bool isFirstGroupValue
= true;
2249 for (int i
= 0; i
<= maxIndex
; ++i
) {
2250 if (isChildItem(i
)) {
2253 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
2254 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
2255 groupValue
= newGroupValue
;
2256 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2257 isFirstGroupValue
= false;
2264 void KFileItemModel::emitSortProgress(int resolvedCount
)
2266 // Be tolerant against a resolvedCount with a wrong range.
2267 // Although there should not be a case where KFileItemModelRolesUpdater
2268 // (= caller) provides a wrong range, it is important to emit
2269 // a useful progress information even if there is an unexpected
2270 // implementation issue.
2272 const int itemCount
= count();
2273 if (resolvedCount
>= itemCount
) {
2274 m_sortingProgressPercent
= -1;
2275 if (m_resortAllItemsTimer
->isActive()) {
2276 m_resortAllItemsTimer
->stop();
2280 emit
directorySortingProgress(100);
2281 } else if (itemCount
> 0) {
2282 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
2284 const int progress
= resolvedCount
* 100 / itemCount
;
2285 if (m_sortingProgressPercent
!= progress
) {
2286 m_sortingProgressPercent
= progress
;
2287 emit
directorySortingProgress(progress
);
2292 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
2294 static const RoleInfoMap rolesInfoMap
[] = {
2295 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
2296 { nullptr, NoRole
, nullptr, nullptr, nullptr, nullptr, false, false },
2297 { "text", NameRole
, I18N_NOOP2_NOSTRIP("@label", "Name"), nullptr, nullptr, false, false },
2298 { "size", SizeRole
, I18N_NOOP2_NOSTRIP("@label", "Size"), nullptr, nullptr, false, false },
2299 { "modificationtime", ModificationTimeRole
, I18N_NOOP2_NOSTRIP("@label", "Modified"), nullptr, nullptr, false, false },
2300 { "creationtime", CreationTimeRole
, I18N_NOOP2_NOSTRIP("@label", "Created"), nullptr, nullptr, false, false },
2301 { "accesstime", AccessTimeRole
, I18N_NOOP2_NOSTRIP("@label", "Accessed"), nullptr, nullptr, false, false },
2302 { "type", TypeRole
, I18N_NOOP2_NOSTRIP("@label", "Type"), nullptr, nullptr, false, false },
2303 { "rating", RatingRole
, I18N_NOOP2_NOSTRIP("@label", "Rating"), nullptr, nullptr, true, false },
2304 { "tags", TagsRole
, I18N_NOOP2_NOSTRIP("@label", "Tags"), nullptr, nullptr, true, false },
2305 { "comment", CommentRole
, I18N_NOOP2_NOSTRIP("@label", "Comment"), nullptr, nullptr, true, false },
2306 { "title", TitleRole
, I18N_NOOP2_NOSTRIP("@label", "Title"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
2307 { "wordCount", WordCountRole
, I18N_NOOP2_NOSTRIP("@label", "Word Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
2308 { "lineCount", LineCountRole
, I18N_NOOP2_NOSTRIP("@label", "Line Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
2309 { "imageDateTime", ImageDateTimeRole
, I18N_NOOP2_NOSTRIP("@label", "Date Photographed"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
2310 { "imageSize", ImageSizeRole
, I18N_NOOP2_NOSTRIP("@label", "Image Size"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
2311 { "orientation", OrientationRole
, I18N_NOOP2_NOSTRIP("@label", "Orientation"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
2312 { "artist", ArtistRole
, I18N_NOOP2_NOSTRIP("@label", "Artist"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
2313 { "genre", GenreRole
, I18N_NOOP2_NOSTRIP("@label", "Genre"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
2314 { "album", AlbumRole
, I18N_NOOP2_NOSTRIP("@label", "Album"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
2315 { "duration", DurationRole
, I18N_NOOP2_NOSTRIP("@label", "Duration"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
2316 { "bitrate", BitrateRole
, I18N_NOOP2_NOSTRIP("@label", "Bitrate"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
2317 { "track", TrackRole
, I18N_NOOP2_NOSTRIP("@label", "Track"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
2318 { "releaseYear", ReleaseYearRole
, I18N_NOOP2_NOSTRIP("@label", "Release Year"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
2319 { "path", PathRole
, I18N_NOOP2_NOSTRIP("@label", "Path"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2320 { "deletiontime",DeletionTimeRole
,I18N_NOOP2_NOSTRIP("@label", "Deletion Time"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2321 { "destination", DestinationRole
, I18N_NOOP2_NOSTRIP("@label", "Link Destination"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2322 { "originUrl", OriginUrlRole
, I18N_NOOP2_NOSTRIP("@label", "Downloaded From"), I18N_NOOP2_NOSTRIP("@label", "Other"), true, false },
2323 { "permissions", PermissionsRole
, I18N_NOOP2_NOSTRIP("@label", "Permissions"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2324 { "owner", OwnerRole
, I18N_NOOP2_NOSTRIP("@label", "Owner"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2325 { "group", GroupRole
, I18N_NOOP2_NOSTRIP("@label", "User Group"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2328 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
2329 return rolesInfoMap
;
2332 void KFileItemModel::determineMimeTypes(const KFileItemList
& items
, int timeout
)
2334 QElapsedTimer timer
;
2336 foreach (const KFileItem
& item
, items
) { // krazy:exclude=foreach
2337 // Only determine mime types for files here. For directories,
2338 // KFileItem::determineMimeType() reads the .directory file inside to
2339 // load the icon, but this is not necessary at all if we just need the
2340 // type. Some special code for setting the correct mime type for
2341 // directories is in retrieveData().
2342 if (!item
.isDir()) {
2343 item
.determineMimeType();
2346 if (timer
.elapsed() > timeout
) {
2347 // Don't block the user interface, let the remaining items
2348 // be resolved asynchronously.
2354 QByteArray
KFileItemModel::sharedValue(const QByteArray
& value
)
2356 static QSet
<QByteArray
> pool
;
2357 const QSet
<QByteArray
>::const_iterator it
= pool
.constFind(value
);
2359 if (it
!= pool
.constEnd()) {
2367 bool KFileItemModel::isConsistent() const
2369 // m_items may contain less items than m_itemData because m_items
2370 // is populated lazily, see KFileItemModel::index(const QUrl& url).
2371 if (m_items
.count() > m_itemData
.count()) {
2375 for (int i
= 0, iMax
= count(); i
< iMax
; ++i
) {
2376 // Check if m_items and m_itemData are consistent.
2377 const KFileItem item
= fileItem(i
);
2378 if (item
.isNull()) {
2379 qCWarning(DolphinDebug
) << "Item" << i
<< "is null";
2383 const int itemIndex
= index(item
);
2384 if (itemIndex
!= i
) {
2385 qCWarning(DolphinDebug
) << "Item" << i
<< "has a wrong index:" << itemIndex
;
2389 // Check if the items are sorted correctly.
2390 if (i
> 0 && !lessThan(m_itemData
.at(i
- 1), m_itemData
.at(i
), m_collator
)) {
2391 qCWarning(DolphinDebug
) << "The order of items" << i
- 1 << "and" << i
<< "is wrong:"
2392 << fileItem(i
- 1) << fileItem(i
);
2396 // Check if all parent-child relationships are consistent.
2397 const ItemData
* data
= m_itemData
.at(i
);
2398 const ItemData
* parent
= data
->parent
;
2400 if (expandedParentsCount(data
) != expandedParentsCount(parent
) + 1) {
2401 qCWarning(DolphinDebug
) << "expandedParentsCount is inconsistent for parent" << parent
->item
<< "and child" << data
->item
;
2405 const int parentIndex
= index(parent
->item
);
2406 if (parentIndex
>= i
) {
2407 qCWarning(DolphinDebug
) << "Index" << parentIndex
<< "of parent" << parent
->item
<< "is not smaller than index" << i
<< "of child" << data
->item
;