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"
25 #include "dolphin_detailsmodesettings.h"
26 #include "dolphindebug.h"
27 #include "private/kfileitemmodeldirlister.h"
28 #include "private/kfileitemmodelsortalgorithm.h"
30 #include <KLocalizedString>
31 #include <KUrlMimeData>
33 #include <QElapsedTimer>
39 Q_GLOBAL_STATIC_WITH_ARGS(QMutex
, s_collatorMutex
, (QMutex::Recursive
))
41 // #define KFILEITEMMODEL_DEBUG
43 KFileItemModel::KFileItemModel(QObject
* parent
) :
44 KItemModelBase("text", parent
),
46 m_sortDirsFirst(true),
48 m_sortingProgressPercent(-1),
55 m_maximumUpdateIntervalTimer(nullptr),
56 m_resortAllItemsTimer(nullptr),
57 m_pendingItemsToInsert(),
62 m_collator
.setNumericMode(true);
64 loadSortingSettings();
66 m_dirLister
= new KFileItemModelDirLister(this);
67 m_dirLister
->setDelayedMimeTypes(true);
69 const QWidget
* parentWidget
= qobject_cast
<QWidget
*>(parent
);
71 m_dirLister
->setMainWindow(parentWidget
->window());
74 connect(m_dirLister
, &KFileItemModelDirLister::started
, this, &KFileItemModel::directoryLoadingStarted
);
75 connect(m_dirLister
, QOverload
<>::of(&KCoreDirLister::canceled
), this, &KFileItemModel::slotCanceled
);
76 connect(m_dirLister
, QOverload
<const QUrl
&>::of(&KCoreDirLister::completed
), this, &KFileItemModel::slotCompleted
);
77 connect(m_dirLister
, &KFileItemModelDirLister::itemsAdded
, this, &KFileItemModel::slotItemsAdded
);
78 connect(m_dirLister
, &KFileItemModelDirLister::itemsDeleted
, this, &KFileItemModel::slotItemsDeleted
);
79 connect(m_dirLister
, &KFileItemModelDirLister::refreshItems
, this, &KFileItemModel::slotRefreshItems
);
80 connect(m_dirLister
, QOverload
<>::of(&KCoreDirLister::clear
), this, &KFileItemModel::slotClear
);
81 connect(m_dirLister
, &KFileItemModelDirLister::infoMessage
, this, &KFileItemModel::infoMessage
);
82 connect(m_dirLister
, &KFileItemModelDirLister::errorMessage
, this, &KFileItemModel::errorMessage
);
83 connect(m_dirLister
, &KFileItemModelDirLister::percent
, this, &KFileItemModel::directoryLoadingProgress
);
84 connect(m_dirLister
, QOverload
<const QUrl
&, const QUrl
&>::of(&KCoreDirLister::redirection
), this, &KFileItemModel::directoryRedirection
);
85 connect(m_dirLister
, &KFileItemModelDirLister::urlIsFileError
, this, &KFileItemModel::urlIsFileError
);
87 // Apply default roles that should be determined
89 m_requestRole
[NameRole
] = true;
90 m_requestRole
[IsDirRole
] = true;
91 m_requestRole
[IsLinkRole
] = true;
92 m_roles
.insert("text");
93 m_roles
.insert("isDir");
94 m_roles
.insert("isLink");
95 m_roles
.insert("isHidden");
97 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
98 // before the completed() or canceled() signal has been emitted.
99 m_maximumUpdateIntervalTimer
= new QTimer(this);
100 m_maximumUpdateIntervalTimer
->setInterval(2000);
101 m_maximumUpdateIntervalTimer
->setSingleShot(true);
102 connect(m_maximumUpdateIntervalTimer
, &QTimer::timeout
, this, &KFileItemModel::dispatchPendingItemsToInsert
);
104 // When changing the value of an item which represents the sort-role a resorting must be
105 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
106 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
107 // resorting is postponed until the timer has been exceeded.
108 m_resortAllItemsTimer
= new QTimer(this);
109 m_resortAllItemsTimer
->setInterval(500);
110 m_resortAllItemsTimer
->setSingleShot(true);
111 connect(m_resortAllItemsTimer
, &QTimer::timeout
, this, &KFileItemModel::resortAllItems
);
113 connect(GeneralSettings::self(), &GeneralSettings::sortingChoiceChanged
, this, &KFileItemModel::slotSortingChoiceChanged
);
116 KFileItemModel::~KFileItemModel()
118 qDeleteAll(m_itemData
);
119 qDeleteAll(m_filteredItems
);
120 qDeleteAll(m_pendingItemsToInsert
);
123 void KFileItemModel::loadDirectory(const QUrl
&url
)
125 m_dirLister
->openUrl(url
);
128 void KFileItemModel::refreshDirectory(const QUrl
&url
)
130 // Refresh all expanded directories first (Bug 295300)
131 QHashIterator
<QUrl
, QUrl
> expandedDirs(m_expandedDirs
);
132 while (expandedDirs
.hasNext()) {
134 m_dirLister
->openUrl(expandedDirs
.value(), KDirLister::Reload
);
137 m_dirLister
->openUrl(url
, KDirLister::Reload
);
140 QUrl
KFileItemModel::directory() const
142 return m_dirLister
->url();
145 void KFileItemModel::cancelDirectoryLoading()
150 int KFileItemModel::count() const
152 return m_itemData
.count();
155 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
157 if (index
>= 0 && index
< count()) {
158 ItemData
* data
= m_itemData
.at(index
);
159 if (data
->values
.isEmpty()) {
160 data
->values
= retrieveData(data
->item
, data
->parent
);
165 return QHash
<QByteArray
, QVariant
>();
168 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
170 if (index
< 0 || index
>= count()) {
174 QHash
<QByteArray
, QVariant
> currentValues
= data(index
);
176 // Determine which roles have been changed
177 QSet
<QByteArray
> changedRoles
;
178 QHashIterator
<QByteArray
, QVariant
> it(values
);
179 while (it
.hasNext()) {
181 const QByteArray role
= sharedValue(it
.key());
182 const QVariant value
= it
.value();
184 if (currentValues
[role
] != value
) {
185 currentValues
[role
] = value
;
186 changedRoles
.insert(role
);
190 if (changedRoles
.isEmpty()) {
194 m_itemData
[index
]->values
= currentValues
;
195 if (changedRoles
.contains("text")) {
196 QUrl url
= m_itemData
[index
]->item
.url();
197 url
= url
.adjusted(QUrl::RemoveFilename
);
198 url
.setPath(url
.path() + currentValues
["text"].toString());
199 m_itemData
[index
]->item
.setUrl(url
);
202 emitItemsChangedAndTriggerResorting(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
207 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
209 if (dirsFirst
!= m_sortDirsFirst
) {
210 m_sortDirsFirst
= dirsFirst
;
215 bool KFileItemModel::sortDirectoriesFirst() const
217 return m_sortDirsFirst
;
220 void KFileItemModel::setShowHiddenFiles(bool show
)
222 m_dirLister
->setShowingDotFiles(show
);
223 m_dirLister
->emitChanges();
225 dispatchPendingItemsToInsert();
229 bool KFileItemModel::showHiddenFiles() const
231 return m_dirLister
->showingDotFiles();
234 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
236 m_dirLister
->setDirOnlyMode(enabled
);
239 bool KFileItemModel::showDirectoriesOnly() const
241 return m_dirLister
->dirOnlyMode();
244 QMimeData
* KFileItemModel::createMimeData(const KItemSet
& indexes
) const
246 QMimeData
* data
= new QMimeData();
248 // The following code has been taken from KDirModel::mimeData()
249 // (kdelibs/kio/kio/kdirmodel.cpp)
250 // Copyright (C) 2006 David Faure <faure@kde.org>
252 QList
<QUrl
> mostLocalUrls
;
253 const ItemData
* lastAddedItem
= nullptr;
255 for (int index
: indexes
) {
256 const ItemData
* itemData
= m_itemData
.at(index
);
257 const ItemData
* parent
= itemData
->parent
;
259 while (parent
&& parent
!= lastAddedItem
) {
260 parent
= parent
->parent
;
263 if (parent
&& parent
== lastAddedItem
) {
264 // A parent of 'itemData' has been added already.
268 lastAddedItem
= itemData
;
269 const KFileItem
& item
= itemData
->item
;
270 if (!item
.isNull()) {
274 mostLocalUrls
<< item
.mostLocalUrl(&isLocal
);
278 KUrlMimeData::setUrls(urls
, mostLocalUrls
, data
);
282 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
284 startFromIndex
= qMax(0, startFromIndex
);
285 for (int i
= startFromIndex
; i
< count(); ++i
) {
286 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
290 for (int i
= 0; i
< startFromIndex
; ++i
) {
291 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
298 bool KFileItemModel::supportsDropping(int index
) const
300 const KFileItem item
= fileItem(index
);
301 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
304 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
306 static QHash
<QByteArray
, QString
> description
;
307 if (description
.isEmpty()) {
309 const RoleInfoMap
* map
= rolesInfoMap(count
);
310 for (int i
= 0; i
< count
; ++i
) {
311 if (!map
[i
].roleTranslation
) {
314 description
.insert(map
[i
].role
, i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
));
318 return description
.value(role
);
321 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
323 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
324 #ifdef KFILEITEMMODEL_DEBUG
328 switch (typeForRole(sortRole())) {
329 case NameRole
: m_groups
= nameRoleGroups(); break;
330 case SizeRole
: m_groups
= sizeRoleGroups(); break;
331 case ModificationTimeRole
:
332 m_groups
= timeRoleGroups([](const ItemData
*item
) {
333 return item
->item
.time(KFileItem::ModificationTime
);
336 case CreationTimeRole
:
337 m_groups
= timeRoleGroups([](const ItemData
*item
) {
338 return item
->item
.time(KFileItem::CreationTime
);
342 m_groups
= timeRoleGroups([](const ItemData
*item
) {
343 return item
->item
.time(KFileItem::AccessTime
);
346 case DeletionTimeRole
:
347 m_groups
= timeRoleGroups([](const ItemData
*item
) {
348 return item
->values
.value("deletiontime").toDateTime();
351 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
352 case RatingRole
: m_groups
= ratingRoleGroups(); break;
353 default: m_groups
= genericStringRoleGroups(sortRole()); break;
356 #ifdef KFILEITEMMODEL_DEBUG
357 qCDebug(DolphinDebug
) << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
364 KFileItem
KFileItemModel::fileItem(int index
) const
366 if (index
>= 0 && index
< count()) {
367 return m_itemData
.at(index
)->item
;
373 KFileItem
KFileItemModel::fileItem(const QUrl
&url
) const
375 const int indexForUrl
= index(url
);
376 if (indexForUrl
>= 0) {
377 return m_itemData
.at(indexForUrl
)->item
;
382 int KFileItemModel::index(const KFileItem
& item
) const
384 return index(item
.url());
387 int KFileItemModel::index(const QUrl
& url
) const
389 const QUrl urlToFind
= url
.adjusted(QUrl::StripTrailingSlash
);
391 const int itemCount
= m_itemData
.count();
392 int itemsInHash
= m_items
.count();
394 int index
= m_items
.value(urlToFind
, -1);
395 while (index
< 0 && itemsInHash
< itemCount
) {
396 // Not all URLs are stored yet in m_items. We grow m_items until either
397 // urlToFind is found, or all URLs have been stored in m_items.
398 // Note that we do not add the URLs to m_items one by one, but in
399 // larger blocks. After each block, we check if urlToFind is in
400 // m_items. We could in principle compare urlToFind with each URL while
401 // we are going through m_itemData, but comparing two QUrls will,
402 // unlike calling qHash for the URLs, trigger a parsing of the URLs
403 // which costs both CPU cycles and memory.
404 const int blockSize
= 1000;
405 const int currentBlockEnd
= qMin(itemsInHash
+ blockSize
, itemCount
);
406 for (int i
= itemsInHash
; i
< currentBlockEnd
; ++i
) {
407 const QUrl nextUrl
= m_itemData
.at(i
)->item
.url();
408 m_items
.insert(nextUrl
, i
);
411 itemsInHash
= currentBlockEnd
;
412 index
= m_items
.value(urlToFind
, -1);
416 // The item could not be found, even though all items from m_itemData
417 // should be in m_items now. We print some diagnostic information which
418 // might help to find the cause of the problem, but only once. This
419 // prevents that obtaining and printing the debugging information
420 // wastes CPU cycles and floods the shell or .xsession-errors.
421 static bool printDebugInfo
= true;
423 if (m_items
.count() != m_itemData
.count() && printDebugInfo
) {
424 printDebugInfo
= false;
426 qCWarning(DolphinDebug
) << "The model is in an inconsistent state.";
427 qCWarning(DolphinDebug
) << "m_items.count() ==" << m_items
.count();
428 qCWarning(DolphinDebug
) << "m_itemData.count() ==" << m_itemData
.count();
430 // Check if there are multiple items with the same URL.
431 QMultiHash
<QUrl
, int> indexesForUrl
;
432 for (int i
= 0; i
< m_itemData
.count(); ++i
) {
433 indexesForUrl
.insert(m_itemData
.at(i
)->item
.url(), i
);
436 foreach (const QUrl
& url
, indexesForUrl
.uniqueKeys()) {
437 if (indexesForUrl
.count(url
) > 1) {
438 qCWarning(DolphinDebug
) << "Multiple items found with the URL" << url
;
440 auto it
= indexesForUrl
.find(url
);
441 while (it
!= indexesForUrl
.end() && it
.key() == url
) {
442 const ItemData
* data
= m_itemData
.at(it
.value());
443 qCWarning(DolphinDebug
) << "index" << it
.value() << ":" << data
->item
;
445 qCWarning(DolphinDebug
) << "parent" << data
->parent
->item
;
457 KFileItem
KFileItemModel::rootItem() const
459 return m_dirLister
->rootItem();
462 void KFileItemModel::clear()
467 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
469 if (m_roles
== roles
) {
473 const QSet
<QByteArray
> changedRoles
= (roles
- m_roles
) + (m_roles
- roles
);
477 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
478 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
479 if (supportedExpanding
&& !willSupportExpanding
) {
480 // No expanding is supported anymore. Take care to delete all items that have an expansion level
481 // that is not 0 (and hence are part of an expanded item).
482 removeExpandedItems();
489 QSetIterator
<QByteArray
> it(roles
);
490 while (it
.hasNext()) {
491 const QByteArray
& role
= it
.next();
492 m_requestRole
[typeForRole(role
)] = true;
496 // Update m_data with the changed requested roles
497 const int maxIndex
= count() - 1;
498 for (int i
= 0; i
<= maxIndex
; ++i
) {
499 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
, m_itemData
.at(i
)->parent
);
502 emit
itemsChanged(KItemRangeList() << KItemRange(0, count()), changedRoles
);
505 // Clear the 'values' of all filtered items. They will be re-populated with the
506 // correct roles the next time 'values' will be accessed via data(int).
507 QHash
<KFileItem
, ItemData
*>::iterator filteredIt
= m_filteredItems
.begin();
508 const QHash
<KFileItem
, ItemData
*>::iterator filteredEnd
= m_filteredItems
.end();
509 while (filteredIt
!= filteredEnd
) {
510 (*filteredIt
)->values
.clear();
515 QSet
<QByteArray
> KFileItemModel::roles() const
520 bool KFileItemModel::setExpanded(int index
, bool expanded
)
522 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
526 QHash
<QByteArray
, QVariant
> values
;
527 values
.insert(sharedValue("isExpanded"), expanded
);
528 if (!setData(index
, values
)) {
532 const KFileItem item
= m_itemData
.at(index
)->item
;
533 const QUrl url
= item
.url();
534 const QUrl targetUrl
= item
.targetUrl();
536 m_expandedDirs
.insert(targetUrl
, url
);
537 m_dirLister
->openUrl(url
, KDirLister::Keep
);
539 const QVariantList previouslyExpandedChildren
= m_itemData
.at(index
)->values
.value("previouslyExpandedChildren").value
<QVariantList
>();
540 foreach (const QVariant
& var
, previouslyExpandedChildren
) {
541 m_urlsToExpand
.insert(var
.toUrl());
544 // Note that there might be (indirect) children of the folder which is to be collapsed in
545 // m_pendingItemsToInsert. To prevent that they will be inserted into the model later,
546 // possibly without a parent, which might result in a crash, we insert all pending items
547 // right now. All new items which would be without a parent will then be removed.
548 dispatchPendingItemsToInsert();
550 // Check if the index of the collapsed folder has changed. If that is the case, then items
551 // were inserted before the collapsed folder, and its index needs to be updated.
552 if (m_itemData
.at(index
)->item
!= item
) {
553 index
= this->index(item
);
556 m_expandedDirs
.remove(targetUrl
);
557 m_dirLister
->stop(url
);
559 const int parentLevel
= expandedParentsCount(index
);
560 const int itemCount
= m_itemData
.count();
561 const int firstChildIndex
= index
+ 1;
563 QVariantList expandedChildren
;
565 int childIndex
= firstChildIndex
;
566 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
567 ItemData
* itemData
= m_itemData
.at(childIndex
);
568 if (itemData
->values
.value("isExpanded").toBool()) {
569 const QUrl targetUrl
= itemData
->item
.targetUrl();
570 const QUrl url
= itemData
->item
.url();
571 m_expandedDirs
.remove(targetUrl
);
572 m_dirLister
->stop(url
); // TODO: try to unit-test this, see https://bugs.kde.org/show_bug.cgi?id=332102#c11
573 expandedChildren
.append(targetUrl
);
577 const int childrenCount
= childIndex
- firstChildIndex
;
579 removeFilteredChildren(KItemRangeList() << KItemRange(index
, 1 + childrenCount
));
580 removeItems(KItemRangeList() << KItemRange(firstChildIndex
, childrenCount
), DeleteItemData
);
582 m_itemData
.at(index
)->values
.insert("previouslyExpandedChildren", expandedChildren
);
588 bool KFileItemModel::isExpanded(int index
) const
590 if (index
>= 0 && index
< count()) {
591 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
596 bool KFileItemModel::isExpandable(int index
) const
598 if (index
>= 0 && index
< count()) {
599 // Call data (instead of accessing m_itemData directly)
600 // to ensure that the value is initialized.
601 return data(index
).value("isExpandable").toBool();
606 int KFileItemModel::expandedParentsCount(int index
) const
608 if (index
>= 0 && index
< count()) {
609 return expandedParentsCount(m_itemData
.at(index
));
614 QSet
<QUrl
> KFileItemModel::expandedDirectories() const
617 const auto dirs
= m_expandedDirs
;
618 for (const auto &dir
: dirs
) {
624 void KFileItemModel::restoreExpandedDirectories(const QSet
<QUrl
> &urls
)
626 m_urlsToExpand
= urls
;
629 void KFileItemModel::expandParentDirectories(const QUrl
&url
)
632 // Assure that each sub-path of the URL that should be
633 // expanded is added to m_urlsToExpand. KDirLister
634 // does not care whether the parent-URL has already been
636 QUrl urlToExpand
= m_dirLister
->url();
637 const int pos
= urlToExpand
.path().length();
639 // first subdir can be empty, if m_dirLister->url().path() does not end with '/'
640 // this happens if baseUrl is not root but a home directory, see FoldersPanel,
641 // so using QString::SkipEmptyParts
642 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator(), QString::SkipEmptyParts
);
643 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
644 QString path
= urlToExpand
.path();
645 if (!path
.endsWith(QLatin1Char('/'))) {
646 path
.append(QLatin1Char('/'));
648 urlToExpand
.setPath(path
+ subDirs
.at(i
));
649 m_urlsToExpand
.insert(urlToExpand
);
652 // KDirLister::open() must called at least once to trigger an initial
653 // loading. The pending URLs that must be restored are handled
654 // in slotCompleted().
655 QSetIterator
<QUrl
> it2(m_urlsToExpand
);
656 while (it2
.hasNext()) {
657 const int idx
= index(it2
.next());
658 if (idx
>= 0 && !isExpanded(idx
)) {
659 setExpanded(idx
, true);
665 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
667 if (m_filter
.pattern() != nameFilter
) {
668 dispatchPendingItemsToInsert();
669 m_filter
.setPattern(nameFilter
);
674 QString
KFileItemModel::nameFilter() const
676 return m_filter
.pattern();
679 void KFileItemModel::setMimeTypeFilters(const QStringList
& filters
)
681 if (m_filter
.mimeTypes() != filters
) {
682 dispatchPendingItemsToInsert();
683 m_filter
.setMimeTypes(filters
);
688 QStringList
KFileItemModel::mimeTypeFilters() const
690 return m_filter
.mimeTypes();
694 void KFileItemModel::applyFilters()
696 // Check which shown items from m_itemData must get
697 // hidden and hence moved to m_filteredItems.
698 QVector
<int> newFilteredIndexes
;
700 const int itemCount
= m_itemData
.count();
701 for (int index
= 0; index
< itemCount
; ++index
) {
702 ItemData
* itemData
= m_itemData
.at(index
);
704 // Only filter non-expanded items as child items may never
705 // exist without a parent item
706 if (!itemData
->values
.value("isExpanded").toBool()) {
707 const KFileItem item
= itemData
->item
;
708 if (!m_filter
.matches(item
)) {
709 newFilteredIndexes
.append(index
);
710 m_filteredItems
.insert(item
, itemData
);
715 const KItemRangeList removedRanges
= KItemRangeList::fromSortedContainer(newFilteredIndexes
);
716 removeItems(removedRanges
, KeepItemData
);
718 // Check which hidden items from m_filteredItems should
719 // get visible again and hence removed from m_filteredItems.
720 QList
<ItemData
*> newVisibleItems
;
722 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
723 while (it
!= m_filteredItems
.end()) {
724 if (m_filter
.matches(it
.key())) {
725 newVisibleItems
.append(it
.value());
726 it
= m_filteredItems
.erase(it
);
732 insertItems(newVisibleItems
);
735 void KFileItemModel::removeFilteredChildren(const KItemRangeList
& itemRanges
)
737 if (m_filteredItems
.isEmpty() || !m_requestRole
[ExpandedParentsCountRole
]) {
738 // There are either no filtered items, or it is not possible to expand
739 // folders -> there cannot be any filtered children.
743 QSet
<ItemData
*> parents
;
744 foreach (const KItemRange
& range
, itemRanges
) {
745 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
746 parents
.insert(m_itemData
.at(index
));
750 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
751 while (it
!= m_filteredItems
.end()) {
752 if (parents
.contains(it
.value()->parent
)) {
754 it
= m_filteredItems
.erase(it
);
761 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
763 static QList
<RoleInfo
> rolesInfo
;
764 if (rolesInfo
.isEmpty()) {
766 const RoleInfoMap
* map
= rolesInfoMap(count
);
767 for (int i
= 0; i
< count
; ++i
) {
768 if (map
[i
].roleType
!= NoRole
) {
770 info
.role
= map
[i
].role
;
771 info
.translation
= i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
);
772 if (map
[i
].groupTranslation
) {
773 info
.group
= i18nc(map
[i
].groupTranslationContext
, map
[i
].groupTranslation
);
775 // For top level roles, groupTranslation is 0. We must make sure that
776 // info.group is an empty string then because the code that generates
777 // menus tries to put the actions into sub menus otherwise.
778 info
.group
= QString();
780 info
.requiresBaloo
= map
[i
].requiresBaloo
;
781 info
.requiresIndexer
= map
[i
].requiresIndexer
;
782 rolesInfo
.append(info
);
790 void KFileItemModel::onGroupedSortingChanged(bool current
)
796 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
, bool resortItems
)
799 m_sortRole
= typeForRole(current
);
801 if (!m_requestRole
[m_sortRole
]) {
802 QSet
<QByteArray
> newRoles
= m_roles
;
812 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
819 void KFileItemModel::loadSortingSettings()
821 using Choice
= GeneralSettings::EnumSortingChoice
;
822 switch (GeneralSettings::sortingChoice()) {
823 case Choice::NaturalSorting
:
824 m_naturalSorting
= true;
825 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
827 case Choice::CaseSensitiveSorting
:
828 m_naturalSorting
= false;
829 m_collator
.setCaseSensitivity(Qt::CaseSensitive
);
831 case Choice::CaseInsensitiveSorting
:
832 m_naturalSorting
= false;
833 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
838 // Workaround for bug https://bugreports.qt.io/browse/QTBUG-69361
839 // Force the clean state of QCollator in single thread to avoid thread safety problems in sort
840 m_collator
.compare(QString(), QString());
843 void KFileItemModel::resortAllItems()
845 m_resortAllItemsTimer
->stop();
847 const int itemCount
= count();
848 if (itemCount
<= 0) {
852 #ifdef KFILEITEMMODEL_DEBUG
855 qCDebug(DolphinDebug
) << "===========================================================";
856 qCDebug(DolphinDebug
) << "Resorting" << itemCount
<< "items";
859 // Remember the order of the current URLs so
860 // that it can be determined which indexes have
861 // been moved because of the resorting.
863 oldUrls
.reserve(itemCount
);
864 foreach (const ItemData
* itemData
, m_itemData
) {
865 oldUrls
.append(itemData
->item
.url());
869 m_items
.reserve(itemCount
);
872 sort(m_itemData
.begin(), m_itemData
.end());
873 for (int i
= 0; i
< itemCount
; ++i
) {
874 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
877 // Determine the first index that has been moved.
878 int firstMovedIndex
= 0;
879 while (firstMovedIndex
< itemCount
880 && firstMovedIndex
== m_items
.value(oldUrls
.at(firstMovedIndex
))) {
884 const bool itemsHaveMoved
= firstMovedIndex
< itemCount
;
885 if (itemsHaveMoved
) {
888 int lastMovedIndex
= itemCount
- 1;
889 while (lastMovedIndex
> firstMovedIndex
890 && lastMovedIndex
== m_items
.value(oldUrls
.at(lastMovedIndex
))) {
894 Q_ASSERT(firstMovedIndex
<= lastMovedIndex
);
896 // Create a list movedToIndexes, which has the property that
897 // movedToIndexes[i] is the new index of the item with the old index
898 // firstMovedIndex + i.
899 const int movedItemsCount
= lastMovedIndex
- firstMovedIndex
+ 1;
900 QList
<int> movedToIndexes
;
901 movedToIndexes
.reserve(movedItemsCount
);
902 for (int i
= firstMovedIndex
; i
<= lastMovedIndex
; ++i
) {
903 const int newIndex
= m_items
.value(oldUrls
.at(i
));
904 movedToIndexes
.append(newIndex
);
907 emit
itemsMoved(KItemRange(firstMovedIndex
, movedItemsCount
), movedToIndexes
);
908 } else if (groupedSorting()) {
909 // The groups might have changed even if the order of the items has not.
910 const QList
<QPair
<int, QVariant
> > oldGroups
= m_groups
;
912 if (groups() != oldGroups
) {
913 emit
groupsChanged();
917 #ifdef KFILEITEMMODEL_DEBUG
918 qCDebug(DolphinDebug
) << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
922 void KFileItemModel::slotCompleted()
924 m_maximumUpdateIntervalTimer
->stop();
925 dispatchPendingItemsToInsert();
927 if (!m_urlsToExpand
.isEmpty()) {
928 // Try to find a URL that can be expanded.
929 // Note that the parent folder must be expanded before any of its subfolders become visible.
930 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
931 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
932 foreach (const QUrl
& url
, m_urlsToExpand
) {
933 const int indexForUrl
= index(url
);
934 if (indexForUrl
>= 0) {
935 m_urlsToExpand
.remove(url
);
936 if (setExpanded(indexForUrl
, true)) {
937 // The dir lister has been triggered. This slot will be called
938 // again after the directory has been expanded.
944 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
945 // if these URLs have been deleted in the meantime.
946 m_urlsToExpand
.clear();
949 emit
directoryLoadingCompleted();
952 void KFileItemModel::slotCanceled()
954 m_maximumUpdateIntervalTimer
->stop();
955 dispatchPendingItemsToInsert();
957 emit
directoryLoadingCanceled();
960 void KFileItemModel::slotItemsAdded(const QUrl
&directoryUrl
, const KFileItemList
& items
)
962 Q_ASSERT(!items
.isEmpty());
965 if (m_expandedDirs
.contains(directoryUrl
)) {
966 parentUrl
= m_expandedDirs
.value(directoryUrl
);
968 parentUrl
= directoryUrl
.adjusted(QUrl::StripTrailingSlash
);
971 if (m_requestRole
[ExpandedParentsCountRole
]) {
972 // If the expanding of items is enabled, the call
973 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
974 // might result in emitting the same items twice due to the Keep-parameter.
975 // This case happens if an item gets expanded, collapsed and expanded again
976 // before the items could be loaded for the first expansion.
977 if (index(items
.first().url()) >= 0) {
978 // The items are already part of the model.
982 if (directoryUrl
!= directory()) {
983 // To be able to compare whether the new items may be inserted as children
984 // of a parent item the pending items must be added to the model first.
985 dispatchPendingItemsToInsert();
988 // KDirLister keeps the children of items that got expanded once even if
989 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
990 // checked whether the parent for new items is still expanded.
991 const int parentIndex
= index(parentUrl
);
992 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
993 // The parent is not expanded.
998 QList
<ItemData
*> itemDataList
= createItemDataList(parentUrl
, items
);
1000 if (!m_filter
.hasSetFilters()) {
1001 m_pendingItemsToInsert
.append(itemDataList
);
1003 // The name or type filter is active. Hide filtered items
1004 // before inserting them into the model and remember
1005 // the filtered items in m_filteredItems.
1006 foreach (ItemData
* itemData
, itemDataList
) {
1007 if (m_filter
.matches(itemData
->item
)) {
1008 m_pendingItemsToInsert
.append(itemData
);
1010 m_filteredItems
.insert(itemData
->item
, itemData
);
1015 if (!m_maximumUpdateIntervalTimer
->isActive()) {
1016 // Assure that items get dispatched if no completed() or canceled() signal is
1017 // emitted during the maximum update interval.
1018 m_maximumUpdateIntervalTimer
->start();
1022 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
1024 dispatchPendingItemsToInsert();
1026 QVector
<int> indexesToRemove
;
1027 indexesToRemove
.reserve(items
.count());
1029 foreach (const KFileItem
& item
, items
) {
1030 const int indexForItem
= index(item
);
1031 if (indexForItem
>= 0) {
1032 indexesToRemove
.append(indexForItem
);
1034 // Probably the item has been filtered.
1035 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(item
);
1036 if (it
!= m_filteredItems
.end()) {
1038 m_filteredItems
.erase(it
);
1043 std::sort(indexesToRemove
.begin(), indexesToRemove
.end());
1045 if (m_requestRole
[ExpandedParentsCountRole
] && !m_expandedDirs
.isEmpty()) {
1046 // Assure that removing a parent item also results in removing all children
1047 QVector
<int> indexesToRemoveWithChildren
;
1048 indexesToRemoveWithChildren
.reserve(m_itemData
.count());
1050 const int itemCount
= m_itemData
.count();
1051 foreach (int index
, indexesToRemove
) {
1052 indexesToRemoveWithChildren
.append(index
);
1054 const int parentLevel
= expandedParentsCount(index
);
1055 int childIndex
= index
+ 1;
1056 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
1057 indexesToRemoveWithChildren
.append(childIndex
);
1062 indexesToRemove
= indexesToRemoveWithChildren
;
1065 const KItemRangeList itemRanges
= KItemRangeList::fromSortedContainer(indexesToRemove
);
1066 removeFilteredChildren(itemRanges
);
1067 removeItems(itemRanges
, DeleteItemData
);
1070 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
1072 Q_ASSERT(!items
.isEmpty());
1073 #ifdef KFILEITEMMODEL_DEBUG
1074 qCDebug(DolphinDebug
) << "Refreshing" << items
.count() << "items";
1077 // Get the indexes of all items that have been refreshed
1079 indexes
.reserve(items
.count());
1081 QSet
<QByteArray
> changedRoles
;
1083 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
1084 while (it
.hasNext()) {
1085 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
1086 const KFileItem
& oldItem
= itemPair
.first
;
1087 const KFileItem
& newItem
= itemPair
.second
;
1088 const int indexForItem
= index(oldItem
);
1089 if (indexForItem
>= 0) {
1090 m_itemData
[indexForItem
]->item
= newItem
;
1092 // Keep old values as long as possible if they could not retrieved synchronously yet.
1093 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
1094 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
, m_itemData
.at(indexForItem
)->parent
));
1095 QHash
<QByteArray
, QVariant
>& values
= m_itemData
[indexForItem
]->values
;
1096 while (it
.hasNext()) {
1098 const QByteArray
& role
= it
.key();
1099 if (values
.value(role
) != it
.value()) {
1100 values
.insert(role
, it
.value());
1101 changedRoles
.insert(role
);
1105 m_items
.remove(oldItem
.url());
1106 m_items
.insert(newItem
.url(), indexForItem
);
1107 indexes
.append(indexForItem
);
1109 // Check if 'oldItem' is one of the filtered items.
1110 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(oldItem
);
1111 if (it
!= m_filteredItems
.end()) {
1112 ItemData
* itemData
= it
.value();
1113 itemData
->item
= newItem
;
1115 // The data stored in 'values' might have changed. Therefore, we clear
1116 // 'values' and re-populate it the next time it is requested via data(int).
1117 itemData
->values
.clear();
1119 m_filteredItems
.erase(it
);
1120 m_filteredItems
.insert(newItem
, itemData
);
1125 // If the changed items have been created recently, they might not be in m_items yet.
1126 // In that case, the list 'indexes' might be empty.
1127 if (indexes
.isEmpty()) {
1131 // Extract the item-ranges out of the changed indexes
1132 std::sort(indexes
.begin(), indexes
.end());
1133 const KItemRangeList itemRangeList
= KItemRangeList::fromSortedContainer(indexes
);
1134 emitItemsChangedAndTriggerResorting(itemRangeList
, changedRoles
);
1137 void KFileItemModel::slotClear()
1139 #ifdef KFILEITEMMODEL_DEBUG
1140 qCDebug(DolphinDebug
) << "Clearing all items";
1143 qDeleteAll(m_filteredItems
);
1144 m_filteredItems
.clear();
1147 m_maximumUpdateIntervalTimer
->stop();
1148 m_resortAllItemsTimer
->stop();
1150 qDeleteAll(m_pendingItemsToInsert
);
1151 m_pendingItemsToInsert
.clear();
1153 const int removedCount
= m_itemData
.count();
1154 if (removedCount
> 0) {
1155 qDeleteAll(m_itemData
);
1158 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
1161 m_expandedDirs
.clear();
1164 void KFileItemModel::slotSortingChoiceChanged()
1166 loadSortingSettings();
1170 void KFileItemModel::dispatchPendingItemsToInsert()
1172 if (!m_pendingItemsToInsert
.isEmpty()) {
1173 insertItems(m_pendingItemsToInsert
);
1174 m_pendingItemsToInsert
.clear();
1178 void KFileItemModel::insertItems(QList
<ItemData
*>& newItems
)
1180 if (newItems
.isEmpty()) {
1184 #ifdef KFILEITEMMODEL_DEBUG
1185 QElapsedTimer timer
;
1187 qCDebug(DolphinDebug
) << "===========================================================";
1188 qCDebug(DolphinDebug
) << "Inserting" << newItems
.count() << "items";
1192 prepareItemsForSorting(newItems
);
1194 // Natural sorting of items can be very slow. However, it becomes much faster
1195 // if the input sequence is already mostly sorted. Therefore, we first sort
1196 // 'newItems' according to the QStrings using QString::operator<(), which is quite fast.
1197 if (m_naturalSorting
) {
1198 if (m_sortRole
== NameRole
) {
1199 parallelMergeSort(newItems
.begin(), newItems
.end(), nameLessThan
, QThread::idealThreadCount());
1200 } else if (isRoleValueNatural(m_sortRole
)) {
1201 auto lambdaLessThan
= [&] (const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
)
1203 const QByteArray role
= roleForType(m_sortRole
);
1204 return a
->values
.value(role
).toString() < b
->values
.value(role
).toString();
1206 parallelMergeSort(newItems
.begin(), newItems
.end(), lambdaLessThan
, QThread::idealThreadCount());
1210 sort(newItems
.begin(), newItems
.end());
1212 #ifdef KFILEITEMMODEL_DEBUG
1213 qCDebug(DolphinDebug
) << "[TIME] Sorting:" << timer
.elapsed();
1216 KItemRangeList itemRanges
;
1217 const int existingItemCount
= m_itemData
.count();
1218 const int newItemCount
= newItems
.count();
1219 const int totalItemCount
= existingItemCount
+ newItemCount
;
1221 if (existingItemCount
== 0) {
1222 // Optimization for the common special case that there are no
1223 // items in the model yet. Happens, e.g., when entering a folder.
1224 m_itemData
= newItems
;
1225 itemRanges
<< KItemRange(0, newItemCount
);
1227 m_itemData
.reserve(totalItemCount
);
1228 for (int i
= existingItemCount
; i
< totalItemCount
; ++i
) {
1229 m_itemData
.append(nullptr);
1232 // We build the new list m_itemData in reverse order to minimize
1233 // the number of moves and guarantee O(N) complexity.
1234 int targetIndex
= totalItemCount
- 1;
1235 int sourceIndexExistingItems
= existingItemCount
- 1;
1236 int sourceIndexNewItems
= newItemCount
- 1;
1240 while (sourceIndexNewItems
>= 0) {
1241 ItemData
* newItem
= newItems
.at(sourceIndexNewItems
);
1242 if (sourceIndexExistingItems
>= 0 && lessThan(newItem
, m_itemData
.at(sourceIndexExistingItems
), m_collator
)) {
1243 // Move an existing item to its new position. If any new items
1244 // are behind it, push the item range to itemRanges.
1245 if (rangeCount
> 0) {
1246 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1250 m_itemData
[targetIndex
] = m_itemData
.at(sourceIndexExistingItems
);
1251 --sourceIndexExistingItems
;
1253 // Insert a new item into the list.
1255 m_itemData
[targetIndex
] = newItem
;
1256 --sourceIndexNewItems
;
1261 // Push the final item range to itemRanges.
1262 if (rangeCount
> 0) {
1263 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1266 // Note that itemRanges is still sorted in reverse order.
1267 std::reverse(itemRanges
.begin(), itemRanges
.end());
1270 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1271 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1274 emit
itemsInserted(itemRanges
);
1276 #ifdef KFILEITEMMODEL_DEBUG
1277 qCDebug(DolphinDebug
) << "[TIME] Inserting of" << newItems
.count() << "items:" << timer
.elapsed();
1281 void KFileItemModel::removeItems(const KItemRangeList
& itemRanges
, RemoveItemsBehavior behavior
)
1283 if (itemRanges
.isEmpty()) {
1289 // Step 1: Remove the items from m_itemData, and free the ItemData.
1290 int removedItemsCount
= 0;
1291 foreach (const KItemRange
& range
, itemRanges
) {
1292 removedItemsCount
+= range
.count
;
1294 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
1295 if (behavior
== DeleteItemData
) {
1296 delete m_itemData
.at(index
);
1299 m_itemData
[index
] = nullptr;
1303 // Step 2: Remove the ItemData pointers from the list m_itemData.
1304 int target
= itemRanges
.at(0).index
;
1305 int source
= itemRanges
.at(0).index
+ itemRanges
.at(0).count
;
1308 const int oldItemDataCount
= m_itemData
.count();
1309 while (source
< oldItemDataCount
) {
1310 m_itemData
[target
] = m_itemData
[source
];
1314 if (nextRange
< itemRanges
.count() && source
== itemRanges
.at(nextRange
).index
) {
1315 // Skip the items in the next removed range.
1316 source
+= itemRanges
.at(nextRange
).count
;
1321 m_itemData
.erase(m_itemData
.end() - removedItemsCount
, m_itemData
.end());
1323 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1324 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1327 emit
itemsRemoved(itemRanges
);
1330 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const QUrl
& parentUrl
, const KFileItemList
& items
) const
1332 if (m_sortRole
== TypeRole
) {
1333 // Try to resolve the MIME-types synchronously to prevent a reordering of
1334 // the items when sorting by type (per default MIME-types are resolved
1335 // asynchronously by KFileItemModelRolesUpdater).
1336 determineMimeTypes(items
, 200);
1339 const int parentIndex
= index(parentUrl
);
1340 ItemData
* parentItem
= parentIndex
< 0 ? nullptr : m_itemData
.at(parentIndex
);
1342 QList
<ItemData
*> itemDataList
;
1343 itemDataList
.reserve(items
.count());
1345 foreach (const KFileItem
& item
, items
) {
1346 ItemData
* itemData
= new ItemData();
1347 itemData
->item
= item
;
1348 itemData
->parent
= parentItem
;
1349 itemDataList
.append(itemData
);
1352 return itemDataList
;
1355 void KFileItemModel::prepareItemsForSorting(QList
<ItemData
*>& itemDataList
)
1357 switch (m_sortRole
) {
1358 case PermissionsRole
:
1361 case DestinationRole
:
1363 case DeletionTimeRole
:
1364 // These roles can be determined with retrieveData, and they have to be stored
1365 // in the QHash "values" for the sorting.
1366 foreach (ItemData
* itemData
, itemDataList
) {
1367 if (itemData
->values
.isEmpty()) {
1368 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1374 // At least store the data including the file type for items with known MIME type.
1375 foreach (ItemData
* itemData
, itemDataList
) {
1376 if (itemData
->values
.isEmpty()) {
1377 const KFileItem item
= itemData
->item
;
1378 if (item
.isDir() || item
.isMimeTypeKnown()) {
1379 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1386 // The other roles are either resolved by KFileItemModelRolesUpdater
1387 // (this includes the SizeRole for directories), or they do not need
1388 // to be stored in the QHash "values" for sorting because the data can
1389 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1395 int KFileItemModel::expandedParentsCount(const ItemData
* data
)
1397 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1398 // if the corresponding item is expanded, and it is not a top-level item.
1399 const ItemData
* parent
= data
->parent
;
1401 if (parent
->parent
) {
1402 Q_ASSERT(parent
->values
.contains("expandedParentsCount"));
1403 return parent
->values
.value("expandedParentsCount").toInt() + 1;
1412 void KFileItemModel::removeExpandedItems()
1414 QVector
<int> indexesToRemove
;
1416 const int maxIndex
= m_itemData
.count() - 1;
1417 for (int i
= 0; i
<= maxIndex
; ++i
) {
1418 const ItemData
* itemData
= m_itemData
.at(i
);
1419 if (itemData
->parent
) {
1420 indexesToRemove
.append(i
);
1424 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove
), DeleteItemData
);
1425 m_expandedDirs
.clear();
1427 // Also remove all filtered items which have a parent.
1428 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
1429 const QHash
<KFileItem
, ItemData
*>::iterator end
= m_filteredItems
.end();
1432 if (it
.value()->parent
) {
1434 it
= m_filteredItems
.erase(it
);
1441 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList
& itemRanges
, const QSet
<QByteArray
>& changedRoles
)
1443 emit
itemsChanged(itemRanges
, changedRoles
);
1445 // Trigger a resorting if necessary. Note that this can happen even if the sort
1446 // role has not changed at all because the file name can be used as a fallback.
1447 if (changedRoles
.contains(sortRole()) || changedRoles
.contains(roleForType(NameRole
))) {
1448 foreach (const KItemRange
& range
, itemRanges
) {
1449 bool needsResorting
= false;
1451 const int first
= range
.index
;
1452 const int last
= range
.index
+ range
.count
- 1;
1454 // Resorting the model is necessary if
1455 // (a) The first item in the range is "lessThan" its predecessor,
1456 // (b) the successor of the last item is "lessThan" the last item, or
1457 // (c) the internal order of the items in the range is incorrect.
1459 && lessThan(m_itemData
.at(first
), m_itemData
.at(first
- 1), m_collator
)) {
1460 needsResorting
= true;
1461 } else if (last
< count() - 1
1462 && lessThan(m_itemData
.at(last
+ 1), m_itemData
.at(last
), m_collator
)) {
1463 needsResorting
= true;
1465 for (int index
= first
; index
< last
; ++index
) {
1466 if (lessThan(m_itemData
.at(index
+ 1), m_itemData
.at(index
), m_collator
)) {
1467 needsResorting
= true;
1473 if (needsResorting
) {
1474 m_resortAllItemsTimer
->start();
1480 if (groupedSorting() && changedRoles
.contains(sortRole())) {
1481 // The position is still correct, but the groups might have changed
1482 // if the changed item is either the first or the last item in a
1484 // In principle, we could try to find out if the item really is the
1485 // first or last one in its group and then update the groups
1486 // (possibly with a delayed timer to make sure that we don't
1487 // re-calculate the groups very often if items are updated one by
1488 // one), but starting m_resortAllItemsTimer is easier.
1489 m_resortAllItemsTimer
->start();
1493 void KFileItemModel::resetRoles()
1495 for (int i
= 0; i
< RolesCount
; ++i
) {
1496 m_requestRole
[i
] = false;
1500 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1502 static QHash
<QByteArray
, RoleType
> roles
;
1503 if (roles
.isEmpty()) {
1504 // Insert user visible roles that can be accessed with
1505 // KFileItemModel::roleInformation()
1507 const RoleInfoMap
* map
= rolesInfoMap(count
);
1508 for (int i
= 0; i
< count
; ++i
) {
1509 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1512 // Insert internal roles (take care to synchronize the implementation
1513 // with KFileItemModel::roleForType() in case if a change is done).
1514 roles
.insert("isDir", IsDirRole
);
1515 roles
.insert("isLink", IsLinkRole
);
1516 roles
.insert("isHidden", IsHiddenRole
);
1517 roles
.insert("isExpanded", IsExpandedRole
);
1518 roles
.insert("isExpandable", IsExpandableRole
);
1519 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1521 Q_ASSERT(roles
.count() == RolesCount
);
1524 return roles
.value(role
, NoRole
);
1527 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1529 static QHash
<RoleType
, QByteArray
> roles
;
1530 if (roles
.isEmpty()) {
1531 // Insert user visible roles that can be accessed with
1532 // KFileItemModel::roleInformation()
1534 const RoleInfoMap
* map
= rolesInfoMap(count
);
1535 for (int i
= 0; i
< count
; ++i
) {
1536 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1539 // Insert internal roles (take care to synchronize the implementation
1540 // with KFileItemModel::typeForRole() in case if a change is done).
1541 roles
.insert(IsDirRole
, "isDir");
1542 roles
.insert(IsLinkRole
, "isLink");
1543 roles
.insert(IsHiddenRole
, "isHidden");
1544 roles
.insert(IsExpandedRole
, "isExpanded");
1545 roles
.insert(IsExpandableRole
, "isExpandable");
1546 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1548 Q_ASSERT(roles
.count() == RolesCount
);
1551 return roles
.value(roleType
);
1554 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
, const ItemData
* parent
) const
1556 // It is important to insert only roles that are fast to retrieve. E.g.
1557 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1558 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1559 QHash
<QByteArray
, QVariant
> data
;
1560 data
.insert(sharedValue("url"), item
.url());
1562 const bool isDir
= item
.isDir();
1563 if (m_requestRole
[IsDirRole
] && isDir
) {
1564 data
.insert(sharedValue("isDir"), true);
1567 if (m_requestRole
[IsLinkRole
] && item
.isLink()) {
1568 data
.insert(sharedValue("isLink"), true);
1571 if (m_requestRole
[IsHiddenRole
]) {
1572 data
.insert(sharedValue("isHidden"), item
.isHidden());
1575 if (m_requestRole
[NameRole
]) {
1576 data
.insert(sharedValue("text"), item
.text());
1579 if (m_requestRole
[SizeRole
] && !isDir
) {
1580 data
.insert(sharedValue("size"), item
.size());
1583 if (m_requestRole
[ModificationTimeRole
]) {
1584 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1585 // having several thousands of items. Instead read the raw number from UDSEntry directly
1586 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1587 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1588 data
.insert(sharedValue("modificationtime"), dateTime
);
1591 if (m_requestRole
[CreationTimeRole
]) {
1592 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1593 // having several thousands of items. Instead read the raw number from UDSEntry directly
1594 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1595 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1596 data
.insert(sharedValue("creationtime"), dateTime
);
1599 if (m_requestRole
[AccessTimeRole
]) {
1600 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1601 // having several thousands of items. Instead read the raw number from UDSEntry directly
1602 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1603 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
1604 data
.insert(sharedValue("accesstime"), dateTime
);
1607 if (m_requestRole
[PermissionsRole
]) {
1608 data
.insert(sharedValue("permissions"), item
.permissionsString());
1611 if (m_requestRole
[OwnerRole
]) {
1612 data
.insert(sharedValue("owner"), item
.user());
1615 if (m_requestRole
[GroupRole
]) {
1616 data
.insert(sharedValue("group"), item
.group());
1619 if (m_requestRole
[DestinationRole
]) {
1620 QString destination
= item
.linkDest();
1621 if (destination
.isEmpty()) {
1622 destination
= QLatin1Char('-');
1624 data
.insert(sharedValue("destination"), destination
);
1627 if (m_requestRole
[PathRole
]) {
1629 if (item
.url().scheme() == QLatin1String("trash")) {
1630 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1632 // For performance reasons cache the home-path in a static QString
1633 // (see QDir::homePath() for more details)
1634 static QString homePath
;
1635 if (homePath
.isEmpty()) {
1636 homePath
= QDir::homePath();
1639 path
= item
.localPath();
1640 if (path
.startsWith(homePath
)) {
1641 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1645 const int index
= path
.lastIndexOf(item
.text());
1646 path
= path
.mid(0, index
- 1);
1647 data
.insert(sharedValue("path"), path
);
1650 if (m_requestRole
[DeletionTimeRole
]) {
1651 QDateTime deletionTime
;
1652 if (item
.url().scheme() == QLatin1String("trash")) {
1653 deletionTime
= QDateTime::fromString(item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
+ 1), Qt::ISODate
);
1655 data
.insert(sharedValue("deletiontime"), deletionTime
);
1658 if (m_requestRole
[IsExpandableRole
] && isDir
) {
1659 data
.insert(sharedValue("isExpandable"), true);
1662 if (m_requestRole
[ExpandedParentsCountRole
]) {
1664 const int level
= expandedParentsCount(parent
) + 1;
1665 data
.insert(sharedValue("expandedParentsCount"), level
);
1669 if (item
.isMimeTypeKnown()) {
1670 data
.insert(sharedValue("iconName"), item
.iconName());
1672 if (m_requestRole
[TypeRole
]) {
1673 data
.insert(sharedValue("type"), item
.mimeComment());
1675 } else if (m_requestRole
[TypeRole
] && isDir
) {
1676 static const QString folderMimeType
= item
.mimeComment();
1677 data
.insert(sharedValue("type"), folderMimeType
);
1683 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const
1687 if (a
->parent
!= b
->parent
) {
1688 const int expansionLevelA
= expandedParentsCount(a
);
1689 const int expansionLevelB
= expandedParentsCount(b
);
1691 // If b has a higher expansion level than a, check if a is a parent
1692 // of b, and make sure that both expansion levels are equal otherwise.
1693 for (int i
= expansionLevelB
; i
> expansionLevelA
; --i
) {
1694 if (b
->parent
== a
) {
1700 // If a has a higher expansion level than a, check if b is a parent
1701 // of a, and make sure that both expansion levels are equal otherwise.
1702 for (int i
= expansionLevelA
; i
> expansionLevelB
; --i
) {
1703 if (a
->parent
== b
) {
1709 Q_ASSERT(expandedParentsCount(a
) == expandedParentsCount(b
));
1711 // Compare the last parents of a and b which are different.
1712 while (a
->parent
!= b
->parent
) {
1718 if (m_sortDirsFirst
|| m_sortRole
== SizeRole
) {
1719 const bool isDirA
= a
->item
.isDir();
1720 const bool isDirB
= b
->item
.isDir();
1721 if (isDirA
&& !isDirB
) {
1723 } else if (!isDirA
&& isDirB
) {
1728 result
= sortRoleCompare(a
, b
, collator
);
1730 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1733 void KFileItemModel::sort(const QList
<KFileItemModel::ItemData
*>::iterator
&begin
,
1734 const QList
<KFileItemModel::ItemData
*>::iterator
&end
) const
1736 auto lambdaLessThan
= [&] (const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
)
1738 return lessThan(a
, b
, m_collator
);
1741 if (m_sortRole
== NameRole
|| isRoleValueNatural(m_sortRole
)) {
1742 // Sorting by string can be expensive, in particular if natural sorting is
1743 // enabled. Use all CPU cores to speed up the sorting process.
1744 static const int numberOfThreads
= QThread::idealThreadCount();
1745 parallelMergeSort(begin
, end
, lambdaLessThan
, numberOfThreads
);
1747 // Sorting by other roles is quite fast. Use only one thread to prevent
1748 // problems caused by non-reentrant comparison functions, see
1749 // https://bugs.kde.org/show_bug.cgi?id=312679
1750 mergeSort(begin
, end
, lambdaLessThan
);
1754 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const
1756 const KFileItem
& itemA
= a
->item
;
1757 const KFileItem
& itemB
= b
->item
;
1761 switch (m_sortRole
) {
1763 // The name role is handled as default fallback after the switch
1767 if (itemA
.isDir()) {
1768 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1769 Q_ASSERT(itemB
.isDir());
1771 QVariant valueA
, valueB
;
1772 if (DetailsModeSettings::directorySizeCount()) {
1773 valueA
= a
->values
.value("count");
1774 valueB
= b
->values
.value("count");
1776 // use dir size then
1777 valueA
= a
->values
.value("size");
1778 valueB
= b
->values
.value("size");
1780 if (valueA
.isNull() && valueB
.isNull()) {
1782 } else if (valueA
.isNull()) {
1784 } else if (valueB
.isNull()) {
1787 if (valueA
< valueB
) {
1794 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1795 Q_ASSERT(!itemB
.isDir());
1796 const KIO::filesize_t sizeA
= itemA
.size();
1797 const KIO::filesize_t sizeB
= itemB
.size();
1798 if (sizeA
> sizeB
) {
1800 } else if (sizeA
< sizeB
) {
1809 case ModificationTimeRole
: {
1810 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1811 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1812 if (dateTimeA
< dateTimeB
) {
1814 } else if (dateTimeA
> dateTimeB
) {
1820 case CreationTimeRole
: {
1821 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1822 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1823 if (dateTimeA
< dateTimeB
) {
1825 } else if (dateTimeA
> dateTimeB
) {
1831 case DeletionTimeRole
: {
1832 const QDateTime dateTimeA
= a
->values
.value("deletiontime").toDateTime();
1833 const QDateTime dateTimeB
= b
->values
.value("deletiontime").toDateTime();
1834 if (dateTimeA
< dateTimeB
) {
1836 } else if (dateTimeA
> dateTimeB
) {
1848 case ReleaseYearRole
: {
1849 result
= a
->values
.value(roleForType(m_sortRole
)).toInt() - b
->values
.value(roleForType(m_sortRole
)).toInt();
1854 const QByteArray role
= roleForType(m_sortRole
);
1855 const QString roleValueA
= a
->values
.value(role
).toString();
1856 const QString roleValueB
= b
->values
.value(role
).toString();
1857 if (!roleValueA
.isEmpty() && roleValueB
.isEmpty()) {
1859 } else if (roleValueA
.isEmpty() && !roleValueB
.isEmpty()) {
1861 } else if (isRoleValueNatural(m_sortRole
)) {
1862 result
= stringCompare(roleValueA
, roleValueB
, collator
);
1864 result
= QString::compare(roleValueA
, roleValueB
);
1872 // The current sort role was sufficient to define an order
1876 // Fallback #1: Compare the text of the items
1877 result
= stringCompare(itemA
.text(), itemB
.text(), collator
);
1882 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1883 result
= stringCompare(itemA
.name(), itemB
.name(), collator
);
1888 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1889 // equal. In this case a comparison of the URL is done which is unique in all cases
1890 // within KDirLister.
1891 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1894 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
, const QCollator
& collator
) const
1896 QMutexLocker
collatorLock(s_collatorMutex());
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 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1915 Q_ASSERT(!m_itemData
.isEmpty());
1917 const int maxIndex
= count() - 1;
1918 QList
<QPair
<int, QVariant
> > groups
;
1922 for (int i
= 0; i
<= maxIndex
; ++i
) {
1923 if (isChildItem(i
)) {
1927 const QString name
= m_itemData
.at(i
)->item
.text();
1929 // Use the first character of the name as group indication
1930 QChar newFirstChar
= name
.at(0).toUpper();
1931 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1932 newFirstChar
= name
.at(1).toUpper();
1935 if (firstChar
!= newFirstChar
) {
1936 QString newGroupValue
;
1937 if (newFirstChar
.isLetter()) {
1939 if (m_collator
.compare(newFirstChar
, QChar(QLatin1Char('A'))) >= 0 && m_collator
.compare(newFirstChar
, QChar(QLatin1Char('Z'))) <= 0) {
1940 // WARNING! Symbols based on latin 'Z' like 'Z' with acute are treated wrong as non Latin and put in a new group.
1942 // Try to find a matching group in the range 'A' to 'Z'.
1943 static std::vector
<QChar
> lettersAtoZ
;
1944 lettersAtoZ
.reserve('Z' - 'A' + 1);
1945 if (lettersAtoZ
.empty()) {
1946 for (char c
= 'A'; c
<= 'Z'; ++c
) {
1947 lettersAtoZ
.push_back(QLatin1Char(c
));
1951 auto localeAwareLessThan
= [this](QChar c1
, QChar c2
) -> bool {
1952 return m_collator
.compare(c1
, c2
) < 0;
1955 std::vector
<QChar
>::iterator it
= std::lower_bound(lettersAtoZ
.begin(), lettersAtoZ
.end(), newFirstChar
, localeAwareLessThan
);
1956 if (it
!= lettersAtoZ
.end()) {
1957 if (localeAwareLessThan(newFirstChar
, *it
)) {
1958 // newFirstChar belongs to the group preceding *it.
1959 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
1962 newGroupValue
= *it
;
1966 // Symbols from non Latin-based scripts
1967 newGroupValue
= newFirstChar
;
1969 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
1970 // Apply group '0 - 9' for any name that starts with a digit
1971 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
1973 newGroupValue
= i18nc("@title:group", "Others");
1976 if (newGroupValue
!= groupValue
) {
1977 groupValue
= newGroupValue
;
1978 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1981 firstChar
= newFirstChar
;
1987 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
1989 Q_ASSERT(!m_itemData
.isEmpty());
1991 const int maxIndex
= count() - 1;
1992 QList
<QPair
<int, QVariant
> > groups
;
1995 for (int i
= 0; i
<= maxIndex
; ++i
) {
1996 if (isChildItem(i
)) {
2000 const KFileItem
& item
= m_itemData
.at(i
)->item
;
2001 const KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
2002 QString newGroupValue
;
2003 if (!item
.isNull() && item
.isDir()) {
2004 newGroupValue
= i18nc("@title:group Size", "Folders");
2005 } else if (fileSize
< 5 * 1024 * 1024) {
2006 newGroupValue
= i18nc("@title:group Size", "Small");
2007 } else if (fileSize
< 10 * 1024 * 1024) {
2008 newGroupValue
= i18nc("@title:group Size", "Medium");
2010 newGroupValue
= i18nc("@title:group Size", "Big");
2013 if (newGroupValue
!= groupValue
) {
2014 groupValue
= newGroupValue
;
2015 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2022 QList
<QPair
<int, QVariant
> > KFileItemModel::timeRoleGroups(const std::function
<QDateTime(const ItemData
*)> &fileTimeCb
) const
2024 Q_ASSERT(!m_itemData
.isEmpty());
2026 const int maxIndex
= count() - 1;
2027 QList
<QPair
<int, QVariant
> > groups
;
2029 const QDate currentDate
= QDate::currentDate();
2031 QDate previousFileDate
;
2033 for (int i
= 0; i
<= maxIndex
; ++i
) {
2034 if (isChildItem(i
)) {
2038 const QDateTime fileTime
= fileTimeCb(m_itemData
.at(i
));
2039 const QDate fileDate
= fileTime
.date();
2040 if (fileDate
== previousFileDate
) {
2041 // The current item is in the same group as the previous item
2044 previousFileDate
= fileDate
;
2046 const int daysDistance
= fileDate
.daysTo(currentDate
);
2048 QString newGroupValue
;
2049 if (currentDate
.year() == fileDate
.year() &&
2050 currentDate
.month() == fileDate
.month()) {
2052 switch (daysDistance
/ 7) {
2054 switch (daysDistance
) {
2055 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
2056 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
2058 newGroupValue
= fileTime
.toString(
2059 i18nc("@title:group Date: The week day name: dddd", "dddd"));
2060 newGroupValue
= i18nc("Can be used to script translation of \"dddd\""
2061 "with context @title:group Date", "%1", newGroupValue
);
2065 newGroupValue
= i18nc("@title:group Date", "One Week Ago");
2068 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
2071 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
2075 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
2081 const QDate lastMonthDate
= currentDate
.addMonths(-1);
2082 if (lastMonthDate
.year() == fileDate
.year() &&
2083 lastMonthDate
.month() == fileDate
.month()) {
2085 if (daysDistance
== 1) {
2086 const KLocalizedString format
= ki18nc("@title:group Date: "
2087 "MMMM is full month name in current locale, and yyyy is "
2088 "full year number", "'Yesterday' (MMMM, yyyy)");
2089 const QString translatedFormat
= format
.toString();
2090 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2091 newGroupValue
= fileTime
.toString(translatedFormat
);
2092 newGroupValue
= i18nc("Can be used to script translation of "
2093 "\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date",
2094 "%1", newGroupValue
);
2096 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2097 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2098 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2100 } else if (daysDistance
<= 7) {
2101 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: "
2102 "The week day name: dddd, MMMM is full month name "
2103 "in current locale, and yyyy is full year number",
2104 "dddd (MMMM, yyyy)"));
2105 newGroupValue
= i18nc("Can be used to script translation of "
2106 "\"dddd (MMMM, yyyy)\" with context @title:group Date",
2107 "%1", newGroupValue
);
2108 } else if (daysDistance
<= 7 * 2) {
2109 const KLocalizedString format
= ki18nc("@title:group Date: "
2110 "MMMM is full month name in current locale, and yyyy is "
2111 "full year number", "'One Week Ago' (MMMM, yyyy)");
2112 const QString translatedFormat
= format
.toString();
2113 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2114 newGroupValue
= fileTime
.toString(translatedFormat
);
2115 newGroupValue
= i18nc("Can be used to script translation of "
2116 "\"'One Week Ago' (MMMM, yyyy)\" with context @title:group Date",
2117 "%1", newGroupValue
);
2119 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2120 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2121 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2123 } else if (daysDistance
<= 7 * 3) {
2124 const KLocalizedString format
= ki18nc("@title:group Date: "
2125 "MMMM is full month name in current locale, and yyyy is "
2126 "full year number", "'Two Weeks Ago' (MMMM, yyyy)");
2127 const QString translatedFormat
= format
.toString();
2128 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2129 newGroupValue
= fileTime
.toString(translatedFormat
);
2130 newGroupValue
= i18nc("Can be used to script translation of "
2131 "\"'Two Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2132 "%1", newGroupValue
);
2134 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2135 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2136 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2138 } else if (daysDistance
<= 7 * 4) {
2139 const KLocalizedString format
= ki18nc("@title:group Date: "
2140 "MMMM is full month name in current locale, and yyyy is "
2141 "full year number", "'Three Weeks Ago' (MMMM, yyyy)");
2142 const QString translatedFormat
= format
.toString();
2143 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2144 newGroupValue
= fileTime
.toString(translatedFormat
);
2145 newGroupValue
= i18nc("Can be used to script translation of "
2146 "\"'Three Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2147 "%1", newGroupValue
);
2149 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2150 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2151 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2154 const KLocalizedString format
= ki18nc("@title:group Date: "
2155 "MMMM is full month name in current locale, and yyyy is "
2156 "full year number", "'Earlier on' MMMM, yyyy");
2157 const QString translatedFormat
= format
.toString();
2158 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2159 newGroupValue
= fileTime
.toString(translatedFormat
);
2160 newGroupValue
= i18nc("Can be used to script translation of "
2161 "\"'Earlier on' MMMM, yyyy\" with context @title:group Date",
2162 "%1", newGroupValue
);
2164 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2165 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2166 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2170 newGroupValue
= fileTime
.toString(i18nc("@title:group "
2171 "The month and year: MMMM is full month name in current locale, "
2172 "and yyyy is full year number", "MMMM, yyyy"));
2173 newGroupValue
= i18nc("Can be used to script translation of "
2174 "\"MMMM, yyyy\" with context @title:group Date",
2175 "%1", newGroupValue
);
2179 if (newGroupValue
!= groupValue
) {
2180 groupValue
= newGroupValue
;
2181 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2188 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
2190 Q_ASSERT(!m_itemData
.isEmpty());
2192 const int maxIndex
= count() - 1;
2193 QList
<QPair
<int, QVariant
> > groups
;
2195 QString permissionsString
;
2197 for (int i
= 0; i
<= maxIndex
; ++i
) {
2198 if (isChildItem(i
)) {
2202 const ItemData
* itemData
= m_itemData
.at(i
);
2203 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
2204 if (newPermissionsString
== permissionsString
) {
2207 permissionsString
= newPermissionsString
;
2209 const QFileInfo
info(itemData
->item
.url().toLocalFile());
2213 if (info
.permission(QFile::ReadUser
)) {
2214 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2216 if (info
.permission(QFile::WriteUser
)) {
2217 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2219 if (info
.permission(QFile::ExeUser
)) {
2220 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2222 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
2226 if (info
.permission(QFile::ReadGroup
)) {
2227 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2229 if (info
.permission(QFile::WriteGroup
)) {
2230 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2232 if (info
.permission(QFile::ExeGroup
)) {
2233 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2235 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
2237 // Set others string
2239 if (info
.permission(QFile::ReadOther
)) {
2240 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2242 if (info
.permission(QFile::WriteOther
)) {
2243 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2245 if (info
.permission(QFile::ExeOther
)) {
2246 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2248 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
2250 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
2251 if (newGroupValue
!= groupValue
) {
2252 groupValue
= newGroupValue
;
2253 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2260 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
2262 Q_ASSERT(!m_itemData
.isEmpty());
2264 const int maxIndex
= count() - 1;
2265 QList
<QPair
<int, QVariant
> > groups
;
2267 int groupValue
= -1;
2268 for (int i
= 0; i
<= maxIndex
; ++i
) {
2269 if (isChildItem(i
)) {
2272 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
2273 if (newGroupValue
!= groupValue
) {
2274 groupValue
= newGroupValue
;
2275 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2282 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
2284 Q_ASSERT(!m_itemData
.isEmpty());
2286 const int maxIndex
= count() - 1;
2287 QList
<QPair
<int, QVariant
> > groups
;
2289 bool isFirstGroupValue
= true;
2291 for (int i
= 0; i
<= maxIndex
; ++i
) {
2292 if (isChildItem(i
)) {
2295 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
2296 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
2297 groupValue
= newGroupValue
;
2298 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2299 isFirstGroupValue
= false;
2306 void KFileItemModel::emitSortProgress(int resolvedCount
)
2308 // Be tolerant against a resolvedCount with a wrong range.
2309 // Although there should not be a case where KFileItemModelRolesUpdater
2310 // (= caller) provides a wrong range, it is important to emit
2311 // a useful progress information even if there is an unexpected
2312 // implementation issue.
2314 const int itemCount
= count();
2315 if (resolvedCount
>= itemCount
) {
2316 m_sortingProgressPercent
= -1;
2317 if (m_resortAllItemsTimer
->isActive()) {
2318 m_resortAllItemsTimer
->stop();
2322 emit
directorySortingProgress(100);
2323 } else if (itemCount
> 0) {
2324 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
2326 const int progress
= resolvedCount
* 100 / itemCount
;
2327 if (m_sortingProgressPercent
!= progress
) {
2328 m_sortingProgressPercent
= progress
;
2329 emit
directorySortingProgress(progress
);
2334 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
2336 static const RoleInfoMap rolesInfoMap
[] = {
2337 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
2338 { nullptr, NoRole
, nullptr, nullptr, nullptr, nullptr, false, false },
2339 { "text", NameRole
, I18NC_NOOP("@label", "Name"), nullptr, nullptr, false, false },
2340 { "size", SizeRole
, I18NC_NOOP("@label", "Size"), nullptr, nullptr, false, false },
2341 { "modificationtime", ModificationTimeRole
, I18NC_NOOP("@label", "Modified"), nullptr, nullptr, false, false },
2342 { "creationtime", CreationTimeRole
, I18NC_NOOP("@label", "Created"), nullptr, nullptr, false, false },
2343 { "accesstime", AccessTimeRole
, I18NC_NOOP("@label", "Accessed"), nullptr, nullptr, false, false },
2344 { "type", TypeRole
, I18NC_NOOP("@label", "Type"), nullptr, nullptr, false, false },
2345 { "rating", RatingRole
, I18NC_NOOP("@label", "Rating"), nullptr, nullptr, true, false },
2346 { "tags", TagsRole
, I18NC_NOOP("@label", "Tags"), nullptr, nullptr, true, false },
2347 { "comment", CommentRole
, I18NC_NOOP("@label", "Comment"), nullptr, nullptr, true, false },
2348 { "title", TitleRole
, I18NC_NOOP("@label", "Title"), I18NC_NOOP("@label", "Document"), true, true },
2349 { "wordCount", WordCountRole
, I18NC_NOOP("@label", "Word Count"), I18NC_NOOP("@label", "Document"), true, true },
2350 { "lineCount", LineCountRole
, I18NC_NOOP("@label", "Line Count"), I18NC_NOOP("@label", "Document"), true, true },
2351 { "imageDateTime", ImageDateTimeRole
, I18NC_NOOP("@label", "Date Photographed"), I18NC_NOOP("@label", "Image"), true, true },
2352 { "width", WidthRole
, I18NC_NOOP("@label", "Width"), I18NC_NOOP("@label", "Image"), true, true },
2353 { "height", HeightRole
, I18NC_NOOP("@label", "Height"), I18NC_NOOP("@label", "Image"), true, true },
2354 { "orientation", OrientationRole
, I18NC_NOOP("@label", "Orientation"), I18NC_NOOP("@label", "Image"), true, true },
2355 { "artist", ArtistRole
, I18NC_NOOP("@label", "Artist"), I18NC_NOOP("@label", "Audio"), true, true },
2356 { "genre", GenreRole
, I18NC_NOOP("@label", "Genre"), I18NC_NOOP("@label", "Audio"), true, true },
2357 { "album", AlbumRole
, I18NC_NOOP("@label", "Album"), I18NC_NOOP("@label", "Audio"), true, true },
2358 { "duration", DurationRole
, I18NC_NOOP("@label", "Duration"), I18NC_NOOP("@label", "Audio"), true, true },
2359 { "bitrate", BitrateRole
, I18NC_NOOP("@label", "Bitrate"), I18NC_NOOP("@label", "Audio"), true, true },
2360 { "track", TrackRole
, I18NC_NOOP("@label", "Track"), I18NC_NOOP("@label", "Audio"), true, true },
2361 { "releaseYear", ReleaseYearRole
, I18NC_NOOP("@label", "Release Year"), I18NC_NOOP("@label", "Audio"), true, true },
2362 { "aspectRatio", AspectRatioRole
, I18NC_NOOP("@label", "Aspect Ratio"), I18NC_NOOP("@label", "Video"), true, true },
2363 { "frameRate", FrameRateRole
, I18NC_NOOP("@label", "Frame Rate"), I18NC_NOOP("@label", "Video"), true, true },
2364 { "path", PathRole
, I18NC_NOOP("@label", "Path"), I18NC_NOOP("@label", "Other"), false, false },
2365 { "deletiontime", DeletionTimeRole
, I18NC_NOOP("@label", "Deletion Time"), I18NC_NOOP("@label", "Other"), false, false },
2366 { "destination", DestinationRole
, I18NC_NOOP("@label", "Link Destination"), I18NC_NOOP("@label", "Other"), false, false },
2367 { "originUrl", OriginUrlRole
, I18NC_NOOP("@label", "Downloaded From"), I18NC_NOOP("@label", "Other"), true, false },
2368 { "permissions", PermissionsRole
, I18NC_NOOP("@label", "Permissions"), I18NC_NOOP("@label", "Other"), false, false },
2369 { "owner", OwnerRole
, I18NC_NOOP("@label", "Owner"), I18NC_NOOP("@label", "Other"), false, false },
2370 { "group", GroupRole
, I18NC_NOOP("@label", "User Group"), I18NC_NOOP("@label", "Other"), false, false },
2373 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
2374 return rolesInfoMap
;
2377 void KFileItemModel::determineMimeTypes(const KFileItemList
& items
, int timeout
)
2379 QElapsedTimer timer
;
2381 foreach (const KFileItem
& item
, items
) { // krazy:exclude=foreach
2382 // Only determine mime types for files here. For directories,
2383 // KFileItem::determineMimeType() reads the .directory file inside to
2384 // load the icon, but this is not necessary at all if we just need the
2385 // type. Some special code for setting the correct mime type for
2386 // directories is in retrieveData().
2387 if (!item
.isDir()) {
2388 item
.determineMimeType();
2391 if (timer
.elapsed() > timeout
) {
2392 // Don't block the user interface, let the remaining items
2393 // be resolved asynchronously.
2399 QByteArray
KFileItemModel::sharedValue(const QByteArray
& value
)
2401 static QSet
<QByteArray
> pool
;
2402 const QSet
<QByteArray
>::const_iterator it
= pool
.constFind(value
);
2404 if (it
!= pool
.constEnd()) {
2412 bool KFileItemModel::isConsistent() const
2414 // m_items may contain less items than m_itemData because m_items
2415 // is populated lazily, see KFileItemModel::index(const QUrl& url).
2416 if (m_items
.count() > m_itemData
.count()) {
2420 for (int i
= 0, iMax
= count(); i
< iMax
; ++i
) {
2421 // Check if m_items and m_itemData are consistent.
2422 const KFileItem item
= fileItem(i
);
2423 if (item
.isNull()) {
2424 qCWarning(DolphinDebug
) << "Item" << i
<< "is null";
2428 const int itemIndex
= index(item
);
2429 if (itemIndex
!= i
) {
2430 qCWarning(DolphinDebug
) << "Item" << i
<< "has a wrong index:" << itemIndex
;
2434 // Check if the items are sorted correctly.
2435 if (i
> 0 && !lessThan(m_itemData
.at(i
- 1), m_itemData
.at(i
), m_collator
)) {
2436 qCWarning(DolphinDebug
) << "The order of items" << i
- 1 << "and" << i
<< "is wrong:"
2437 << fileItem(i
- 1) << fileItem(i
);
2441 // Check if all parent-child relationships are consistent.
2442 const ItemData
* data
= m_itemData
.at(i
);
2443 const ItemData
* parent
= data
->parent
;
2445 if (expandedParentsCount(data
) != expandedParentsCount(parent
) + 1) {
2446 qCWarning(DolphinDebug
) << "expandedParentsCount is inconsistent for parent" << parent
->item
<< "and child" << data
->item
;
2450 const int parentIndex
= index(parent
->item
);
2451 if (parentIndex
>= i
) {
2452 qCWarning(DolphinDebug
) << "Index" << parentIndex
<< "of parent" << parent
->item
<< "is not smaller than index" << i
<< "of child" << data
->item
;