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"
41 // #define KFILEITEMMODEL_DEBUG
43 KFileItemModel::KFileItemModel(QObject
* parent
) :
44 KItemModelBase("text", parent
),
46 m_sortDirsFirst(true),
48 m_sortingProgressPercent(-1),
55 m_maximumUpdateIntervalTimer(0),
56 m_resortAllItemsTimer(0),
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
, static_cast<void(KFileItemModelDirLister::*)()>(&KFileItemModelDirLister::canceled
), this, &KFileItemModel::slotCanceled
);
76 connect(m_dirLister
, static_cast<void(KFileItemModelDirLister::*)(const QUrl
&)>(&KFileItemModelDirLister::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
, static_cast<void(KFileItemModelDirLister::*)()>(&KFileItemModelDirLister::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
, static_cast<void(KFileItemModelDirLister::*)(const QUrl
&, const QUrl
&)>(&KFileItemModelDirLister::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");
96 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
97 // before the completed() or canceled() signal has been emitted.
98 m_maximumUpdateIntervalTimer
= new QTimer(this);
99 m_maximumUpdateIntervalTimer
->setInterval(2000);
100 m_maximumUpdateIntervalTimer
->setSingleShot(true);
101 connect(m_maximumUpdateIntervalTimer
, &QTimer::timeout
, this, &KFileItemModel::dispatchPendingItemsToInsert
);
103 // When changing the value of an item which represents the sort-role a resorting must be
104 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
105 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
106 // resorting is postponed until the timer has been exceeded.
107 m_resortAllItemsTimer
= new QTimer(this);
108 m_resortAllItemsTimer
->setInterval(500);
109 m_resortAllItemsTimer
->setSingleShot(true);
110 connect(m_resortAllItemsTimer
, &QTimer::timeout
, this, &KFileItemModel::resortAllItems
);
112 connect(GeneralSettings::self(), &GeneralSettings::sortingChoiceChanged
, this, &KFileItemModel::slotSortingChoiceChanged
);
115 KFileItemModel::~KFileItemModel()
117 qDeleteAll(m_itemData
);
118 qDeleteAll(m_filteredItems
);
119 qDeleteAll(m_pendingItemsToInsert
);
122 void KFileItemModel::loadDirectory(const QUrl
&url
)
124 m_dirLister
->openUrl(url
);
127 void KFileItemModel::refreshDirectory(const QUrl
&url
)
129 // Refresh all expanded directories first (Bug 295300)
130 QHashIterator
<QUrl
, QUrl
> expandedDirs(m_expandedDirs
);
131 while (expandedDirs
.hasNext()) {
133 m_dirLister
->openUrl(expandedDirs
.value(), KDirLister::Reload
);
136 m_dirLister
->openUrl(url
, KDirLister::Reload
);
139 QUrl
KFileItemModel::directory() const
141 return m_dirLister
->url();
144 void KFileItemModel::cancelDirectoryLoading()
149 int KFileItemModel::count() const
151 return m_itemData
.count();
154 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
156 if (index
>= 0 && index
< count()) {
157 ItemData
* data
= m_itemData
.at(index
);
158 if (data
->values
.isEmpty()) {
159 data
->values
= retrieveData(data
->item
, data
->parent
);
164 return QHash
<QByteArray
, QVariant
>();
167 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
169 if (index
< 0 || index
>= count()) {
173 QHash
<QByteArray
, QVariant
> currentValues
= data(index
);
175 // Determine which roles have been changed
176 QSet
<QByteArray
> changedRoles
;
177 QHashIterator
<QByteArray
, QVariant
> it(values
);
178 while (it
.hasNext()) {
180 const QByteArray role
= sharedValue(it
.key());
181 const QVariant value
= it
.value();
183 if (currentValues
[role
] != value
) {
184 currentValues
[role
] = value
;
185 changedRoles
.insert(role
);
189 if (changedRoles
.isEmpty()) {
193 m_itemData
[index
]->values
= currentValues
;
194 if (changedRoles
.contains("text")) {
195 QUrl url
= m_itemData
[index
]->item
.url();
196 url
= url
.adjusted(QUrl::RemoveFilename
);
197 url
.setPath(url
.path() + currentValues
["text"].toString());
198 m_itemData
[index
]->item
.setUrl(url
);
201 emitItemsChangedAndTriggerResorting(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
206 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
208 if (dirsFirst
!= m_sortDirsFirst
) {
209 m_sortDirsFirst
= dirsFirst
;
214 bool KFileItemModel::sortDirectoriesFirst() const
216 return m_sortDirsFirst
;
219 void KFileItemModel::setShowHiddenFiles(bool show
)
221 m_dirLister
->setShowingDotFiles(show
);
222 m_dirLister
->emitChanges();
224 dispatchPendingItemsToInsert();
228 bool KFileItemModel::showHiddenFiles() const
230 return m_dirLister
->showingDotFiles();
233 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
235 m_dirLister
->setDirOnlyMode(enabled
);
238 bool KFileItemModel::showDirectoriesOnly() const
240 return m_dirLister
->dirOnlyMode();
243 QMimeData
* KFileItemModel::createMimeData(const KItemSet
& indexes
) const
245 QMimeData
* data
= new QMimeData();
247 // The following code has been taken from KDirModel::mimeData()
248 // (kdelibs/kio/kio/kdirmodel.cpp)
249 // Copyright (C) 2006 David Faure <faure@kde.org>
251 QList
<QUrl
> mostLocalUrls
;
252 bool canUseMostLocalUrls
= true;
253 const ItemData
* lastAddedItem
= 0;
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
);
276 canUseMostLocalUrls
= false;
281 KUrlMimeData::setUrls(urls
, mostLocalUrls
, data
);
285 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
287 startFromIndex
= qMax(0, startFromIndex
);
288 for (int i
= startFromIndex
; i
< count(); ++i
) {
289 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
293 for (int i
= 0; i
< startFromIndex
; ++i
) {
294 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
301 bool KFileItemModel::supportsDropping(int index
) const
303 const KFileItem item
= fileItem(index
);
304 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
307 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
309 static QHash
<QByteArray
, QString
> description
;
310 if (description
.isEmpty()) {
312 const RoleInfoMap
* map
= rolesInfoMap(count
);
313 for (int i
= 0; i
< count
; ++i
) {
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
: m_groups
= timeRoleGroups(KFileItem::ModificationTime
); break;
332 case AccessTimeRole
: m_groups
= timeRoleGroups(KFileItem::AccessTime
); break;
333 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
334 case RatingRole
: m_groups
= ratingRoleGroups(); break;
335 default: m_groups
= genericStringRoleGroups(sortRole()); break;
338 #ifdef KFILEITEMMODEL_DEBUG
339 qCDebug(DolphinDebug
) << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
346 KFileItem
KFileItemModel::fileItem(int index
) const
348 if (index
>= 0 && index
< count()) {
349 return m_itemData
.at(index
)->item
;
355 KFileItem
KFileItemModel::fileItem(const QUrl
&url
) const
357 const int indexForUrl
= index(url
);
358 if (indexForUrl
>= 0) {
359 return m_itemData
.at(indexForUrl
)->item
;
364 int KFileItemModel::index(const KFileItem
& item
) const
366 return index(item
.url());
369 int KFileItemModel::index(const QUrl
& url
) const
371 const QUrl urlToFind
= url
.adjusted(QUrl::StripTrailingSlash
);
373 const int itemCount
= m_itemData
.count();
374 int itemsInHash
= m_items
.count();
376 int index
= m_items
.value(urlToFind
, -1);
377 while (index
< 0 && itemsInHash
< itemCount
) {
378 // Not all URLs are stored yet in m_items. We grow m_items until either
379 // urlToFind is found, or all URLs have been stored in m_items.
380 // Note that we do not add the URLs to m_items one by one, but in
381 // larger blocks. After each block, we check if urlToFind is in
382 // m_items. We could in principle compare urlToFind with each URL while
383 // we are going through m_itemData, but comparing two QUrls will,
384 // unlike calling qHash for the URLs, trigger a parsing of the URLs
385 // which costs both CPU cycles and memory.
386 const int blockSize
= 1000;
387 const int currentBlockEnd
= qMin(itemsInHash
+ blockSize
, itemCount
);
388 for (int i
= itemsInHash
; i
< currentBlockEnd
; ++i
) {
389 const QUrl nextUrl
= m_itemData
.at(i
)->item
.url();
390 m_items
.insert(nextUrl
, i
);
393 itemsInHash
= currentBlockEnd
;
394 index
= m_items
.value(urlToFind
, -1);
398 // The item could not be found, even though all items from m_itemData
399 // should be in m_items now. We print some diagnostic information which
400 // might help to find the cause of the problem, but only once. This
401 // prevents that obtaining and printing the debugging information
402 // wastes CPU cycles and floods the shell or .xsession-errors.
403 static bool printDebugInfo
= true;
405 if (m_items
.count() != m_itemData
.count() && printDebugInfo
) {
406 printDebugInfo
= false;
408 qCWarning(DolphinDebug
) << "The model is in an inconsistent state.";
409 qCWarning(DolphinDebug
) << "m_items.count() ==" << m_items
.count();
410 qCWarning(DolphinDebug
) << "m_itemData.count() ==" << m_itemData
.count();
412 // Check if there are multiple items with the same URL.
413 QMultiHash
<QUrl
, int> indexesForUrl
;
414 for (int i
= 0; i
< m_itemData
.count(); ++i
) {
415 indexesForUrl
.insert(m_itemData
.at(i
)->item
.url(), i
);
418 foreach (const QUrl
& url
, indexesForUrl
.uniqueKeys()) {
419 if (indexesForUrl
.count(url
) > 1) {
420 qCWarning(DolphinDebug
) << "Multiple items found with the URL" << url
;
422 auto it
= indexesForUrl
.find(url
);
423 while (it
!= indexesForUrl
.end() && it
.key() == url
) {
424 const ItemData
* data
= m_itemData
.at(it
.value());
425 qCWarning(DolphinDebug
) << "index" << it
.value() << ":" << data
->item
;
427 qCWarning(DolphinDebug
) << "parent" << data
->parent
->item
;
439 KFileItem
KFileItemModel::rootItem() const
441 return m_dirLister
->rootItem();
444 void KFileItemModel::clear()
449 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
451 if (m_roles
== roles
) {
455 const QSet
<QByteArray
> changedRoles
= (roles
- m_roles
) + (m_roles
- roles
);
459 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
460 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
461 if (supportedExpanding
&& !willSupportExpanding
) {
462 // No expanding is supported anymore. Take care to delete all items that have an expansion level
463 // that is not 0 (and hence are part of an expanded item).
464 removeExpandedItems();
471 QSetIterator
<QByteArray
> it(roles
);
472 while (it
.hasNext()) {
473 const QByteArray
& role
= it
.next();
474 m_requestRole
[typeForRole(role
)] = true;
478 // Update m_data with the changed requested roles
479 const int maxIndex
= count() - 1;
480 for (int i
= 0; i
<= maxIndex
; ++i
) {
481 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
, m_itemData
.at(i
)->parent
);
484 emit
itemsChanged(KItemRangeList() << KItemRange(0, count()), changedRoles
);
487 // Clear the 'values' of all filtered items. They will be re-populated with the
488 // correct roles the next time 'values' will be accessed via data(int).
489 QHash
<KFileItem
, ItemData
*>::iterator filteredIt
= m_filteredItems
.begin();
490 const QHash
<KFileItem
, ItemData
*>::iterator filteredEnd
= m_filteredItems
.end();
491 while (filteredIt
!= filteredEnd
) {
492 (*filteredIt
)->values
.clear();
497 QSet
<QByteArray
> KFileItemModel::roles() const
502 bool KFileItemModel::setExpanded(int index
, bool expanded
)
504 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
508 QHash
<QByteArray
, QVariant
> values
;
509 values
.insert(sharedValue("isExpanded"), expanded
);
510 if (!setData(index
, values
)) {
514 const KFileItem item
= m_itemData
.at(index
)->item
;
515 const QUrl url
= item
.url();
516 const QUrl targetUrl
= item
.targetUrl();
518 m_expandedDirs
.insert(targetUrl
, url
);
519 m_dirLister
->openUrl(url
, KDirLister::Keep
);
521 const QVariantList previouslyExpandedChildren
= m_itemData
.at(index
)->values
.value("previouslyExpandedChildren").value
<QVariantList
>();
522 foreach (const QVariant
& var
, previouslyExpandedChildren
) {
523 m_urlsToExpand
.insert(var
.toUrl());
526 // Note that there might be (indirect) children of the folder which is to be collapsed in
527 // m_pendingItemsToInsert. To prevent that they will be inserted into the model later,
528 // possibly without a parent, which might result in a crash, we insert all pending items
529 // right now. All new items which would be without a parent will then be removed.
530 dispatchPendingItemsToInsert();
532 // Check if the index of the collapsed folder has changed. If that is the case, then items
533 // were inserted before the collapsed folder, and its index needs to be updated.
534 if (m_itemData
.at(index
)->item
!= item
) {
535 index
= this->index(item
);
538 m_expandedDirs
.remove(targetUrl
);
539 m_dirLister
->stop(url
);
541 const int parentLevel
= expandedParentsCount(index
);
542 const int itemCount
= m_itemData
.count();
543 const int firstChildIndex
= index
+ 1;
545 QVariantList expandedChildren
;
547 int childIndex
= firstChildIndex
;
548 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
549 ItemData
* itemData
= m_itemData
.at(childIndex
);
550 if (itemData
->values
.value("isExpanded").toBool()) {
551 const QUrl targetUrl
= itemData
->item
.targetUrl();
552 const QUrl url
= itemData
->item
.url();
553 m_expandedDirs
.remove(targetUrl
);
554 m_dirLister
->stop(url
); // TODO: try to unit-test this, see https://bugs.kde.org/show_bug.cgi?id=332102#c11
555 expandedChildren
.append(targetUrl
);
559 const int childrenCount
= childIndex
- firstChildIndex
;
561 removeFilteredChildren(KItemRangeList() << KItemRange(index
, 1 + childrenCount
));
562 removeItems(KItemRangeList() << KItemRange(firstChildIndex
, childrenCount
), DeleteItemData
);
564 m_itemData
.at(index
)->values
.insert("previouslyExpandedChildren", expandedChildren
);
570 bool KFileItemModel::isExpanded(int index
) const
572 if (index
>= 0 && index
< count()) {
573 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
578 bool KFileItemModel::isExpandable(int index
) const
580 if (index
>= 0 && index
< count()) {
581 // Call data (instead of accessing m_itemData directly)
582 // to ensure that the value is initialized.
583 return data(index
).value("isExpandable").toBool();
588 int KFileItemModel::expandedParentsCount(int index
) const
590 if (index
>= 0 && index
< count()) {
591 return expandedParentsCount(m_itemData
.at(index
));
596 QSet
<QUrl
> KFileItemModel::expandedDirectories() const
599 const auto dirs
= m_expandedDirs
;
600 for (const auto &dir
: dirs
) {
606 void KFileItemModel::restoreExpandedDirectories(const QSet
<QUrl
> &urls
)
608 m_urlsToExpand
= urls
;
611 void KFileItemModel::expandParentDirectories(const QUrl
&url
)
613 const int pos
= m_dirLister
->url().path().length();
615 // Assure that each sub-path of the URL that should be
616 // expanded is added to m_urlsToExpand. KDirLister
617 // does not care whether the parent-URL has already been
619 QUrl urlToExpand
= m_dirLister
->url();
620 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator());
621 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
622 urlToExpand
.setPath(urlToExpand
.path() + '/' + subDirs
.at(i
));
623 m_urlsToExpand
.insert(urlToExpand
);
626 // KDirLister::open() must called at least once to trigger an initial
627 // loading. The pending URLs that must be restored are handled
628 // in slotCompleted().
629 QSetIterator
<QUrl
> it2(m_urlsToExpand
);
630 while (it2
.hasNext()) {
631 const int idx
= index(it2
.next());
632 if (idx
>= 0 && !isExpanded(idx
)) {
633 setExpanded(idx
, true);
639 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
641 if (m_filter
.pattern() != nameFilter
) {
642 dispatchPendingItemsToInsert();
643 m_filter
.setPattern(nameFilter
);
648 QString
KFileItemModel::nameFilter() const
650 return m_filter
.pattern();
653 void KFileItemModel::setMimeTypeFilters(const QStringList
& filters
)
655 if (m_filter
.mimeTypes() != filters
) {
656 dispatchPendingItemsToInsert();
657 m_filter
.setMimeTypes(filters
);
662 QStringList
KFileItemModel::mimeTypeFilters() const
664 return m_filter
.mimeTypes();
668 void KFileItemModel::applyFilters()
670 // Check which shown items from m_itemData must get
671 // hidden and hence moved to m_filteredItems.
672 QVector
<int> newFilteredIndexes
;
674 const int itemCount
= m_itemData
.count();
675 for (int index
= 0; index
< itemCount
; ++index
) {
676 ItemData
* itemData
= m_itemData
.at(index
);
678 // Only filter non-expanded items as child items may never
679 // exist without a parent item
680 if (!itemData
->values
.value("isExpanded").toBool()) {
681 const KFileItem item
= itemData
->item
;
682 if (!m_filter
.matches(item
)) {
683 newFilteredIndexes
.append(index
);
684 m_filteredItems
.insert(item
, itemData
);
689 const KItemRangeList removedRanges
= KItemRangeList::fromSortedContainer(newFilteredIndexes
);
690 removeItems(removedRanges
, KeepItemData
);
692 // Check which hidden items from m_filteredItems should
693 // get visible again and hence removed from m_filteredItems.
694 QList
<ItemData
*> newVisibleItems
;
696 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
697 while (it
!= m_filteredItems
.end()) {
698 if (m_filter
.matches(it
.key())) {
699 newVisibleItems
.append(it
.value());
700 it
= m_filteredItems
.erase(it
);
706 insertItems(newVisibleItems
);
709 void KFileItemModel::removeFilteredChildren(const KItemRangeList
& itemRanges
)
711 if (m_filteredItems
.isEmpty() || !m_requestRole
[ExpandedParentsCountRole
]) {
712 // There are either no filtered items, or it is not possible to expand
713 // folders -> there cannot be any filtered children.
717 QSet
<ItemData
*> parents
;
718 foreach (const KItemRange
& range
, itemRanges
) {
719 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
720 parents
.insert(m_itemData
.at(index
));
724 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
725 while (it
!= m_filteredItems
.end()) {
726 if (parents
.contains(it
.value()->parent
)) {
728 it
= m_filteredItems
.erase(it
);
735 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
737 static QList
<RoleInfo
> rolesInfo
;
738 if (rolesInfo
.isEmpty()) {
740 const RoleInfoMap
* map
= rolesInfoMap(count
);
741 for (int i
= 0; i
< count
; ++i
) {
742 if (map
[i
].roleType
!= NoRole
) {
744 info
.role
= map
[i
].role
;
745 info
.translation
= i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
);
746 if (map
[i
].groupTranslation
) {
747 info
.group
= i18nc(map
[i
].groupTranslationContext
, map
[i
].groupTranslation
);
749 // For top level roles, groupTranslation is 0. We must make sure that
750 // info.group is an empty string then because the code that generates
751 // menus tries to put the actions into sub menus otherwise.
752 info
.group
= QString();
754 info
.requiresBaloo
= map
[i
].requiresBaloo
;
755 info
.requiresIndexer
= map
[i
].requiresIndexer
;
756 rolesInfo
.append(info
);
764 void KFileItemModel::onGroupedSortingChanged(bool current
)
770 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
773 m_sortRole
= typeForRole(current
);
775 if (!m_requestRole
[m_sortRole
]) {
776 QSet
<QByteArray
> newRoles
= m_roles
;
784 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
791 void KFileItemModel::loadSortingSettings()
793 using Choice
= GeneralSettings::EnumSortingChoice
;
794 switch (GeneralSettings::sortingChoice()) {
795 case Choice::NaturalSorting
:
796 m_naturalSorting
= true;
797 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
799 case Choice::CaseSensitiveSorting
:
800 m_naturalSorting
= false;
801 m_collator
.setCaseSensitivity(Qt::CaseSensitive
);
803 case Choice::CaseInsensitiveSorting
:
804 m_naturalSorting
= false;
805 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
812 void KFileItemModel::resortAllItems()
814 m_resortAllItemsTimer
->stop();
816 const int itemCount
= count();
817 if (itemCount
<= 0) {
821 #ifdef KFILEITEMMODEL_DEBUG
824 qCDebug(DolphinDebug
) << "===========================================================";
825 qCDebug(DolphinDebug
) << "Resorting" << itemCount
<< "items";
828 // Remember the order of the current URLs so
829 // that it can be determined which indexes have
830 // been moved because of the resorting.
832 oldUrls
.reserve(itemCount
);
833 foreach (const ItemData
* itemData
, m_itemData
) {
834 oldUrls
.append(itemData
->item
.url());
838 m_items
.reserve(itemCount
);
841 sort(m_itemData
.begin(), m_itemData
.end());
842 for (int i
= 0; i
< itemCount
; ++i
) {
843 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
846 // Determine the first index that has been moved.
847 int firstMovedIndex
= 0;
848 while (firstMovedIndex
< itemCount
849 && firstMovedIndex
== m_items
.value(oldUrls
.at(firstMovedIndex
))) {
853 const bool itemsHaveMoved
= firstMovedIndex
< itemCount
;
854 if (itemsHaveMoved
) {
857 int lastMovedIndex
= itemCount
- 1;
858 while (lastMovedIndex
> firstMovedIndex
859 && lastMovedIndex
== m_items
.value(oldUrls
.at(lastMovedIndex
))) {
863 Q_ASSERT(firstMovedIndex
<= lastMovedIndex
);
865 // Create a list movedToIndexes, which has the property that
866 // movedToIndexes[i] is the new index of the item with the old index
867 // firstMovedIndex + i.
868 const int movedItemsCount
= lastMovedIndex
- firstMovedIndex
+ 1;
869 QList
<int> movedToIndexes
;
870 movedToIndexes
.reserve(movedItemsCount
);
871 for (int i
= firstMovedIndex
; i
<= lastMovedIndex
; ++i
) {
872 const int newIndex
= m_items
.value(oldUrls
.at(i
));
873 movedToIndexes
.append(newIndex
);
876 emit
itemsMoved(KItemRange(firstMovedIndex
, movedItemsCount
), movedToIndexes
);
877 } else if (groupedSorting()) {
878 // The groups might have changed even if the order of the items has not.
879 const QList
<QPair
<int, QVariant
> > oldGroups
= m_groups
;
881 if (groups() != oldGroups
) {
882 emit
groupsChanged();
886 #ifdef KFILEITEMMODEL_DEBUG
887 qCDebug(DolphinDebug
) << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
891 void KFileItemModel::slotCompleted()
893 dispatchPendingItemsToInsert();
895 if (!m_urlsToExpand
.isEmpty()) {
896 // Try to find a URL that can be expanded.
897 // Note that the parent folder must be expanded before any of its subfolders become visible.
898 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
899 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
900 foreach (const QUrl
& url
, m_urlsToExpand
) {
901 const int indexForUrl
= index(url
);
902 if (indexForUrl
>= 0) {
903 m_urlsToExpand
.remove(url
);
904 if (setExpanded(indexForUrl
, true)) {
905 // The dir lister has been triggered. This slot will be called
906 // again after the directory has been expanded.
912 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
913 // if these URLs have been deleted in the meantime.
914 m_urlsToExpand
.clear();
917 emit
directoryLoadingCompleted();
920 void KFileItemModel::slotCanceled()
922 m_maximumUpdateIntervalTimer
->stop();
923 dispatchPendingItemsToInsert();
925 emit
directoryLoadingCanceled();
928 void KFileItemModel::slotItemsAdded(const QUrl
&directoryUrl
, const KFileItemList
& items
)
930 Q_ASSERT(!items
.isEmpty());
933 if (m_expandedDirs
.contains(directoryUrl
)) {
934 parentUrl
= m_expandedDirs
.value(directoryUrl
);
936 parentUrl
= directoryUrl
.adjusted(QUrl::StripTrailingSlash
);
939 if (m_requestRole
[ExpandedParentsCountRole
]) {
940 // If the expanding of items is enabled, the call
941 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
942 // might result in emitting the same items twice due to the Keep-parameter.
943 // This case happens if an item gets expanded, collapsed and expanded again
944 // before the items could be loaded for the first expansion.
945 if (index(items
.first().url()) >= 0) {
946 // The items are already part of the model.
950 if (directoryUrl
!= directory()) {
951 // To be able to compare whether the new items may be inserted as children
952 // of a parent item the pending items must be added to the model first.
953 dispatchPendingItemsToInsert();
956 // KDirLister keeps the children of items that got expanded once even if
957 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
958 // checked whether the parent for new items is still expanded.
959 const int parentIndex
= index(parentUrl
);
960 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
961 // The parent is not expanded.
966 QList
<ItemData
*> itemDataList
= createItemDataList(parentUrl
, items
);
968 if (!m_filter
.hasSetFilters()) {
969 m_pendingItemsToInsert
.append(itemDataList
);
971 // The name or type filter is active. Hide filtered items
972 // before inserting them into the model and remember
973 // the filtered items in m_filteredItems.
974 foreach (ItemData
* itemData
, itemDataList
) {
975 if (m_filter
.matches(itemData
->item
)) {
976 m_pendingItemsToInsert
.append(itemData
);
978 m_filteredItems
.insert(itemData
->item
, itemData
);
983 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer
->isActive()) {
984 // Assure that items get dispatched if no completed() or canceled() signal is
985 // emitted during the maximum update interval.
986 m_maximumUpdateIntervalTimer
->start();
990 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
992 dispatchPendingItemsToInsert();
994 QVector
<int> indexesToRemove
;
995 indexesToRemove
.reserve(items
.count());
997 foreach (const KFileItem
& item
, items
) {
998 const int indexForItem
= index(item
);
999 if (indexForItem
>= 0) {
1000 indexesToRemove
.append(indexForItem
);
1002 // Probably the item has been filtered.
1003 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(item
);
1004 if (it
!= m_filteredItems
.end()) {
1006 m_filteredItems
.erase(it
);
1011 std::sort(indexesToRemove
.begin(), indexesToRemove
.end());
1013 if (m_requestRole
[ExpandedParentsCountRole
] && !m_expandedDirs
.isEmpty()) {
1014 // Assure that removing a parent item also results in removing all children
1015 QVector
<int> indexesToRemoveWithChildren
;
1016 indexesToRemoveWithChildren
.reserve(m_itemData
.count());
1018 const int itemCount
= m_itemData
.count();
1019 foreach (int index
, indexesToRemove
) {
1020 indexesToRemoveWithChildren
.append(index
);
1022 const int parentLevel
= expandedParentsCount(index
);
1023 int childIndex
= index
+ 1;
1024 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
1025 indexesToRemoveWithChildren
.append(childIndex
);
1030 indexesToRemove
= indexesToRemoveWithChildren
;
1033 const KItemRangeList itemRanges
= KItemRangeList::fromSortedContainer(indexesToRemove
);
1034 removeFilteredChildren(itemRanges
);
1035 removeItems(itemRanges
, DeleteItemData
);
1038 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
1040 Q_ASSERT(!items
.isEmpty());
1041 #ifdef KFILEITEMMODEL_DEBUG
1042 qCDebug(DolphinDebug
) << "Refreshing" << items
.count() << "items";
1045 // Get the indexes of all items that have been refreshed
1047 indexes
.reserve(items
.count());
1049 QSet
<QByteArray
> changedRoles
;
1051 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
1052 while (it
.hasNext()) {
1053 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
1054 const KFileItem
& oldItem
= itemPair
.first
;
1055 const KFileItem
& newItem
= itemPair
.second
;
1056 const int indexForItem
= index(oldItem
);
1057 if (indexForItem
>= 0) {
1058 m_itemData
[indexForItem
]->item
= newItem
;
1060 // Keep old values as long as possible if they could not retrieved synchronously yet.
1061 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
1062 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
, m_itemData
.at(indexForItem
)->parent
));
1063 QHash
<QByteArray
, QVariant
>& values
= m_itemData
[indexForItem
]->values
;
1064 while (it
.hasNext()) {
1066 const QByteArray
& role
= it
.key();
1067 if (values
.value(role
) != it
.value()) {
1068 values
.insert(role
, it
.value());
1069 changedRoles
.insert(role
);
1073 m_items
.remove(oldItem
.url());
1074 m_items
.insert(newItem
.url(), indexForItem
);
1075 indexes
.append(indexForItem
);
1077 // Check if 'oldItem' is one of the filtered items.
1078 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(oldItem
);
1079 if (it
!= m_filteredItems
.end()) {
1080 ItemData
* itemData
= it
.value();
1081 itemData
->item
= newItem
;
1083 // The data stored in 'values' might have changed. Therefore, we clear
1084 // 'values' and re-populate it the next time it is requested via data(int).
1085 itemData
->values
.clear();
1087 m_filteredItems
.erase(it
);
1088 m_filteredItems
.insert(newItem
, itemData
);
1093 // If the changed items have been created recently, they might not be in m_items yet.
1094 // In that case, the list 'indexes' might be empty.
1095 if (indexes
.isEmpty()) {
1099 // Extract the item-ranges out of the changed indexes
1101 const KItemRangeList itemRangeList
= KItemRangeList::fromSortedContainer(indexes
);
1102 emitItemsChangedAndTriggerResorting(itemRangeList
, changedRoles
);
1105 void KFileItemModel::slotClear()
1107 #ifdef KFILEITEMMODEL_DEBUG
1108 qCDebug(DolphinDebug
) << "Clearing all items";
1111 qDeleteAll(m_filteredItems
);
1112 m_filteredItems
.clear();
1115 m_maximumUpdateIntervalTimer
->stop();
1116 m_resortAllItemsTimer
->stop();
1118 qDeleteAll(m_pendingItemsToInsert
);
1119 m_pendingItemsToInsert
.clear();
1121 const int removedCount
= m_itemData
.count();
1122 if (removedCount
> 0) {
1123 qDeleteAll(m_itemData
);
1126 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
1129 m_expandedDirs
.clear();
1132 void KFileItemModel::slotSortingChoiceChanged()
1134 loadSortingSettings();
1138 void KFileItemModel::dispatchPendingItemsToInsert()
1140 if (!m_pendingItemsToInsert
.isEmpty()) {
1141 insertItems(m_pendingItemsToInsert
);
1142 m_pendingItemsToInsert
.clear();
1146 void KFileItemModel::insertItems(QList
<ItemData
*>& newItems
)
1148 if (newItems
.isEmpty()) {
1152 #ifdef KFILEITEMMODEL_DEBUG
1153 QElapsedTimer timer
;
1155 qCDebug(DolphinDebug
) << "===========================================================";
1156 qCDebug(DolphinDebug
) << "Inserting" << newItems
.count() << "items";
1160 prepareItemsForSorting(newItems
);
1162 if (m_sortRole
== NameRole
&& m_naturalSorting
) {
1163 // Natural sorting of items can be very slow. However, it becomes much
1164 // faster if the input sequence is already mostly sorted. Therefore, we
1165 // first sort 'newItems' according to the QStrings returned by
1166 // KFileItem::text() using QString::operator<(), which is quite fast.
1167 parallelMergeSort(newItems
.begin(), newItems
.end(), nameLessThan
, QThread::idealThreadCount());
1170 sort(newItems
.begin(), newItems
.end());
1172 #ifdef KFILEITEMMODEL_DEBUG
1173 qCDebug(DolphinDebug
) << "[TIME] Sorting:" << timer
.elapsed();
1176 KItemRangeList itemRanges
;
1177 const int existingItemCount
= m_itemData
.count();
1178 const int newItemCount
= newItems
.count();
1179 const int totalItemCount
= existingItemCount
+ newItemCount
;
1181 if (existingItemCount
== 0) {
1182 // Optimization for the common special case that there are no
1183 // items in the model yet. Happens, e.g., when entering a folder.
1184 m_itemData
= newItems
;
1185 itemRanges
<< KItemRange(0, newItemCount
);
1187 m_itemData
.reserve(totalItemCount
);
1188 for (int i
= existingItemCount
; i
< totalItemCount
; ++i
) {
1189 m_itemData
.append(0);
1192 // We build the new list m_itemData in reverse order to minimize
1193 // the number of moves and guarantee O(N) complexity.
1194 int targetIndex
= totalItemCount
- 1;
1195 int sourceIndexExistingItems
= existingItemCount
- 1;
1196 int sourceIndexNewItems
= newItemCount
- 1;
1200 while (sourceIndexNewItems
>= 0) {
1201 ItemData
* newItem
= newItems
.at(sourceIndexNewItems
);
1202 if (sourceIndexExistingItems
>= 0 && lessThan(newItem
, m_itemData
.at(sourceIndexExistingItems
), m_collator
)) {
1203 // Move an existing item to its new position. If any new items
1204 // are behind it, push the item range to itemRanges.
1205 if (rangeCount
> 0) {
1206 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1210 m_itemData
[targetIndex
] = m_itemData
.at(sourceIndexExistingItems
);
1211 --sourceIndexExistingItems
;
1213 // Insert a new item into the list.
1215 m_itemData
[targetIndex
] = newItem
;
1216 --sourceIndexNewItems
;
1221 // Push the final item range to itemRanges.
1222 if (rangeCount
> 0) {
1223 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1226 // Note that itemRanges is still sorted in reverse order.
1227 std::reverse(itemRanges
.begin(), itemRanges
.end());
1230 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1231 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1234 emit
itemsInserted(itemRanges
);
1236 #ifdef KFILEITEMMODEL_DEBUG
1237 qCDebug(DolphinDebug
) << "[TIME] Inserting of" << newItems
.count() << "items:" << timer
.elapsed();
1241 void KFileItemModel::removeItems(const KItemRangeList
& itemRanges
, RemoveItemsBehavior behavior
)
1243 if (itemRanges
.isEmpty()) {
1249 // Step 1: Remove the items from m_itemData, and free the ItemData.
1250 int removedItemsCount
= 0;
1251 foreach (const KItemRange
& range
, itemRanges
) {
1252 removedItemsCount
+= range
.count
;
1254 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
1255 if (behavior
== DeleteItemData
) {
1256 delete m_itemData
.at(index
);
1259 m_itemData
[index
] = 0;
1263 // Step 2: Remove the ItemData pointers from the list m_itemData.
1264 int target
= itemRanges
.at(0).index
;
1265 int source
= itemRanges
.at(0).index
+ itemRanges
.at(0).count
;
1268 const int oldItemDataCount
= m_itemData
.count();
1269 while (source
< oldItemDataCount
) {
1270 m_itemData
[target
] = m_itemData
[source
];
1274 if (nextRange
< itemRanges
.count() && source
== itemRanges
.at(nextRange
).index
) {
1275 // Skip the items in the next removed range.
1276 source
+= itemRanges
.at(nextRange
).count
;
1281 m_itemData
.erase(m_itemData
.end() - removedItemsCount
, m_itemData
.end());
1283 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1284 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1287 emit
itemsRemoved(itemRanges
);
1290 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const QUrl
& parentUrl
, const KFileItemList
& items
) const
1292 if (m_sortRole
== TypeRole
) {
1293 // Try to resolve the MIME-types synchronously to prevent a reordering of
1294 // the items when sorting by type (per default MIME-types are resolved
1295 // asynchronously by KFileItemModelRolesUpdater).
1296 determineMimeTypes(items
, 200);
1299 const int parentIndex
= index(parentUrl
);
1300 ItemData
* parentItem
= parentIndex
< 0 ? 0 : m_itemData
.at(parentIndex
);
1302 QList
<ItemData
*> itemDataList
;
1303 itemDataList
.reserve(items
.count());
1305 foreach (const KFileItem
& item
, items
) {
1306 ItemData
* itemData
= new ItemData();
1307 itemData
->item
= item
;
1308 itemData
->parent
= parentItem
;
1309 itemDataList
.append(itemData
);
1312 return itemDataList
;
1315 void KFileItemModel::prepareItemsForSorting(QList
<ItemData
*>& itemDataList
)
1317 switch (m_sortRole
) {
1318 case PermissionsRole
:
1321 case DestinationRole
:
1323 // These roles can be determined with retrieveData, and they have to be stored
1324 // in the QHash "values" for the sorting.
1325 foreach (ItemData
* itemData
, itemDataList
) {
1326 if (itemData
->values
.isEmpty()) {
1327 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1333 // At least store the data including the file type for items with known MIME type.
1334 foreach (ItemData
* itemData
, itemDataList
) {
1335 if (itemData
->values
.isEmpty()) {
1336 const KFileItem item
= itemData
->item
;
1337 if (item
.isDir() || item
.isMimeTypeKnown()) {
1338 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1345 // The other roles are either resolved by KFileItemModelRolesUpdater
1346 // (this includes the SizeRole for directories), or they do not need
1347 // to be stored in the QHash "values" for sorting because the data can
1348 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1354 int KFileItemModel::expandedParentsCount(const ItemData
* data
)
1356 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1357 // if the corresponding item is expanded, and it is not a top-level item.
1358 const ItemData
* parent
= data
->parent
;
1360 if (parent
->parent
) {
1361 Q_ASSERT(parent
->values
.contains("expandedParentsCount"));
1362 return parent
->values
.value("expandedParentsCount").toInt() + 1;
1371 void KFileItemModel::removeExpandedItems()
1373 QVector
<int> indexesToRemove
;
1375 const int maxIndex
= m_itemData
.count() - 1;
1376 for (int i
= 0; i
<= maxIndex
; ++i
) {
1377 const ItemData
* itemData
= m_itemData
.at(i
);
1378 if (itemData
->parent
) {
1379 indexesToRemove
.append(i
);
1383 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove
), DeleteItemData
);
1384 m_expandedDirs
.clear();
1386 // Also remove all filtered items which have a parent.
1387 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
1388 const QHash
<KFileItem
, ItemData
*>::iterator end
= m_filteredItems
.end();
1391 if (it
.value()->parent
) {
1393 it
= m_filteredItems
.erase(it
);
1400 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList
& itemRanges
, const QSet
<QByteArray
>& changedRoles
)
1402 emit
itemsChanged(itemRanges
, changedRoles
);
1404 // Trigger a resorting if necessary. Note that this can happen even if the sort
1405 // role has not changed at all because the file name can be used as a fallback.
1406 if (changedRoles
.contains(sortRole()) || changedRoles
.contains(roleForType(NameRole
))) {
1407 foreach (const KItemRange
& range
, itemRanges
) {
1408 bool needsResorting
= false;
1410 const int first
= range
.index
;
1411 const int last
= range
.index
+ range
.count
- 1;
1413 // Resorting the model is necessary if
1414 // (a) The first item in the range is "lessThan" its predecessor,
1415 // (b) the successor of the last item is "lessThan" the last item, or
1416 // (c) the internal order of the items in the range is incorrect.
1418 && lessThan(m_itemData
.at(first
), m_itemData
.at(first
- 1), m_collator
)) {
1419 needsResorting
= true;
1420 } else if (last
< count() - 1
1421 && lessThan(m_itemData
.at(last
+ 1), m_itemData
.at(last
), m_collator
)) {
1422 needsResorting
= true;
1424 for (int index
= first
; index
< last
; ++index
) {
1425 if (lessThan(m_itemData
.at(index
+ 1), m_itemData
.at(index
), m_collator
)) {
1426 needsResorting
= true;
1432 if (needsResorting
) {
1433 m_resortAllItemsTimer
->start();
1439 if (groupedSorting() && changedRoles
.contains(sortRole())) {
1440 // The position is still correct, but the groups might have changed
1441 // if the changed item is either the first or the last item in a
1443 // In principle, we could try to find out if the item really is the
1444 // first or last one in its group and then update the groups
1445 // (possibly with a delayed timer to make sure that we don't
1446 // re-calculate the groups very often if items are updated one by
1447 // one), but starting m_resortAllItemsTimer is easier.
1448 m_resortAllItemsTimer
->start();
1452 void KFileItemModel::resetRoles()
1454 for (int i
= 0; i
< RolesCount
; ++i
) {
1455 m_requestRole
[i
] = false;
1459 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1461 static QHash
<QByteArray
, RoleType
> roles
;
1462 if (roles
.isEmpty()) {
1463 // Insert user visible roles that can be accessed with
1464 // KFileItemModel::roleInformation()
1466 const RoleInfoMap
* map
= rolesInfoMap(count
);
1467 for (int i
= 0; i
< count
; ++i
) {
1468 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1471 // Insert internal roles (take care to synchronize the implementation
1472 // with KFileItemModel::roleForType() in case if a change is done).
1473 roles
.insert("isDir", IsDirRole
);
1474 roles
.insert("isLink", IsLinkRole
);
1475 roles
.insert("isExpanded", IsExpandedRole
);
1476 roles
.insert("isExpandable", IsExpandableRole
);
1477 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1479 Q_ASSERT(roles
.count() == RolesCount
);
1482 return roles
.value(role
, NoRole
);
1485 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1487 static QHash
<RoleType
, QByteArray
> roles
;
1488 if (roles
.isEmpty()) {
1489 // Insert user visible roles that can be accessed with
1490 // KFileItemModel::roleInformation()
1492 const RoleInfoMap
* map
= rolesInfoMap(count
);
1493 for (int i
= 0; i
< count
; ++i
) {
1494 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1497 // Insert internal roles (take care to synchronize the implementation
1498 // with KFileItemModel::typeForRole() in case if a change is done).
1499 roles
.insert(IsDirRole
, "isDir");
1500 roles
.insert(IsLinkRole
, "isLink");
1501 roles
.insert(IsExpandedRole
, "isExpanded");
1502 roles
.insert(IsExpandableRole
, "isExpandable");
1503 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1505 Q_ASSERT(roles
.count() == RolesCount
);
1508 return roles
.value(roleType
);
1511 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
, const ItemData
* parent
) const
1513 // It is important to insert only roles that are fast to retrieve. E.g.
1514 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1515 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1516 QHash
<QByteArray
, QVariant
> data
;
1517 data
.insert(sharedValue("url"), item
.url());
1519 const bool isDir
= item
.isDir();
1520 if (m_requestRole
[IsDirRole
] && isDir
) {
1521 data
.insert(sharedValue("isDir"), true);
1524 if (m_requestRole
[IsLinkRole
] && item
.isLink()) {
1525 data
.insert(sharedValue("isLink"), true);
1528 if (m_requestRole
[NameRole
]) {
1529 data
.insert(sharedValue("text"), item
.text());
1532 if (m_requestRole
[SizeRole
] && !isDir
) {
1533 data
.insert(sharedValue("size"), item
.size());
1536 if (m_requestRole
[ModificationTimeRole
]) {
1537 // Don't use KFileItem::timeString() as this is too expensive when
1538 // having several thousands of items. Instead the formatting of the
1539 // date-time will be done on-demand by the view when the date will be shown.
1540 const QDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
1541 data
.insert(sharedValue("modificationtime"), dateTime
);
1544 if (m_requestRole
[AccessTimeRole
]) {
1545 // Don't use KFileItem::timeString() as this is too expensive when
1546 // having several thousands of items. Instead the formatting of the
1547 // date-time will be done on-demand by the view when the date will be shown.
1548 const QDateTime dateTime
= item
.time(KFileItem::AccessTime
);
1549 data
.insert(sharedValue("accesstime"), dateTime
);
1552 if (m_requestRole
[PermissionsRole
]) {
1553 data
.insert(sharedValue("permissions"), item
.permissionsString());
1556 if (m_requestRole
[OwnerRole
]) {
1557 data
.insert(sharedValue("owner"), item
.user());
1560 if (m_requestRole
[GroupRole
]) {
1561 data
.insert(sharedValue("group"), item
.group());
1564 if (m_requestRole
[DestinationRole
]) {
1565 QString destination
= item
.linkDest();
1566 if (destination
.isEmpty()) {
1567 destination
= QStringLiteral("-");
1569 data
.insert(sharedValue("destination"), destination
);
1572 if (m_requestRole
[PathRole
]) {
1574 if (item
.url().scheme() == QLatin1String("trash")) {
1575 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1577 // For performance reasons cache the home-path in a static QString
1578 // (see QDir::homePath() for more details)
1579 static QString homePath
;
1580 if (homePath
.isEmpty()) {
1581 homePath
= QDir::homePath();
1584 path
= item
.localPath();
1585 if (path
.startsWith(homePath
)) {
1586 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1590 const int index
= path
.lastIndexOf(item
.text());
1591 path
= path
.mid(0, index
- 1);
1592 data
.insert(sharedValue("path"), path
);
1595 if (m_requestRole
[IsExpandableRole
] && isDir
) {
1596 data
.insert(sharedValue("isExpandable"), true);
1599 if (m_requestRole
[ExpandedParentsCountRole
]) {
1601 const int level
= expandedParentsCount(parent
) + 1;
1602 data
.insert(sharedValue("expandedParentsCount"), level
);
1606 if (item
.isMimeTypeKnown()) {
1607 data
.insert(sharedValue("iconName"), item
.iconName());
1609 if (m_requestRole
[TypeRole
]) {
1610 data
.insert(sharedValue("type"), item
.mimeComment());
1612 } else if (m_requestRole
[TypeRole
] && isDir
) {
1613 static const QString folderMimeType
= item
.mimeComment();
1614 data
.insert(sharedValue("type"), folderMimeType
);
1620 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const
1624 if (a
->parent
!= b
->parent
) {
1625 const int expansionLevelA
= expandedParentsCount(a
);
1626 const int expansionLevelB
= expandedParentsCount(b
);
1628 // If b has a higher expansion level than a, check if a is a parent
1629 // of b, and make sure that both expansion levels are equal otherwise.
1630 for (int i
= expansionLevelB
; i
> expansionLevelA
; --i
) {
1631 if (b
->parent
== a
) {
1637 // If a has a higher expansion level than a, check if b is a parent
1638 // of a, and make sure that both expansion levels are equal otherwise.
1639 for (int i
= expansionLevelA
; i
> expansionLevelB
; --i
) {
1640 if (a
->parent
== b
) {
1646 Q_ASSERT(expandedParentsCount(a
) == expandedParentsCount(b
));
1648 // Compare the last parents of a and b which are different.
1649 while (a
->parent
!= b
->parent
) {
1655 if (m_sortDirsFirst
|| m_sortRole
== SizeRole
) {
1656 const bool isDirA
= a
->item
.isDir();
1657 const bool isDirB
= b
->item
.isDir();
1658 if (isDirA
&& !isDirB
) {
1660 } else if (!isDirA
&& isDirB
) {
1665 result
= sortRoleCompare(a
, b
, collator
);
1667 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1671 * Helper class for KFileItemModel::sort().
1673 class KFileItemModelLessThan
1676 KFileItemModelLessThan(const KFileItemModel
* model
, const QCollator
& collator
) :
1678 m_collator(collator
)
1682 KFileItemModelLessThan(const KFileItemModelLessThan
& other
) :
1683 m_model(other
.m_model
),
1686 m_collator
.setCaseSensitivity(other
.m_collator
.caseSensitivity());
1687 m_collator
.setIgnorePunctuation(other
.m_collator
.ignorePunctuation());
1688 m_collator
.setLocale(other
.m_collator
.locale());
1689 m_collator
.setNumericMode(other
.m_collator
.numericMode());
1692 ~KFileItemModelLessThan() = default;
1693 //We do not delete m_model as the pointer was passed from outside ant it will be deleted elsewhere.
1695 KFileItemModelLessThan
& operator=(const KFileItemModelLessThan
& other
)
1697 m_model
= other
.m_model
;
1698 m_collator
= other
.m_collator
;
1702 bool operator()(const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
) const
1704 return m_model
->lessThan(a
, b
, m_collator
);
1708 const KFileItemModel
* m_model
;
1709 QCollator m_collator
;
1712 void KFileItemModel::sort(QList
<KFileItemModel::ItemData
*>::iterator begin
,
1713 QList
<KFileItemModel::ItemData
*>::iterator end
) const
1715 KFileItemModelLessThan
lessThan(this, m_collator
);
1717 if (m_sortRole
== NameRole
) {
1718 // Sorting by name can be expensive, in particular if natural sorting is
1719 // enabled. Use all CPU cores to speed up the sorting process.
1720 static const int numberOfThreads
= QThread::idealThreadCount();
1721 parallelMergeSort(begin
, end
, lessThan
, numberOfThreads
);
1723 // Sorting by other roles is quite fast. Use only one thread to prevent
1724 // problems caused by non-reentrant comparison functions, see
1725 // https://bugs.kde.org/show_bug.cgi?id=312679
1726 mergeSort(begin
, end
, lessThan
);
1730 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const
1732 const KFileItem
& itemA
= a
->item
;
1733 const KFileItem
& itemB
= b
->item
;
1737 switch (m_sortRole
) {
1739 // The name role is handled as default fallback after the switch
1743 if (itemA
.isDir()) {
1744 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1745 Q_ASSERT(itemB
.isDir());
1747 const QVariant valueA
= a
->values
.value("size");
1748 const QVariant valueB
= b
->values
.value("size");
1749 if (valueA
.isNull() && valueB
.isNull()) {
1751 } else if (valueA
.isNull()) {
1753 } else if (valueB
.isNull()) {
1756 result
= valueA
.toInt() - valueB
.toInt();
1759 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1760 Q_ASSERT(!itemB
.isDir());
1761 const KIO::filesize_t sizeA
= itemA
.size();
1762 const KIO::filesize_t sizeB
= itemB
.size();
1763 if (sizeA
> sizeB
) {
1765 } else if (sizeA
< sizeB
) {
1774 case ModificationTimeRole
: {
1775 const QDateTime dateTimeA
= itemA
.time(KFileItem::ModificationTime
);
1776 const QDateTime dateTimeB
= itemB
.time(KFileItem::ModificationTime
);
1777 if (dateTimeA
< dateTimeB
) {
1779 } else if (dateTimeA
> dateTimeB
) {
1786 result
= a
->values
.value("rating").toInt() - b
->values
.value("rating").toInt();
1790 case ImageSizeRole
: {
1791 // Alway use a natural comparing to interpret the numbers of a string like
1792 // "1600 x 1200" for having a correct sorting.
1793 result
= collator
.compare(a
->values
.value("imageSize").toString(),
1794 b
->values
.value("imageSize").toString());
1799 const QByteArray role
= roleForType(m_sortRole
);
1800 result
= QString::compare(a
->values
.value(role
).toString(),
1801 b
->values
.value(role
).toString());
1808 // The current sort role was sufficient to define an order
1812 // Fallback #1: Compare the text of the items
1813 result
= stringCompare(itemA
.text(), itemB
.text(), collator
);
1818 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1819 result
= stringCompare(itemA
.name(), itemB
.name(), collator
);
1824 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1825 // equal. In this case a comparison of the URL is done which is unique in all cases
1826 // within KDirLister.
1827 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1830 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
, const QCollator
& collator
) const
1832 if (m_naturalSorting
) {
1833 return collator
.compare(a
, b
);
1836 const int result
= QString::compare(a
, b
, collator
.caseSensitivity());
1837 if (result
!= 0 || collator
.caseSensitivity() == Qt::CaseSensitive
) {
1838 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1839 // comparison, still a deterministic sort order is required. A case sensitive
1840 // comparison is done as fallback.
1844 return QString::compare(a
, b
, Qt::CaseSensitive
);
1847 bool KFileItemModel::useMaximumUpdateInterval() const
1849 return !m_dirLister
->url().isLocalFile();
1852 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1854 Q_ASSERT(!m_itemData
.isEmpty());
1856 const int maxIndex
= count() - 1;
1857 QList
<QPair
<int, QVariant
> > groups
;
1861 for (int i
= 0; i
<= maxIndex
; ++i
) {
1862 if (isChildItem(i
)) {
1866 const QString name
= m_itemData
.at(i
)->item
.text();
1868 // Use the first character of the name as group indication
1869 QChar newFirstChar
= name
.at(0).toUpper();
1870 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1871 newFirstChar
= name
.at(1).toUpper();
1874 if (firstChar
!= newFirstChar
) {
1875 QString newGroupValue
;
1876 if (newFirstChar
.isLetter()) {
1877 // Try to find a matching group in the range 'A' to 'Z'.
1878 static std::vector
<QChar
> lettersAtoZ
;
1879 lettersAtoZ
.reserve('Z' - 'A' + 1);
1880 if (lettersAtoZ
.empty()) {
1881 for (char c
= 'A'; c
<= 'Z'; ++c
) {
1882 lettersAtoZ
.push_back(QLatin1Char(c
));
1886 auto localeAwareLessThan
= [this](QChar c1
, QChar c2
) -> bool {
1887 return m_collator
.compare(c1
, c2
) < 0;
1890 std::vector
<QChar
>::iterator it
= std::lower_bound(lettersAtoZ
.begin(), lettersAtoZ
.end(), newFirstChar
, localeAwareLessThan
);
1891 if (it
!= lettersAtoZ
.end()) {
1892 if (localeAwareLessThan(newFirstChar
, *it
) && it
!= lettersAtoZ
.begin()) {
1893 // newFirstChar belongs to the group preceding *it.
1894 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
1897 newGroupValue
= *it
;
1899 newGroupValue
= newFirstChar
;
1901 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
1902 // Apply group '0 - 9' for any name that starts with a digit
1903 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
1905 newGroupValue
= i18nc("@title:group", "Others");
1908 if (newGroupValue
!= groupValue
) {
1909 groupValue
= newGroupValue
;
1910 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1913 firstChar
= newFirstChar
;
1919 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
1921 Q_ASSERT(!m_itemData
.isEmpty());
1923 const int maxIndex
= count() - 1;
1924 QList
<QPair
<int, QVariant
> > groups
;
1927 for (int i
= 0; i
<= maxIndex
; ++i
) {
1928 if (isChildItem(i
)) {
1932 const KFileItem
& item
= m_itemData
.at(i
)->item
;
1933 const KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
1934 QString newGroupValue
;
1935 if (!item
.isNull() && item
.isDir()) {
1936 newGroupValue
= i18nc("@title:group Size", "Folders");
1937 } else if (fileSize
< 5 * 1024 * 1024) {
1938 newGroupValue
= i18nc("@title:group Size", "Small");
1939 } else if (fileSize
< 10 * 1024 * 1024) {
1940 newGroupValue
= i18nc("@title:group Size", "Medium");
1942 newGroupValue
= i18nc("@title:group Size", "Big");
1945 if (newGroupValue
!= groupValue
) {
1946 groupValue
= newGroupValue
;
1947 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1954 QList
<QPair
<int, QVariant
> > KFileItemModel::timeRoleGroups(KFileItem::FileTimes which
) const
1956 Q_ASSERT(!m_itemData
.isEmpty());
1958 const int maxIndex
= count() - 1;
1959 QList
<QPair
<int, QVariant
> > groups
;
1961 const QDate currentDate
= QDate::currentDate();
1963 QDate previousFileDate
;
1965 for (int i
= 0; i
<= maxIndex
; ++i
) {
1966 if (isChildItem(i
)) {
1970 const QDateTime fileTime
= m_itemData
.at(i
)->item
.time(which
);
1971 const QDate fileDate
= fileTime
.date();
1972 if (fileDate
== previousFileDate
) {
1973 // The current item is in the same group as the previous item
1976 previousFileDate
= fileDate
;
1978 const int daysDistance
= fileDate
.daysTo(currentDate
);
1980 QString newGroupValue
;
1981 if (currentDate
.year() == fileDate
.year() &&
1982 currentDate
.month() == fileDate
.month()) {
1984 switch (daysDistance
/ 7) {
1986 switch (daysDistance
) {
1987 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
1988 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
1990 newGroupValue
= fileTime
.toString(
1991 i18nc("@title:group Date: The week day name: dddd", "dddd"));
1992 newGroupValue
= i18nc("Can be used to script translation of \"dddd\""
1993 "with context @title:group Date", "%1", newGroupValue
);
1997 newGroupValue
= i18nc("@title:group Date", "One Week Ago");
2000 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
2003 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
2007 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
2013 const QDate lastMonthDate
= currentDate
.addMonths(-1);
2014 if (lastMonthDate
.year() == fileDate
.year() &&
2015 lastMonthDate
.month() == fileDate
.month()) {
2017 if (daysDistance
== 1) {
2018 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: "
2019 "MMMM is full month name in current locale, and yyyy is "
2020 "full year number", "'Yesterday' (MMMM, yyyy)"));
2021 newGroupValue
= i18nc("Can be used to script translation of "
2022 "\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date",
2023 "%1", newGroupValue
);
2024 } else if (daysDistance
<= 7) {
2025 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: "
2026 "The week day name: dddd, MMMM is full month name "
2027 "in current locale, and yyyy is full year number",
2028 "dddd (MMMM, yyyy)"));
2029 newGroupValue
= i18nc("Can be used to script translation of "
2030 "\"dddd (MMMM, yyyy)\" with context @title:group Date",
2031 "%1", newGroupValue
);
2032 } else if (daysDistance
<= 7 * 2) {
2033 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: "
2034 "MMMM is full month name in current locale, and yyyy is "
2035 "full year number", "'One Week Ago' (MMMM, yyyy)"));
2036 newGroupValue
= i18nc("Can be used to script translation of "
2037 "\"'One Week Ago' (MMMM, yyyy)\" with context @title:group Date",
2038 "%1", newGroupValue
);
2039 } else if (daysDistance
<= 7 * 3) {
2040 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: "
2041 "MMMM is full month name in current locale, and yyyy is "
2042 "full year number", "'Two Weeks Ago' (MMMM, yyyy)"));
2043 newGroupValue
= i18nc("Can be used to script translation of "
2044 "\"'Two Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2045 "%1", newGroupValue
);
2046 } else if (daysDistance
<= 7 * 4) {
2047 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: "
2048 "MMMM is full month name in current locale, and yyyy is "
2049 "full year number", "'Three Weeks Ago' (MMMM, yyyy)"));
2050 newGroupValue
= i18nc("Can be used to script translation of "
2051 "\"'Three Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2052 "%1", newGroupValue
);
2054 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: "
2055 "MMMM is full month name in current locale, and yyyy is "
2056 "full year number", "'Earlier on' MMMM, yyyy"));
2057 newGroupValue
= i18nc("Can be used to script translation of "
2058 "\"'Earlier on' MMMM, yyyy\" with context @title:group Date",
2059 "%1", newGroupValue
);
2062 newGroupValue
= fileTime
.toString(i18nc("@title:group "
2063 "The month and year: MMMM is full month name in current locale, "
2064 "and yyyy is full year number", "MMMM, yyyy"));
2065 newGroupValue
= i18nc("Can be used to script translation of "
2066 "\"MMMM, yyyy\" with context @title:group Date",
2067 "%1", newGroupValue
);
2071 if (newGroupValue
!= groupValue
) {
2072 groupValue
= newGroupValue
;
2073 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2080 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
2082 Q_ASSERT(!m_itemData
.isEmpty());
2084 const int maxIndex
= count() - 1;
2085 QList
<QPair
<int, QVariant
> > groups
;
2087 QString permissionsString
;
2089 for (int i
= 0; i
<= maxIndex
; ++i
) {
2090 if (isChildItem(i
)) {
2094 const ItemData
* itemData
= m_itemData
.at(i
);
2095 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
2096 if (newPermissionsString
== permissionsString
) {
2099 permissionsString
= newPermissionsString
;
2101 const QFileInfo
info(itemData
->item
.url().toLocalFile());
2105 if (info
.permission(QFile::ReadUser
)) {
2106 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2108 if (info
.permission(QFile::WriteUser
)) {
2109 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2111 if (info
.permission(QFile::ExeUser
)) {
2112 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2114 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
2118 if (info
.permission(QFile::ReadGroup
)) {
2119 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2121 if (info
.permission(QFile::WriteGroup
)) {
2122 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2124 if (info
.permission(QFile::ExeGroup
)) {
2125 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2127 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
2129 // Set others string
2131 if (info
.permission(QFile::ReadOther
)) {
2132 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2134 if (info
.permission(QFile::WriteOther
)) {
2135 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2137 if (info
.permission(QFile::ExeOther
)) {
2138 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2140 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
2142 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
2143 if (newGroupValue
!= groupValue
) {
2144 groupValue
= newGroupValue
;
2145 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2152 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
2154 Q_ASSERT(!m_itemData
.isEmpty());
2156 const int maxIndex
= count() - 1;
2157 QList
<QPair
<int, QVariant
> > groups
;
2159 int groupValue
= -1;
2160 for (int i
= 0; i
<= maxIndex
; ++i
) {
2161 if (isChildItem(i
)) {
2164 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
2165 if (newGroupValue
!= groupValue
) {
2166 groupValue
= newGroupValue
;
2167 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2174 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
2176 Q_ASSERT(!m_itemData
.isEmpty());
2178 const int maxIndex
= count() - 1;
2179 QList
<QPair
<int, QVariant
> > groups
;
2181 bool isFirstGroupValue
= true;
2183 for (int i
= 0; i
<= maxIndex
; ++i
) {
2184 if (isChildItem(i
)) {
2187 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
2188 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
2189 groupValue
= newGroupValue
;
2190 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2191 isFirstGroupValue
= false;
2198 void KFileItemModel::emitSortProgress(int resolvedCount
)
2200 // Be tolerant against a resolvedCount with a wrong range.
2201 // Although there should not be a case where KFileItemModelRolesUpdater
2202 // (= caller) provides a wrong range, it is important to emit
2203 // a useful progress information even if there is an unexpected
2204 // implementation issue.
2206 const int itemCount
= count();
2207 if (resolvedCount
>= itemCount
) {
2208 m_sortingProgressPercent
= -1;
2209 if (m_resortAllItemsTimer
->isActive()) {
2210 m_resortAllItemsTimer
->stop();
2214 emit
directorySortingProgress(100);
2215 } else if (itemCount
> 0) {
2216 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
2218 const int progress
= resolvedCount
* 100 / itemCount
;
2219 if (m_sortingProgressPercent
!= progress
) {
2220 m_sortingProgressPercent
= progress
;
2221 emit
directorySortingProgress(progress
);
2226 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
2228 static const RoleInfoMap rolesInfoMap
[] = {
2229 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
2230 { 0, NoRole
, 0, 0, 0, 0, false, false },
2231 { "text", NameRole
, I18N_NOOP2_NOSTRIP("@label", "Name"), 0, 0, false, false },
2232 { "size", SizeRole
, I18N_NOOP2_NOSTRIP("@label", "Size"), 0, 0, false, false },
2233 { "modificationtime", ModificationTimeRole
, I18N_NOOP2_NOSTRIP("@label", "Modified"), 0, 0, false, false },
2234 { "accesstime", AccessTimeRole
, I18N_NOOP2_NOSTRIP("@label", "Accessed"), 0, 0, false, false },
2235 { "type", TypeRole
, I18N_NOOP2_NOSTRIP("@label", "Type"), 0, 0, false, false },
2236 { "rating", RatingRole
, I18N_NOOP2_NOSTRIP("@label", "Rating"), 0, 0, true, false },
2237 { "tags", TagsRole
, I18N_NOOP2_NOSTRIP("@label", "Tags"), 0, 0, true, false },
2238 { "comment", CommentRole
, I18N_NOOP2_NOSTRIP("@label", "Comment"), 0, 0, true, false },
2239 { "title", TitleRole
, I18N_NOOP2_NOSTRIP("@label", "Title"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
2240 { "wordCount", WordCountRole
, I18N_NOOP2_NOSTRIP("@label", "Word Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
2241 { "lineCount", LineCountRole
, I18N_NOOP2_NOSTRIP("@label", "Line Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
2242 { "imageSize", ImageSizeRole
, I18N_NOOP2_NOSTRIP("@label", "Image Size"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
2243 { "orientation", OrientationRole
, I18N_NOOP2_NOSTRIP("@label", "Orientation"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
2244 { "artist", ArtistRole
, I18N_NOOP2_NOSTRIP("@label", "Artist"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
2245 { "album", AlbumRole
, I18N_NOOP2_NOSTRIP("@label", "Album"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
2246 { "duration", DurationRole
, I18N_NOOP2_NOSTRIP("@label", "Duration"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
2247 { "track", TrackRole
, I18N_NOOP2_NOSTRIP("@label", "Track"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
2248 { "path", PathRole
, I18N_NOOP2_NOSTRIP("@label", "Path"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2249 { "destination", DestinationRole
, I18N_NOOP2_NOSTRIP("@label", "Link Destination"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2250 { "originUrl", OriginUrlRole
, I18N_NOOP2_NOSTRIP("@label", "Downloaded From"), I18N_NOOP2_NOSTRIP("@label", "Other"), true, false },
2251 { "permissions", PermissionsRole
, I18N_NOOP2_NOSTRIP("@label", "Permissions"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2252 { "owner", OwnerRole
, I18N_NOOP2_NOSTRIP("@label", "Owner"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2253 { "group", GroupRole
, I18N_NOOP2_NOSTRIP("@label", "User Group"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2256 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
2257 return rolesInfoMap
;
2260 void KFileItemModel::determineMimeTypes(const KFileItemList
& items
, int timeout
)
2262 QElapsedTimer timer
;
2264 foreach (const KFileItem
& item
, items
) { // krazy:exclude=foreach
2265 // Only determine mime types for files here. For directories,
2266 // KFileItem::determineMimeType() reads the .directory file inside to
2267 // load the icon, but this is not necessary at all if we just need the
2268 // type. Some special code for setting the correct mime type for
2269 // directories is in retrieveData().
2270 if (!item
.isDir()) {
2271 item
.determineMimeType();
2274 if (timer
.elapsed() > timeout
) {
2275 // Don't block the user interface, let the remaining items
2276 // be resolved asynchronously.
2282 QByteArray
KFileItemModel::sharedValue(const QByteArray
& value
)
2284 static QSet
<QByteArray
> pool
;
2285 const QSet
<QByteArray
>::const_iterator it
= pool
.constFind(value
);
2287 if (it
!= pool
.constEnd()) {
2295 bool KFileItemModel::isConsistent() const
2297 // m_items may contain less items than m_itemData because m_items
2298 // is populated lazily, see KFileItemModel::index(const QUrl& url).
2299 if (m_items
.count() > m_itemData
.count()) {
2303 for (int i
= 0; i
< count(); ++i
) {
2304 // Check if m_items and m_itemData are consistent.
2305 const KFileItem item
= fileItem(i
);
2306 if (item
.isNull()) {
2307 qCWarning(DolphinDebug
) << "Item" << i
<< "is null";
2311 const int itemIndex
= index(item
);
2312 if (itemIndex
!= i
) {
2313 qCWarning(DolphinDebug
) << "Item" << i
<< "has a wrong index:" << itemIndex
;
2317 // Check if the items are sorted correctly.
2318 if (i
> 0 && !lessThan(m_itemData
.at(i
- 1), m_itemData
.at(i
), m_collator
)) {
2319 qCWarning(DolphinDebug
) << "The order of items" << i
- 1 << "and" << i
<< "is wrong:"
2320 << fileItem(i
- 1) << fileItem(i
);
2324 // Check if all parent-child relationships are consistent.
2325 const ItemData
* data
= m_itemData
.at(i
);
2326 const ItemData
* parent
= data
->parent
;
2328 if (expandedParentsCount(data
) != expandedParentsCount(parent
) + 1) {
2329 qCWarning(DolphinDebug
) << "expandedParentsCount is inconsistent for parent" << parent
->item
<< "and child" << data
->item
;
2333 const int parentIndex
= index(parent
->item
);
2334 if (parentIndex
>= i
) {
2335 qCWarning(DolphinDebug
) << "Index" << parentIndex
<< "of parent" << parent
->item
<< "is not smaller than index" << i
<< "of child" << data
->item
;