1 /***************************************************************************
2 * Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
4 * This program is free software; you can redistribute it and/or modify *
5 * it under the terms of the GNU General Public License as published by *
6 * the Free Software Foundation; either version 2 of the License, or *
7 * (at your option) any later version. *
9 * This program is distributed in the hope that it will be useful, *
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
12 * GNU General Public License for more details. *
14 * You should have received a copy of the GNU General Public License *
15 * along with this program; if not, write to the *
16 * Free Software Foundation, Inc., *
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
18 ***************************************************************************/
20 #include "kfileitemmodel.h"
23 #include <KGlobalSettings>
25 #include <KStringHandler>
28 #include "private/kfileitemmodelsortalgorithm.h"
29 #include "private/kfileitemmodeldirlister.h"
31 #include <QApplication>
35 // #define KFILEITEMMODEL_DEBUG
37 KFileItemModel::KFileItemModel(QObject
* parent
) :
38 KItemModelBase("text", parent
),
40 m_naturalSorting(KGlobalSettings::naturalSorting()),
41 m_sortDirsFirst(true),
43 m_sortingProgressPercent(-1),
45 m_caseSensitivity(Qt::CaseInsensitive
),
51 m_maximumUpdateIntervalTimer(0),
52 m_resortAllItemsTimer(0),
53 m_pendingItemsToInsert(),
55 m_expandedParentsCountRoot(UninitializedExpandedParentsCountRoot
),
59 m_dirLister
= new KFileItemModelDirLister(this);
60 m_dirLister
->setAutoUpdate(true);
61 m_dirLister
->setDelayedMimeTypes(true);
62 m_dirLister
->setMainWindow(qApp
->activeWindow());
64 connect(m_dirLister
, SIGNAL(started(KUrl
)), this, SIGNAL(directoryLoadingStarted()));
65 connect(m_dirLister
, SIGNAL(canceled()), this, SLOT(slotCanceled()));
66 connect(m_dirLister
, SIGNAL(completed(KUrl
)), this, SLOT(slotCompleted()));
67 connect(m_dirLister
, SIGNAL(newItems(KFileItemList
)), this, SLOT(slotNewItems(KFileItemList
)));
68 connect(m_dirLister
, SIGNAL(itemsDeleted(KFileItemList
)), this, SLOT(slotItemsDeleted(KFileItemList
)));
69 connect(m_dirLister
, SIGNAL(refreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)), this, SLOT(slotRefreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)));
70 connect(m_dirLister
, SIGNAL(clear()), this, SLOT(slotClear()));
71 connect(m_dirLister
, SIGNAL(clear(KUrl
)), this, SLOT(slotClear(KUrl
)));
72 connect(m_dirLister
, SIGNAL(infoMessage(QString
)), this, SIGNAL(infoMessage(QString
)));
73 connect(m_dirLister
, SIGNAL(errorMessage(QString
)), this, SIGNAL(errorMessage(QString
)));
74 connect(m_dirLister
, SIGNAL(redirection(KUrl
,KUrl
)), this, SIGNAL(directoryRedirection(KUrl
,KUrl
)));
75 connect(m_dirLister
, SIGNAL(urlIsFileError(KUrl
)), this, SIGNAL(urlIsFileError(KUrl
)));
77 // Apply default roles that should be determined
79 m_requestRole
[NameRole
] = true;
80 m_requestRole
[IsDirRole
] = true;
81 m_requestRole
[IsLinkRole
] = true;
82 m_roles
.insert("text");
83 m_roles
.insert("isDir");
84 m_roles
.insert("isLink");
86 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
87 // before the completed() or canceled() signal has been emitted.
88 m_maximumUpdateIntervalTimer
= new QTimer(this);
89 m_maximumUpdateIntervalTimer
->setInterval(2000);
90 m_maximumUpdateIntervalTimer
->setSingleShot(true);
91 connect(m_maximumUpdateIntervalTimer
, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
93 // When changing the value of an item which represents the sort-role a resorting must be
94 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
95 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
96 // resorting is postponed until the timer has been exceeded.
97 m_resortAllItemsTimer
= new QTimer(this);
98 m_resortAllItemsTimer
->setInterval(500);
99 m_resortAllItemsTimer
->setSingleShot(true);
100 connect(m_resortAllItemsTimer
, SIGNAL(timeout()), this, SLOT(resortAllItems()));
102 connect(KGlobalSettings::self(), SIGNAL(naturalSortingChanged()), this, SLOT(slotNaturalSortingChanged()));
105 KFileItemModel::~KFileItemModel()
107 qDeleteAll(m_itemData
);
111 void KFileItemModel::loadDirectory(const KUrl
& url
)
113 m_dirLister
->openUrl(url
);
116 void KFileItemModel::refreshDirectory(const KUrl
& url
)
118 m_dirLister
->openUrl(url
, KDirLister::Reload
);
121 KUrl
KFileItemModel::directory() const
123 return m_dirLister
->url();
126 void KFileItemModel::cancelDirectoryLoading()
131 int KFileItemModel::count() const
133 return m_itemData
.count();
136 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
138 if (index
>= 0 && index
< count()) {
139 return m_itemData
.at(index
)->values
;
141 return QHash
<QByteArray
, QVariant
>();
144 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
146 if (index
< 0 || index
>= count()) {
150 QHash
<QByteArray
, QVariant
> currentValues
= m_itemData
.at(index
)->values
;
152 // Determine which roles have been changed
153 QSet
<QByteArray
> changedRoles
;
154 QHashIterator
<QByteArray
, QVariant
> it(values
);
155 while (it
.hasNext()) {
157 const QByteArray role
= it
.key();
158 const QVariant value
= it
.value();
160 if (currentValues
[role
] != value
) {
161 currentValues
[role
] = value
;
162 changedRoles
.insert(role
);
166 if (changedRoles
.isEmpty()) {
170 m_itemData
[index
]->values
= currentValues
;
171 if (changedRoles
.contains("text")) {
172 KUrl url
= m_itemData
[index
]->item
.url();
173 url
.setFileName(currentValues
["text"].toString());
174 m_itemData
[index
]->item
.setUrl(url
);
177 emit
itemsChanged(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
179 if (changedRoles
.contains(sortRole())) {
180 m_resortAllItemsTimer
->start();
186 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
188 if (dirsFirst
!= m_sortDirsFirst
) {
189 m_sortDirsFirst
= dirsFirst
;
194 bool KFileItemModel::sortDirectoriesFirst() const
196 return m_sortDirsFirst
;
199 void KFileItemModel::setShowHiddenFiles(bool show
)
201 m_dirLister
->setShowingDotFiles(show
);
202 m_dirLister
->emitChanges();
208 bool KFileItemModel::showHiddenFiles() const
210 return m_dirLister
->showingDotFiles();
213 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
215 m_dirLister
->setDirOnlyMode(enabled
);
218 bool KFileItemModel::showDirectoriesOnly() const
220 return m_dirLister
->dirOnlyMode();
223 QMimeData
* KFileItemModel::createMimeData(const QSet
<int>& indexes
) const
225 QMimeData
* data
= new QMimeData();
227 // The following code has been taken from KDirModel::mimeData()
228 // (kdelibs/kio/kio/kdirmodel.cpp)
229 // Copyright (C) 2006 David Faure <faure@kde.org>
231 KUrl::List mostLocalUrls
;
232 bool canUseMostLocalUrls
= true;
234 QSetIterator
<int> it(indexes
);
235 while (it
.hasNext()) {
236 const int index
= it
.next();
237 const KFileItem item
= fileItem(index
);
238 if (!item
.isNull()) {
242 mostLocalUrls
<< item
.mostLocalUrl(isLocal
);
244 canUseMostLocalUrls
= false;
249 const bool different
= canUseMostLocalUrls
&& mostLocalUrls
!= urls
;
250 urls
= KDirModel::simplifiedUrlList(urls
); // TODO: Check if we still need KDirModel for this in KDE 5.0
252 mostLocalUrls
= KDirModel::simplifiedUrlList(mostLocalUrls
);
253 urls
.populateMimeData(mostLocalUrls
, data
);
255 urls
.populateMimeData(data
);
261 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
263 startFromIndex
= qMax(0, startFromIndex
);
264 for (int i
= startFromIndex
; i
< count(); ++i
) {
265 if (data(i
)["text"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
269 for (int i
= 0; i
< startFromIndex
; ++i
) {
270 if (data(i
)["text"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
277 bool KFileItemModel::supportsDropping(int index
) const
279 const KFileItem item
= fileItem(index
);
280 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
283 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
285 static QHash
<QByteArray
, QString
> description
;
286 if (description
.isEmpty()) {
288 const RoleInfoMap
* map
= rolesInfoMap(count
);
289 for (int i
= 0; i
< count
; ++i
) {
290 description
.insert(map
[i
].role
, map
[i
].roleTranslation
);
294 return description
.value(role
);
297 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
299 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
300 #ifdef KFILEITEMMODEL_DEBUG
304 switch (typeForRole(sortRole())) {
305 case NameRole
: m_groups
= nameRoleGroups(); break;
306 case SizeRole
: m_groups
= sizeRoleGroups(); break;
307 case DateRole
: m_groups
= dateRoleGroups(); break;
308 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
309 case RatingRole
: m_groups
= ratingRoleGroups(); break;
310 default: m_groups
= genericStringRoleGroups(sortRole()); break;
313 #ifdef KFILEITEMMODEL_DEBUG
314 kDebug() << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
321 KFileItem
KFileItemModel::fileItem(int index
) const
323 if (index
>= 0 && index
< count()) {
324 return m_itemData
.at(index
)->item
;
330 KFileItem
KFileItemModel::fileItem(const KUrl
& url
) const
332 const int index
= m_items
.value(url
, -1);
334 return m_itemData
.at(index
)->item
;
339 int KFileItemModel::index(const KFileItem
& item
) const
345 return m_items
.value(item
.url(), -1);
348 int KFileItemModel::index(const KUrl
& url
) const
350 KUrl urlToFind
= url
;
351 urlToFind
.adjustPath(KUrl::RemoveTrailingSlash
);
352 return m_items
.value(urlToFind
, -1);
355 KFileItem
KFileItemModel::rootItem() const
357 return m_dirLister
->rootItem();
360 void KFileItemModel::clear()
365 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
367 if (m_roles
== roles
) {
373 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
374 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
375 if (supportedExpanding
&& !willSupportExpanding
) {
376 // No expanding is supported anymore. Take care to delete all items that have an expansion level
377 // that is not 0 (and hence are part of an expanded item).
378 removeExpandedItems();
385 QSetIterator
<QByteArray
> it(roles
);
386 while (it
.hasNext()) {
387 const QByteArray
& role
= it
.next();
388 m_requestRole
[typeForRole(role
)] = true;
392 // Update m_data with the changed requested roles
393 const int maxIndex
= count() - 1;
394 for (int i
= 0; i
<= maxIndex
; ++i
) {
395 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
);
398 kWarning() << "TODO: Emitting itemsChanged() with no information what has changed!";
399 emit
itemsChanged(KItemRangeList() << KItemRange(0, count()), QSet
<QByteArray
>());
403 QSet
<QByteArray
> KFileItemModel::roles() const
408 bool KFileItemModel::setExpanded(int index
, bool expanded
)
410 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
414 QHash
<QByteArray
, QVariant
> values
;
415 values
.insert("isExpanded", expanded
);
416 if (!setData(index
, values
)) {
420 const KUrl url
= m_itemData
.at(index
)->item
.url();
422 m_expandedDirs
.insert(url
);
423 m_dirLister
->openUrl(url
, KDirLister::Keep
);
425 m_expandedDirs
.remove(url
);
426 m_dirLister
->stop(url
);
429 KFileItemList itemsToRemove
;
430 const int expandedParentsCount
= data(index
)["expandedParentsCount"].toInt();
432 while (index
< count() && data(index
)["expandedParentsCount"].toInt() > expandedParentsCount
) {
433 itemsToRemove
.append(m_itemData
.at(index
)->item
);
436 removeItems(itemsToRemove
);
442 bool KFileItemModel::isExpanded(int index
) const
444 if (index
>= 0 && index
< count()) {
445 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
450 bool KFileItemModel::isExpandable(int index
) const
452 if (index
>= 0 && index
< count()) {
453 return m_itemData
.at(index
)->values
.value("isExpandable").toBool();
458 int KFileItemModel::expandedParentsCount(int index
) const
460 if (index
>= 0 && index
< count()) {
461 const int parentsCount
= m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt();
462 if (parentsCount
> 0) {
469 QSet
<KUrl
> KFileItemModel::expandedDirectories() const
471 return m_expandedDirs
;
474 void KFileItemModel::restoreExpandedDirectories(const QSet
<KUrl
>& urls
)
476 m_urlsToExpand
= urls
;
479 void KFileItemModel::expandParentDirectories(const KUrl
& url
)
481 const int pos
= m_dirLister
->url().path().length();
483 // Assure that each sub-path of the URL that should be
484 // expanded is added to m_urlsToExpand. KDirLister
485 // does not care whether the parent-URL has already been
487 KUrl urlToExpand
= m_dirLister
->url();
488 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator());
489 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
490 urlToExpand
.addPath(subDirs
.at(i
));
491 m_urlsToExpand
.insert(urlToExpand
);
494 // KDirLister::open() must called at least once to trigger an initial
495 // loading. The pending URLs that must be restored are handled
496 // in slotCompleted().
497 QSetIterator
<KUrl
> it2(m_urlsToExpand
);
498 while (it2
.hasNext()) {
499 const int idx
= index(it2
.next());
500 if (idx
>= 0 && !isExpanded(idx
)) {
501 setExpanded(idx
, true);
507 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
509 if (m_filter
.pattern() != nameFilter
) {
510 dispatchPendingItemsToInsert();
512 m_filter
.setPattern(nameFilter
);
514 // Check which shown items from m_itemData must get
515 // hidden and hence moved to m_filteredItems.
516 KFileItemList newFilteredItems
;
518 foreach (ItemData
* itemData
, m_itemData
) {
519 if (!m_filter
.matches(itemData
->item
)) {
520 // Only filter non-expanded items as child items may never
521 // exist without a parent item
522 if (!itemData
->values
.value("isExpanded").toBool()) {
523 newFilteredItems
.append(itemData
->item
);
524 m_filteredItems
.insert(itemData
->item
);
529 removeItems(newFilteredItems
);
531 // Check which hidden items from m_filteredItems should
532 // get visible again and hence removed from m_filteredItems.
533 KFileItemList newVisibleItems
;
535 QMutableSetIterator
<KFileItem
> it(m_filteredItems
);
536 while (it
.hasNext()) {
537 const KFileItem item
= it
.next();
538 if (m_filter
.matches(item
)) {
539 newVisibleItems
.append(item
);
544 insertItems(newVisibleItems
);
548 QString
KFileItemModel::nameFilter() const
550 return m_filter
.pattern();
553 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
555 static QList
<RoleInfo
> rolesInfo
;
556 if (rolesInfo
.isEmpty()) {
558 const RoleInfoMap
* map
= rolesInfoMap(count
);
559 for (int i
= 0; i
< count
; ++i
) {
560 if (map
[i
].roleType
!= NoRole
) {
562 info
.role
= map
[i
].role
;
563 info
.translation
= map
[i
].roleTranslation
;
564 info
.group
= map
[i
].groupTranslation
;
565 info
.requiresNepomuk
= map
[i
].requiresNepomuk
;
566 info
.requiresIndexer
= map
[i
].requiresIndexer
;
567 rolesInfo
.append(info
);
575 void KFileItemModel::onGroupedSortingChanged(bool current
)
581 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
584 m_sortRole
= typeForRole(current
);
586 #ifdef KFILEITEMMODEL_DEBUG
587 if (!m_requestRole
[m_sortRole
]) {
588 kWarning() << "The sort-role has been changed to a role that has not been received yet";
595 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
602 void KFileItemModel::resortAllItems()
604 m_resortAllItemsTimer
->stop();
606 const int itemCount
= count();
607 if (itemCount
<= 0) {
611 #ifdef KFILEITEMMODEL_DEBUG
614 kDebug() << "===========================================================";
615 kDebug() << "Resorting" << itemCount
<< "items";
618 // Remember the order of the current URLs so
619 // that it can be determined which indexes have
620 // been moved because of the resorting.
622 oldUrls
.reserve(itemCount
);
623 foreach (const ItemData
* itemData
, m_itemData
) {
624 oldUrls
.append(itemData
->item
.url());
631 KFileItemModelSortAlgorithm::sort(this, m_itemData
.begin(), m_itemData
.end());
632 for (int i
= 0; i
< itemCount
; ++i
) {
633 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
636 // Determine the indexes that have been moved
637 QList
<int> movedToIndexes
;
638 movedToIndexes
.reserve(itemCount
);
639 for (int i
= 0; i
< itemCount
; i
++) {
640 const int newIndex
= m_items
.value(oldUrls
.at(i
).url());
641 movedToIndexes
.append(newIndex
);
644 // Don't check whether items have really been moved and always emit a
645 // itemsMoved() signal after resorting: In case of grouped items
646 // the groups might change even if the items themselves don't change their
647 // position. Let the receiver of the signal decide whether a check for moved
648 // items makes sense.
649 emit
itemsMoved(KItemRange(0, itemCount
), movedToIndexes
);
651 #ifdef KFILEITEMMODEL_DEBUG
652 kDebug() << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
656 void KFileItemModel::slotCompleted()
658 dispatchPendingItemsToInsert();
660 if (!m_urlsToExpand
.isEmpty()) {
661 // Try to find a URL that can be expanded.
662 // Note that the parent folder must be expanded before any of its subfolders become visible.
663 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
664 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
665 foreach (const KUrl
& url
, m_urlsToExpand
) {
666 const int index
= m_items
.value(url
, -1);
668 m_urlsToExpand
.remove(url
);
669 if (setExpanded(index
, true)) {
670 // The dir lister has been triggered. This slot will be called
671 // again after the directory has been expanded.
677 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
678 // if these URLs have been deleted in the meantime.
679 m_urlsToExpand
.clear();
682 emit
directoryLoadingCompleted();
685 void KFileItemModel::slotCanceled()
687 m_maximumUpdateIntervalTimer
->stop();
688 dispatchPendingItemsToInsert();
691 void KFileItemModel::slotNewItems(const KFileItemList
& items
)
693 Q_ASSERT(!items
.isEmpty());
695 if (m_requestRole
[ExpandedParentsCountRole
] && m_expandedParentsCountRoot
>= 0) {
696 // To be able to compare whether the new items may be inserted as children
697 // of a parent item the pending items must be added to the model first.
698 dispatchPendingItemsToInsert();
700 KFileItem item
= items
.first();
702 // If the expanding of items is enabled, the call
703 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
704 // might result in emitting the same items twice due to the Keep-parameter.
705 // This case happens if an item gets expanded, collapsed and expanded again
706 // before the items could be loaded for the first expansion.
707 const int index
= m_items
.value(item
.url(), -1);
709 // The items are already part of the model.
713 // KDirLister keeps the children of items that got expanded once even if
714 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
715 // checked whether the parent for new items is still expanded.
716 KUrl parentUrl
= item
.url().upUrl();
717 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
718 const int parentIndex
= m_items
.value(parentUrl
, -1);
719 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
720 // The parent is not expanded.
725 if (m_filter
.pattern().isEmpty()) {
726 m_pendingItemsToInsert
.append(items
);
728 // The name-filter is active. Hide filtered items
729 // before inserting them into the model and remember
730 // the filtered items in m_filteredItems.
731 KFileItemList filteredItems
;
732 foreach (const KFileItem
& item
, items
) {
733 if (m_filter
.matches(item
)) {
734 filteredItems
.append(item
);
736 m_filteredItems
.insert(item
);
740 m_pendingItemsToInsert
.append(filteredItems
);
743 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer
->isActive()) {
744 // Assure that items get dispatched if no completed() or canceled() signal is
745 // emitted during the maximum update interval.
746 m_maximumUpdateIntervalTimer
->start();
750 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
752 dispatchPendingItemsToInsert();
754 KFileItemList itemsToRemove
= items
;
755 if (m_requestRole
[ExpandedParentsCountRole
] && m_expandedParentsCountRoot
>= 0) {
756 // Assure that removing a parent item also results in removing all children
757 foreach (const KFileItem
& item
, items
) {
758 itemsToRemove
.append(childItems(item
));
762 if (!m_filteredItems
.isEmpty()) {
763 foreach (const KFileItem
& item
, itemsToRemove
) {
764 m_filteredItems
.remove(item
);
768 removeItems(itemsToRemove
);
771 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
773 Q_ASSERT(!items
.isEmpty());
774 #ifdef KFILEITEMMODEL_DEBUG
775 kDebug() << "Refreshing" << items
.count() << "items";
780 // Get the indexes of all items that have been refreshed
782 indexes
.reserve(items
.count());
784 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
785 while (it
.hasNext()) {
786 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
787 const KFileItem
& oldItem
= itemPair
.first
;
788 const KFileItem
& newItem
= itemPair
.second
;
789 const int index
= m_items
.value(oldItem
.url(), -1);
791 m_itemData
[index
]->item
= newItem
;
793 // Keep old values as long as possible if they could not retrieved synchronously yet.
794 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
795 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
));
796 while (it
.hasNext()) {
798 m_itemData
[index
]->values
.insert(it
.key(), it
.value());
801 m_items
.remove(oldItem
.url());
802 m_items
.insert(newItem
.url(), index
);
803 indexes
.append(index
);
807 // If the changed items have been created recently, they might not be in m_items yet.
808 // In that case, the list 'indexes' might be empty.
809 if (indexes
.isEmpty()) {
813 // Extract the item-ranges out of the changed indexes
816 KItemRangeList itemRangeList
;
817 int previousIndex
= indexes
.at(0);
818 int rangeIndex
= previousIndex
;
821 const int maxIndex
= indexes
.count() - 1;
822 for (int i
= 1; i
<= maxIndex
; ++i
) {
823 const int currentIndex
= indexes
.at(i
);
824 if (currentIndex
== previousIndex
+ 1) {
827 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
829 rangeIndex
= currentIndex
;
832 previousIndex
= currentIndex
;
835 if (rangeCount
> 0) {
836 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
839 emit
itemsChanged(itemRangeList
, m_roles
);
844 void KFileItemModel::slotClear()
846 #ifdef KFILEITEMMODEL_DEBUG
847 kDebug() << "Clearing all items";
850 m_filteredItems
.clear();
853 m_maximumUpdateIntervalTimer
->stop();
854 m_resortAllItemsTimer
->stop();
855 m_pendingItemsToInsert
.clear();
857 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
859 const int removedCount
= m_itemData
.count();
860 if (removedCount
> 0) {
861 qDeleteAll(m_itemData
);
864 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
867 m_expandedDirs
.clear();
870 void KFileItemModel::slotClear(const KUrl
& url
)
875 void KFileItemModel::slotNaturalSortingChanged()
877 m_naturalSorting
= KGlobalSettings::naturalSorting();
881 void KFileItemModel::dispatchPendingItemsToInsert()
883 if (!m_pendingItemsToInsert
.isEmpty()) {
884 insertItems(m_pendingItemsToInsert
);
885 m_pendingItemsToInsert
.clear();
889 void KFileItemModel::insertItems(const KFileItemList
& items
)
891 if (items
.isEmpty()) {
895 if (m_sortRole
== TypeRole
) {
896 // Try to resolve the MIME-types synchronously to prevent a reordering of
897 // the items when sorting by type (per default MIME-types are resolved
898 // asynchronously by KFileItemModelRolesUpdater).
899 determineMimeTypes(items
, 200);
902 #ifdef KFILEITEMMODEL_DEBUG
905 kDebug() << "===========================================================";
906 kDebug() << "Inserting" << items
.count() << "items";
911 QList
<ItemData
*> sortedItems
= createItemDataList(items
);
912 KFileItemModelSortAlgorithm::sort(this, sortedItems
.begin(), sortedItems
.end());
914 #ifdef KFILEITEMMODEL_DEBUG
915 kDebug() << "[TIME] Sorting:" << timer
.elapsed();
918 KItemRangeList itemRanges
;
921 int insertedAtIndex
= -1; // Index for the current item-range
922 int insertedCount
= 0; // Count for the current item-range
923 int previouslyInsertedCount
= 0; // Sum of previously inserted items for all ranges
924 while (sourceIndex
< sortedItems
.count()) {
925 // Find target index from m_items to insert the current item
927 const int previousTargetIndex
= targetIndex
;
928 while (targetIndex
< m_itemData
.count()) {
929 if (!lessThan(m_itemData
.at(targetIndex
), sortedItems
.at(sourceIndex
))) {
935 if (targetIndex
- previousTargetIndex
> 0 && insertedAtIndex
>= 0) {
936 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
937 previouslyInsertedCount
+= insertedCount
;
938 insertedAtIndex
= targetIndex
- previouslyInsertedCount
;
942 // Insert item at the position targetIndex by transferring
943 // the ownership of the item-data from sortedItems to m_itemData.
944 // m_items will be inserted after the loop (see comment below)
945 m_itemData
.insert(targetIndex
, sortedItems
.at(sourceIndex
));
948 if (insertedAtIndex
< 0) {
949 insertedAtIndex
= targetIndex
;
950 Q_ASSERT(previouslyInsertedCount
== 0);
956 // The indexes of all m_items must be adjusted, not only the index
958 const int itemDataCount
= m_itemData
.count();
959 for (int i
= 0; i
< itemDataCount
; ++i
) {
960 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
963 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
964 emit
itemsInserted(itemRanges
);
966 #ifdef KFILEITEMMODEL_DEBUG
967 kDebug() << "[TIME] Inserting of" << items
.count() << "items:" << timer
.elapsed();
971 void KFileItemModel::removeItems(const KFileItemList
& items
)
973 if (items
.isEmpty()) {
977 #ifdef KFILEITEMMODEL_DEBUG
978 kDebug() << "Removing " << items
.count() << "items";
983 QList
<ItemData
*> sortedItems
;
984 sortedItems
.reserve(items
.count());
985 foreach (const KFileItem
& item
, items
) {
986 const int index
= m_items
.value(item
.url(), -1);
988 sortedItems
.append(m_itemData
.at(index
));
991 KFileItemModelSortAlgorithm::sort(this, sortedItems
.begin(), sortedItems
.end());
993 QList
<int> indexesToRemove
;
994 indexesToRemove
.reserve(items
.count());
996 // Calculate the item ranges that will get deleted
997 KItemRangeList itemRanges
;
998 int removedAtIndex
= -1;
999 int removedCount
= 0;
1000 int targetIndex
= 0;
1001 foreach (const ItemData
* itemData
, sortedItems
) {
1002 const KFileItem
& itemToRemove
= itemData
->item
;
1004 const int previousTargetIndex
= targetIndex
;
1005 while (targetIndex
< m_itemData
.count()) {
1006 if (m_itemData
.at(targetIndex
)->item
.url() == itemToRemove
.url()) {
1011 if (targetIndex
>= m_itemData
.count()) {
1012 kWarning() << "Item that should be deleted has not been found!";
1016 if (targetIndex
- previousTargetIndex
> 0 && removedAtIndex
>= 0) {
1017 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
1018 removedAtIndex
= targetIndex
;
1022 indexesToRemove
.append(targetIndex
);
1023 if (removedAtIndex
< 0) {
1024 removedAtIndex
= targetIndex
;
1031 for (int i
= indexesToRemove
.count() - 1; i
>= 0; --i
) {
1032 const int indexToRemove
= indexesToRemove
.at(i
);
1033 ItemData
* data
= m_itemData
.at(indexToRemove
);
1035 m_items
.remove(data
->item
.url());
1038 m_itemData
.removeAt(indexToRemove
);
1041 // The indexes of all m_items must be adjusted, not only the index
1042 // of the removed items
1043 const int itemDataCount
= m_itemData
.count();
1044 for (int i
= 0; i
< itemDataCount
; ++i
) {
1045 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
1049 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
1052 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
1053 emit
itemsRemoved(itemRanges
);
1056 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const KFileItemList
& items
) const
1058 QList
<ItemData
*> itemDataList
;
1059 itemDataList
.reserve(items
.count());
1061 foreach (const KFileItem
& item
, items
) {
1062 ItemData
* itemData
= new ItemData();
1063 itemData
->item
= item
;
1064 itemData
->values
= retrieveData(item
);
1065 itemData
->parent
= 0;
1067 const bool determineParent
= m_requestRole
[ExpandedParentsCountRole
]
1068 && itemData
->values
["expandedParentsCount"].toInt() > 0;
1069 if (determineParent
) {
1070 KUrl parentUrl
= item
.url().upUrl();
1071 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
1072 const int parentIndex
= m_items
.value(parentUrl
, -1);
1073 if (parentIndex
>= 0) {
1074 itemData
->parent
= m_itemData
.at(parentIndex
);
1076 kWarning() << "Parent item not found for" << item
.url();
1080 itemDataList
.append(itemData
);
1083 return itemDataList
;
1086 void KFileItemModel::removeExpandedItems()
1088 KFileItemList expandedItems
;
1090 const int maxIndex
= m_itemData
.count() - 1;
1091 for (int i
= 0; i
<= maxIndex
; ++i
) {
1092 const ItemData
* itemData
= m_itemData
.at(i
);
1093 if (itemData
->values
.value("expandedParentsCount").toInt() > 0) {
1094 expandedItems
.append(itemData
->item
);
1098 // The m_expandedParentsCountRoot may not get reset before all items with
1099 // a bigger count have been removed.
1100 removeItems(expandedItems
);
1102 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
1103 m_expandedDirs
.clear();
1106 void KFileItemModel::resetRoles()
1108 for (int i
= 0; i
< RolesCount
; ++i
) {
1109 m_requestRole
[i
] = false;
1113 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1115 static QHash
<QByteArray
, RoleType
> roles
;
1116 if (roles
.isEmpty()) {
1117 // Insert user visible roles that can be accessed with
1118 // KFileItemModel::roleInformation()
1120 const RoleInfoMap
* map
= rolesInfoMap(count
);
1121 for (int i
= 0; i
< count
; ++i
) {
1122 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1125 // Insert internal roles (take care to synchronize the implementation
1126 // with KFileItemModel::roleForType() in case if a change is done).
1127 roles
.insert("isDir", IsDirRole
);
1128 roles
.insert("isLink", IsLinkRole
);
1129 roles
.insert("isExpanded", IsExpandedRole
);
1130 roles
.insert("isExpandable", IsExpandableRole
);
1131 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1133 Q_ASSERT(roles
.count() == RolesCount
);
1136 return roles
.value(role
, NoRole
);
1139 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1141 static QHash
<RoleType
, QByteArray
> roles
;
1142 if (roles
.isEmpty()) {
1143 // Insert user visible roles that can be accessed with
1144 // KFileItemModel::roleInformation()
1146 const RoleInfoMap
* map
= rolesInfoMap(count
);
1147 for (int i
= 0; i
< count
; ++i
) {
1148 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1151 // Insert internal roles (take care to synchronize the implementation
1152 // with KFileItemModel::typeForRole() in case if a change is done).
1153 roles
.insert(IsDirRole
, "isDir");
1154 roles
.insert(IsLinkRole
, "isLink");
1155 roles
.insert(IsExpandedRole
, "isExpanded");
1156 roles
.insert(IsExpandableRole
, "isExpandable");
1157 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1159 Q_ASSERT(roles
.count() == RolesCount
);
1162 return roles
.value(roleType
);
1165 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
) const
1167 // It is important to insert only roles that are fast to retrieve. E.g.
1168 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1169 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1170 QHash
<QByteArray
, QVariant
> data
;
1171 data
.insert("url", item
.url());
1173 const bool isDir
= item
.isDir();
1174 if (m_requestRole
[IsDirRole
]) {
1175 data
.insert("isDir", isDir
);
1178 if (m_requestRole
[IsLinkRole
]) {
1179 const bool isLink
= item
.isLink();
1180 data
.insert("isLink", isLink
);
1183 if (m_requestRole
[NameRole
]) {
1184 data
.insert("text", item
.text());
1187 if (m_requestRole
[SizeRole
]) {
1189 data
.insert("size", QVariant());
1191 data
.insert("size", item
.size());
1195 if (m_requestRole
[DateRole
]) {
1196 // Don't use KFileItem::timeString() as this is too expensive when
1197 // having several thousands of items. Instead the formatting of the
1198 // date-time will be done on-demand by the view when the date will be shown.
1199 const KDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
1200 data
.insert("date", dateTime
.dateTime());
1203 if (m_requestRole
[PermissionsRole
]) {
1204 data
.insert("permissions", item
.permissionsString());
1207 if (m_requestRole
[OwnerRole
]) {
1208 data
.insert("owner", item
.user());
1211 if (m_requestRole
[GroupRole
]) {
1212 data
.insert("group", item
.group());
1215 if (m_requestRole
[DestinationRole
]) {
1216 QString destination
= item
.linkDest();
1217 if (destination
.isEmpty()) {
1218 destination
= QLatin1String("-");
1220 data
.insert("destination", destination
);
1223 if (m_requestRole
[PathRole
]) {
1225 if (item
.url().protocol() == QLatin1String("trash")) {
1226 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1228 // For performance reasons cache the home-path in a static QString
1229 // (see QDir::homePath() for more details)
1230 static QString homePath
;
1231 if (homePath
.isEmpty()) {
1232 homePath
= QDir::homePath();
1235 path
= item
.localPath();
1236 if (path
.startsWith(homePath
)) {
1237 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1241 const int index
= path
.lastIndexOf(item
.text());
1242 path
= path
.mid(0, index
- 1);
1243 data
.insert("path", path
);
1246 if (m_requestRole
[IsExpandedRole
]) {
1247 data
.insert("isExpanded", false);
1250 if (m_requestRole
[IsExpandableRole
]) {
1251 data
.insert("isExpandable", item
.isDir() && item
.url() == item
.targetUrl());
1254 if (m_requestRole
[ExpandedParentsCountRole
]) {
1255 if (m_expandedParentsCountRoot
== UninitializedExpandedParentsCountRoot
) {
1256 const KUrl rootUrl
= m_dirLister
->url();
1257 const QString protocol
= rootUrl
.protocol();
1258 const bool forceExpandedParentsCountRoot
= (protocol
== QLatin1String("trash") ||
1259 protocol
== QLatin1String("nepomuk") ||
1260 protocol
== QLatin1String("remote") ||
1261 protocol
.contains(QLatin1String("search")));
1262 if (forceExpandedParentsCountRoot
) {
1263 m_expandedParentsCountRoot
= ForceExpandedParentsCountRoot
;
1265 const QString rootDir
= rootUrl
.path(KUrl::AddTrailingSlash
);
1266 m_expandedParentsCountRoot
= rootDir
.count('/');
1270 if (m_expandedParentsCountRoot
== ForceExpandedParentsCountRoot
) {
1271 data
.insert("expandedParentsCount", -1);
1273 const QString dir
= item
.url().directory(KUrl::AppendTrailingSlash
);
1274 const int level
= dir
.count('/') - m_expandedParentsCountRoot
;
1275 data
.insert("expandedParentsCount", level
);
1279 if (item
.isMimeTypeKnown()) {
1280 data
.insert("iconName", item
.iconName());
1282 if (m_requestRole
[TypeRole
]) {
1283 data
.insert("type", item
.mimeComment());
1290 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
) const
1294 if (m_expandedParentsCountRoot
>= 0) {
1295 result
= expandedParentsCountCompare(a
, b
);
1297 // The items have parents with different expansion levels
1298 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1302 if (m_sortDirsFirst
|| m_sortRole
== SizeRole
) {
1303 const bool isDirA
= a
->item
.isDir();
1304 const bool isDirB
= b
->item
.isDir();
1305 if (isDirA
&& !isDirB
) {
1307 } else if (!isDirA
&& isDirB
) {
1312 result
= sortRoleCompare(a
, b
);
1314 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1317 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
) const
1319 const KFileItem
& itemA
= a
->item
;
1320 const KFileItem
& itemB
= b
->item
;
1324 switch (m_sortRole
) {
1326 // The name role is handled as default fallback after the switch
1330 if (itemA
.isDir()) {
1331 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1332 Q_ASSERT(itemB
.isDir());
1334 const QVariant valueA
= a
->values
.value("size");
1335 const QVariant valueB
= b
->values
.value("size");
1336 if (valueA
.isNull() && valueB
.isNull()) {
1338 } else if (valueA
.isNull()) {
1340 } else if (valueB
.isNull()) {
1343 result
= valueA
.toInt() - valueB
.toInt();
1346 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1347 Q_ASSERT(!itemB
.isDir());
1348 const KIO::filesize_t sizeA
= itemA
.size();
1349 const KIO::filesize_t sizeB
= itemB
.size();
1350 if (sizeA
> sizeB
) {
1352 } else if (sizeA
< sizeB
) {
1362 const KDateTime dateTimeA
= itemA
.time(KFileItem::ModificationTime
);
1363 const KDateTime dateTimeB
= itemB
.time(KFileItem::ModificationTime
);
1364 if (dateTimeA
< dateTimeB
) {
1366 } else if (dateTimeA
> dateTimeB
) {
1373 result
= a
->values
.value("rating").toInt() - b
->values
.value("rating").toInt();
1377 case ImageSizeRole
: {
1378 // Alway use a natural comparing to interpret the numbers of a string like
1379 // "1600 x 1200" for having a correct sorting.
1380 result
= KStringHandler::naturalCompare(a
->values
.value("imageSize").toString(),
1381 b
->values
.value("imageSize").toString(),
1387 const QByteArray role
= roleForType(m_sortRole
);
1388 result
= QString::compare(a
->values
.value(role
).toString(),
1389 b
->values
.value(role
).toString());
1396 // The current sort role was sufficient to define an order
1400 // Fallback #1: Compare the text of the items
1401 result
= stringCompare(itemA
.text(), itemB
.text());
1406 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1407 result
= stringCompare(itemA
.name(m_caseSensitivity
== Qt::CaseInsensitive
),
1408 itemB
.name(m_caseSensitivity
== Qt::CaseInsensitive
));
1413 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1414 // equal. In this case a comparison of the URL is done which is unique in all cases
1415 // within KDirLister.
1416 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1419 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
) const
1421 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1422 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1423 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1424 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1426 if (m_caseSensitivity
== Qt::CaseInsensitive
) {
1427 const int result
= m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseInsensitive
)
1428 : QString::compare(a
, b
, Qt::CaseInsensitive
);
1430 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1431 // comparison, still a deterministic sort order is required. A case sensitive
1432 // comparison is done as fallback.
1437 return m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseSensitive
)
1438 : QString::compare(a
, b
, Qt::CaseSensitive
);
1441 int KFileItemModel::expandedParentsCountCompare(const ItemData
* a
, const ItemData
* b
) const
1443 const KUrl urlA
= a
->item
.url();
1444 const KUrl urlB
= b
->item
.url();
1445 if (urlA
.directory() == urlB
.directory()) {
1446 // Both items have the same directory as parent
1450 // Check whether one item is the parent of the other item
1451 if (urlA
.isParentOf(urlB
)) {
1452 return (sortOrder() == Qt::AscendingOrder
) ? -1 : +1;
1453 } else if (urlB
.isParentOf(urlA
)) {
1454 return (sortOrder() == Qt::AscendingOrder
) ? +1 : -1;
1457 // Determine the maximum common path of both items and
1458 // remember the index in 'index'
1459 const QString pathA
= urlA
.path();
1460 const QString pathB
= urlB
.path();
1462 const int maxIndex
= qMin(pathA
.length(), pathB
.length()) - 1;
1464 while (index
<= maxIndex
&& pathA
.at(index
) == pathB
.at(index
)) {
1467 if (index
> maxIndex
) {
1470 while ((pathA
.at(index
) != QLatin1Char('/') || pathB
.at(index
) != QLatin1Char('/')) && index
> 0) {
1474 // Determine the first sub-path after the common path and
1475 // check whether it represents a directory or already a file
1477 const QString subPathA
= subPath(a
->item
, pathA
, index
, &isDirA
);
1479 const QString subPathB
= subPath(b
->item
, pathB
, index
, &isDirB
);
1481 if (m_sortDirsFirst
|| m_sortRole
== SizeRole
) {
1482 if (isDirA
&& !isDirB
) {
1483 return (sortOrder() == Qt::AscendingOrder
) ? -1 : +1;
1484 } else if (!isDirA
&& isDirB
) {
1485 return (sortOrder() == Qt::AscendingOrder
) ? +1 : -1;
1489 // Compare the items of the parents that represent the first
1490 // different path after the common path.
1491 const QString parentPathA
= pathA
.left(index
) + subPathA
;
1492 const QString parentPathB
= pathB
.left(index
) + subPathB
;
1494 const ItemData
* parentA
= a
;
1495 while (parentA
&& parentA
->item
.url().path() != parentPathA
) {
1496 parentA
= parentA
->parent
;
1499 const ItemData
* parentB
= b
;
1500 while (parentB
&& parentB
->item
.url().path() != parentPathB
) {
1501 parentB
= parentB
->parent
;
1504 if (parentA
&& parentB
) {
1505 return sortRoleCompare(parentA
, parentB
);
1508 kWarning() << "Child items without parent detected:" << a
->item
.url() << b
->item
.url();
1509 return QString::compare(urlA
.url(), urlB
.url(), Qt::CaseSensitive
);
1512 QString
KFileItemModel::subPath(const KFileItem
& item
,
1513 const QString
& itemPath
,
1518 const int pathIndex
= itemPath
.indexOf('/', start
+ 1);
1519 *isDir
= (pathIndex
> 0) || item
.isDir();
1520 return itemPath
.mid(start
, pathIndex
- start
);
1523 bool KFileItemModel::useMaximumUpdateInterval() const
1525 return !m_dirLister
->url().isLocalFile();
1528 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1530 Q_ASSERT(!m_itemData
.isEmpty());
1532 const int maxIndex
= count() - 1;
1533 QList
<QPair
<int, QVariant
> > groups
;
1537 bool isLetter
= false;
1538 for (int i
= 0; i
<= maxIndex
; ++i
) {
1539 if (isChildItem(i
)) {
1543 const QString name
= m_itemData
.at(i
)->values
.value("text").toString();
1545 // Use the first character of the name as group indication
1546 QChar newFirstChar
= name
.at(0).toUpper();
1547 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1548 newFirstChar
= name
.at(1).toUpper();
1551 if (firstChar
!= newFirstChar
) {
1552 QString newGroupValue
;
1553 if (newFirstChar
>= QLatin1Char('A') && newFirstChar
<= QLatin1Char('Z')) {
1554 // Apply group 'A' - 'Z'
1555 newGroupValue
= newFirstChar
;
1557 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
1558 // Apply group '0 - 9' for any name that starts with a digit
1559 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
1563 // If the current group is 'A' - 'Z' check whether a locale character
1564 // fits into the existing group.
1565 // TODO: This does not work in the case if e.g. the group 'O' starts with
1566 // an umlaut 'O' -> provide unit-test to document this known issue
1567 const QChar
prevChar(firstChar
.unicode() - ushort(1));
1568 const QChar
nextChar(firstChar
.unicode() + ushort(1));
1569 const QString
currChar(newFirstChar
);
1570 const bool partOfCurrentGroup
= currChar
.localeAwareCompare(prevChar
) > 0 &&
1571 currChar
.localeAwareCompare(nextChar
) < 0;
1572 if (partOfCurrentGroup
) {
1576 newGroupValue
= i18nc("@title:group", "Others");
1580 if (newGroupValue
!= groupValue
) {
1581 groupValue
= newGroupValue
;
1582 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1585 firstChar
= newFirstChar
;
1591 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
1593 Q_ASSERT(!m_itemData
.isEmpty());
1595 const int maxIndex
= count() - 1;
1596 QList
<QPair
<int, QVariant
> > groups
;
1599 for (int i
= 0; i
<= maxIndex
; ++i
) {
1600 if (isChildItem(i
)) {
1604 const KFileItem
& item
= m_itemData
.at(i
)->item
;
1605 const KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
1606 QString newGroupValue
;
1607 if (!item
.isNull() && item
.isDir()) {
1608 newGroupValue
= i18nc("@title:group Size", "Folders");
1609 } else if (fileSize
< 5 * 1024 * 1024) {
1610 newGroupValue
= i18nc("@title:group Size", "Small");
1611 } else if (fileSize
< 10 * 1024 * 1024) {
1612 newGroupValue
= i18nc("@title:group Size", "Medium");
1614 newGroupValue
= i18nc("@title:group Size", "Big");
1617 if (newGroupValue
!= groupValue
) {
1618 groupValue
= newGroupValue
;
1619 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1626 QList
<QPair
<int, QVariant
> > KFileItemModel::dateRoleGroups() const
1628 Q_ASSERT(!m_itemData
.isEmpty());
1630 const int maxIndex
= count() - 1;
1631 QList
<QPair
<int, QVariant
> > groups
;
1633 const QDate currentDate
= KDateTime::currentLocalDateTime().date();
1635 int yearForCurrentWeek
= 0;
1636 int currentWeek
= currentDate
.weekNumber(&yearForCurrentWeek
);
1637 if (yearForCurrentWeek
== currentDate
.year() + 1) {
1641 QDate previousModifiedDate
;
1643 for (int i
= 0; i
<= maxIndex
; ++i
) {
1644 if (isChildItem(i
)) {
1648 const KDateTime modifiedTime
= m_itemData
.at(i
)->item
.time(KFileItem::ModificationTime
);
1649 const QDate modifiedDate
= modifiedTime
.date();
1650 if (modifiedDate
== previousModifiedDate
) {
1651 // The current item is in the same group as the previous item
1654 previousModifiedDate
= modifiedDate
;
1656 const int daysDistance
= modifiedDate
.daysTo(currentDate
);
1658 int yearForModifiedWeek
= 0;
1659 int modifiedWeek
= modifiedDate
.weekNumber(&yearForModifiedWeek
);
1660 if (yearForModifiedWeek
== modifiedDate
.year() + 1) {
1664 QString newGroupValue
;
1665 if (currentDate
.year() == modifiedDate
.year() && currentDate
.month() == modifiedDate
.month()) {
1666 if (modifiedWeek
> currentWeek
) {
1667 // Usecase: modified date = 2010-01-01, current date = 2010-01-22
1668 // modified week = 53, current week = 3
1671 switch (currentWeek
- modifiedWeek
) {
1673 switch (daysDistance
) {
1674 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
1675 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
1676 default: newGroupValue
= modifiedTime
.toString(i18nc("@title:group The week day name: %A", "%A"));
1680 newGroupValue
= i18nc("@title:group Date", "Last Week");
1683 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
1686 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
1690 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
1696 const QDate lastMonthDate
= currentDate
.addMonths(-1);
1697 if (lastMonthDate
.year() == modifiedDate
.year() && lastMonthDate
.month() == modifiedDate
.month()) {
1698 if (daysDistance
== 1) {
1699 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Yesterday (%B, %Y)"));
1700 } else if (daysDistance
<= 7) {
1701 newGroupValue
= modifiedTime
.toString(i18nc("@title:group The week day name: %A, %B is full month name in current locale, and %Y is full year number", "%A (%B, %Y)"));
1702 } else if (daysDistance
<= 7 * 2) {
1703 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Last Week (%B, %Y)"));
1704 } else if (daysDistance
<= 7 * 3) {
1705 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Two Weeks Ago (%B, %Y)"));
1706 } else if (daysDistance
<= 7 * 4) {
1707 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Three Weeks Ago (%B, %Y)"));
1709 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Earlier on %B, %Y"));
1712 newGroupValue
= modifiedTime
.toString(i18nc("@title:group The month and year: %B is full month name in current locale, and %Y is full year number", "%B, %Y"));
1716 if (newGroupValue
!= groupValue
) {
1717 groupValue
= newGroupValue
;
1718 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1725 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
1727 Q_ASSERT(!m_itemData
.isEmpty());
1729 const int maxIndex
= count() - 1;
1730 QList
<QPair
<int, QVariant
> > groups
;
1732 QString permissionsString
;
1734 for (int i
= 0; i
<= maxIndex
; ++i
) {
1735 if (isChildItem(i
)) {
1739 const ItemData
* itemData
= m_itemData
.at(i
);
1740 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
1741 if (newPermissionsString
== permissionsString
) {
1744 permissionsString
= newPermissionsString
;
1746 const QFileInfo
info(itemData
->item
.url().pathOrUrl());
1750 if (info
.permission(QFile::ReadUser
)) {
1751 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1753 if (info
.permission(QFile::WriteUser
)) {
1754 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1756 if (info
.permission(QFile::ExeUser
)) {
1757 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1759 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
1763 if (info
.permission(QFile::ReadGroup
)) {
1764 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1766 if (info
.permission(QFile::WriteGroup
)) {
1767 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1769 if (info
.permission(QFile::ExeGroup
)) {
1770 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1772 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
1774 // Set others string
1776 if (info
.permission(QFile::ReadOther
)) {
1777 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1779 if (info
.permission(QFile::WriteOther
)) {
1780 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1782 if (info
.permission(QFile::ExeOther
)) {
1783 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1785 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
1787 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
1788 if (newGroupValue
!= groupValue
) {
1789 groupValue
= newGroupValue
;
1790 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1797 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
1799 Q_ASSERT(!m_itemData
.isEmpty());
1801 const int maxIndex
= count() - 1;
1802 QList
<QPair
<int, QVariant
> > groups
;
1804 int groupValue
= -1;
1805 for (int i
= 0; i
<= maxIndex
; ++i
) {
1806 if (isChildItem(i
)) {
1809 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
1810 if (newGroupValue
!= groupValue
) {
1811 groupValue
= newGroupValue
;
1812 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1819 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
1821 Q_ASSERT(!m_itemData
.isEmpty());
1823 const int maxIndex
= count() - 1;
1824 QList
<QPair
<int, QVariant
> > groups
;
1826 bool isFirstGroupValue
= true;
1828 for (int i
= 0; i
<= maxIndex
; ++i
) {
1829 if (isChildItem(i
)) {
1832 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
1833 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
1834 groupValue
= newGroupValue
;
1835 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1836 isFirstGroupValue
= false;
1843 KFileItemList
KFileItemModel::childItems(const KFileItem
& item
) const
1845 KFileItemList items
;
1847 int index
= m_items
.value(item
.url(), -1);
1849 const int parentLevel
= m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt();
1851 while (index
< m_itemData
.count() && m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt() > parentLevel
) {
1852 items
.append(m_itemData
.at(index
)->item
);
1860 void KFileItemModel::emitSortProgress(int resolvedCount
)
1862 // Be tolerant against a resolvedCount with a wrong range.
1863 // Although there should not be a case where KFileItemModelRolesUpdater
1864 // (= caller) provides a wrong range, it is important to emit
1865 // a useful progress information even if there is an unexpected
1866 // implementation issue.
1868 const int itemCount
= count();
1869 if (resolvedCount
>= itemCount
) {
1870 m_sortingProgressPercent
= -1;
1871 if (m_resortAllItemsTimer
->isActive()) {
1872 m_resortAllItemsTimer
->stop();
1876 emit
directorySortingProgress(100);
1877 } else if (itemCount
> 0) {
1878 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
1880 const int progress
= resolvedCount
* 100 / itemCount
;
1881 if (m_sortingProgressPercent
!= progress
) {
1882 m_sortingProgressPercent
= progress
;
1883 emit
directorySortingProgress(progress
);
1888 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
1890 static const RoleInfoMap rolesInfoMap
[] = {
1891 // | role | roleType | role translation | group translation | requires Nepomuk | requires indexer
1892 { 0, NoRole
, 0, 0, 0, 0, false, false },
1893 { "text", NameRole
, I18N_NOOP2_NOSTRIP("@label", "Name"), 0, 0, false, false },
1894 { "size", SizeRole
, I18N_NOOP2_NOSTRIP("@label", "Size"), 0, 0, false, false },
1895 { "date", DateRole
, I18N_NOOP2_NOSTRIP("@label", "Date"), 0, 0, false, false },
1896 { "type", TypeRole
, I18N_NOOP2_NOSTRIP("@label", "Type"), 0, 0, false, false },
1897 { "rating", RatingRole
, I18N_NOOP2_NOSTRIP("@label", "Rating"), 0, 0, true, false },
1898 { "tags", TagsRole
, I18N_NOOP2_NOSTRIP("@label", "Tags"), 0, 0, true, false },
1899 { "comment", CommentRole
, I18N_NOOP2_NOSTRIP("@label", "Comment"), 0, 0, true, false },
1900 { "wordCount", WordCountRole
, I18N_NOOP2_NOSTRIP("@label", "Word Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
1901 { "lineCount", LineCountRole
, I18N_NOOP2_NOSTRIP("@label", "Line Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
1902 { "imageSize", ImageSizeRole
, I18N_NOOP2_NOSTRIP("@label", "Image Size"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
1903 { "orientation", OrientationRole
, I18N_NOOP2_NOSTRIP("@label", "Orientation"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
1904 { "artist", ArtistRole
, I18N_NOOP2_NOSTRIP("@label", "Artist"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1905 { "album", AlbumRole
, I18N_NOOP2_NOSTRIP("@label", "Album"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1906 { "duration", DurationRole
, I18N_NOOP2_NOSTRIP("@label", "Duration"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1907 { "track", TrackRole
, I18N_NOOP2_NOSTRIP("@label", "Track"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1908 { "path", PathRole
, I18N_NOOP2_NOSTRIP("@label", "Path"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1909 { "destination", DestinationRole
, I18N_NOOP2_NOSTRIP("@label", "Link Destination"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1910 { "copiedFrom", CopiedFromRole
, I18N_NOOP2_NOSTRIP("@label", "Copied From"), I18N_NOOP2_NOSTRIP("@label", "Other"), true, false },
1911 { "permissions", PermissionsRole
, I18N_NOOP2_NOSTRIP("@label", "Permissions"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1912 { "owner", OwnerRole
, I18N_NOOP2_NOSTRIP("@label", "Owner"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1913 { "group", GroupRole
, I18N_NOOP2_NOSTRIP("@label", "User Group"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1916 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
1917 return rolesInfoMap
;
1920 void KFileItemModel::determineMimeTypes(const KFileItemList
& items
, int timeout
)
1922 QElapsedTimer timer
;
1924 foreach (KFileItem item
, items
) { // krazy:exclude=foreach
1925 item
.determineMimeType();
1926 if (timer
.elapsed() > timeout
) {
1927 // Don't block the user interface, let the remaining items
1928 // be resolved asynchronously.
1934 #include "kfileitemmodel.moc"