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"
24 #include "kfileitemmodelsortalgorithm_p.h"
25 #include <KGlobalSettings>
27 #include <KStringHandler>
33 // #define KFILEITEMMODEL_DEBUG
35 KFileItemModel::KFileItemModel(KDirLister
* dirLister
, QObject
* parent
) :
36 KItemModelBase("name", parent
),
37 m_dirLister(dirLister
),
38 m_naturalSorting(KGlobalSettings::naturalSorting()),
39 m_sortFoldersFirst(true),
41 m_sortProgressPercent(-1),
43 m_caseSensitivity(Qt::CaseInsensitive
),
49 m_maximumUpdateIntervalTimer(0),
50 m_resortAllItemsTimer(0),
51 m_pendingItemsToInsert(),
53 m_expandedParentsCountRoot(UninitializedExpandedParentsCountRoot
),
57 // Apply default roles that should be determined
59 m_requestRole
[NameRole
] = true;
60 m_requestRole
[IsDirRole
] = true;
61 m_roles
.insert("name");
62 m_roles
.insert("isDir");
66 connect(dirLister
, SIGNAL(canceled()), this, SLOT(slotCanceled()));
67 connect(dirLister
, SIGNAL(completed(KUrl
)), this, SLOT(slotCompleted()));
68 connect(dirLister
, SIGNAL(newItems(KFileItemList
)), this, SLOT(slotNewItems(KFileItemList
)));
69 connect(dirLister
, SIGNAL(itemsDeleted(KFileItemList
)), this, SLOT(slotItemsDeleted(KFileItemList
)));
70 connect(dirLister
, SIGNAL(refreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)), this, SLOT(slotRefreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)));
71 connect(dirLister
, SIGNAL(clear()), this, SLOT(slotClear()));
72 connect(dirLister
, SIGNAL(clear(KUrl
)), this, SLOT(slotClear(KUrl
)));
74 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
75 // before the completed() or canceled() signal has been emitted.
76 m_maximumUpdateIntervalTimer
= new QTimer(this);
77 m_maximumUpdateIntervalTimer
->setInterval(2000);
78 m_maximumUpdateIntervalTimer
->setSingleShot(true);
79 connect(m_maximumUpdateIntervalTimer
, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
81 // When changing the value of an item which represents the sort-role a resorting must be
82 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
83 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
84 // resorting is postponed until the timer has been exceeded.
85 m_resortAllItemsTimer
= new QTimer(this);
86 m_resortAllItemsTimer
->setInterval(500);
87 m_resortAllItemsTimer
->setSingleShot(true);
88 connect(m_resortAllItemsTimer
, SIGNAL(timeout()), this, SLOT(resortAllItems()));
90 connect(KGlobalSettings::self(), SIGNAL(naturalSortingChanged()), this, SLOT(slotNaturalSortingChanged()));
93 KFileItemModel::~KFileItemModel()
95 qDeleteAll(m_itemData
);
99 int KFileItemModel::count() const
101 return m_itemData
.count();
104 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
106 if (index
>= 0 && index
< count()) {
107 return m_itemData
.at(index
)->values
;
109 return QHash
<QByteArray
, QVariant
>();
112 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
114 if (index
< 0 || index
>= count()) {
118 QHash
<QByteArray
, QVariant
> currentValues
= m_itemData
.at(index
)->values
;
120 // Determine which roles have been changed
121 QSet
<QByteArray
> changedRoles
;
122 QHashIterator
<QByteArray
, QVariant
> it(values
);
123 while (it
.hasNext()) {
125 const QByteArray role
= it
.key();
126 const QVariant value
= it
.value();
128 if (currentValues
[role
] != value
) {
129 currentValues
[role
] = value
;
130 changedRoles
.insert(role
);
134 if (changedRoles
.isEmpty()) {
138 m_itemData
[index
]->values
= currentValues
;
139 emit
itemsChanged(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
141 if (changedRoles
.contains(sortRole())) {
142 m_resortAllItemsTimer
->start();
148 void KFileItemModel::setSortFoldersFirst(bool foldersFirst
)
150 if (foldersFirst
!= m_sortFoldersFirst
) {
151 m_sortFoldersFirst
= foldersFirst
;
156 bool KFileItemModel::sortFoldersFirst() const
158 return m_sortFoldersFirst
;
161 void KFileItemModel::setShowHiddenFiles(bool show
)
163 KDirLister
* dirLister
= m_dirLister
.data();
165 dirLister
->setShowingDotFiles(show
);
166 dirLister
->emitChanges();
173 bool KFileItemModel::showHiddenFiles() const
175 const KDirLister
* dirLister
= m_dirLister
.data();
176 return dirLister
? dirLister
->showingDotFiles() : false;
179 void KFileItemModel::setShowFoldersOnly(bool enabled
)
181 KDirLister
* dirLister
= m_dirLister
.data();
183 dirLister
->setDirOnlyMode(enabled
);
187 bool KFileItemModel::showFoldersOnly() const
189 KDirLister
* dirLister
= m_dirLister
.data();
190 return dirLister
? dirLister
->dirOnlyMode() : false;
193 QMimeData
* KFileItemModel::createMimeData(const QSet
<int>& indexes
) const
195 QMimeData
* data
= new QMimeData();
197 // The following code has been taken from KDirModel::mimeData()
198 // (kdelibs/kio/kio/kdirmodel.cpp)
199 // Copyright (C) 2006 David Faure <faure@kde.org>
201 KUrl::List mostLocalUrls
;
202 bool canUseMostLocalUrls
= true;
204 QSetIterator
<int> it(indexes
);
205 while (it
.hasNext()) {
206 const int index
= it
.next();
207 const KFileItem item
= fileItem(index
);
208 if (!item
.isNull()) {
212 mostLocalUrls
<< item
.mostLocalUrl(isLocal
);
214 canUseMostLocalUrls
= false;
219 const bool different
= canUseMostLocalUrls
&& mostLocalUrls
!= urls
;
220 urls
= KDirModel::simplifiedUrlList(urls
); // TODO: Check if we still need KDirModel for this in KDE 5.0
222 mostLocalUrls
= KDirModel::simplifiedUrlList(mostLocalUrls
);
223 urls
.populateMimeData(mostLocalUrls
, data
);
225 urls
.populateMimeData(data
);
231 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
233 startFromIndex
= qMax(0, startFromIndex
);
234 for (int i
= startFromIndex
; i
< count(); ++i
) {
235 if (data(i
)["name"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
239 for (int i
= 0; i
< startFromIndex
; ++i
) {
240 if (data(i
)["name"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
247 bool KFileItemModel::supportsDropping(int index
) const
249 const KFileItem item
= fileItem(index
);
250 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
253 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
255 static QHash
<QByteArray
, QString
> description
;
256 if (description
.isEmpty()) {
258 const RoleInfoMap
* map
= rolesInfoMap(count
);
259 for (int i
= 0; i
< count
; ++i
) {
260 description
.insert(map
[i
].role
, map
[i
].roleTranslation
);
264 return description
.value(role
);
267 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
269 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
270 #ifdef KFILEITEMMODEL_DEBUG
274 switch (typeForRole(sortRole())) {
275 case NameRole
: m_groups
= nameRoleGroups(); break;
276 case SizeRole
: m_groups
= sizeRoleGroups(); break;
277 case DateRole
: m_groups
= dateRoleGroups(); break;
278 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
279 case RatingRole
: m_groups
= ratingRoleGroups(); break;
280 default: m_groups
= genericStringRoleGroups(sortRole()); break;
283 #ifdef KFILEITEMMODEL_DEBUG
284 kDebug() << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
291 KFileItem
KFileItemModel::fileItem(int index
) const
293 if (index
>= 0 && index
< count()) {
294 return m_itemData
.at(index
)->item
;
300 KFileItem
KFileItemModel::fileItem(const KUrl
& url
) const
302 const int index
= m_items
.value(url
, -1);
304 return m_itemData
.at(index
)->item
;
309 int KFileItemModel::index(const KFileItem
& item
) const
315 return m_items
.value(item
.url(), -1);
318 int KFileItemModel::index(const KUrl
& url
) const
320 KUrl urlToFind
= url
;
321 urlToFind
.adjustPath(KUrl::RemoveTrailingSlash
);
322 return m_items
.value(urlToFind
, -1);
325 KFileItem
KFileItemModel::rootItem() const
327 const KDirLister
* dirLister
= m_dirLister
.data();
329 return dirLister
->rootItem();
334 void KFileItemModel::clear()
339 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
341 if (m_roles
== roles
) {
347 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
348 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
349 if (supportedExpanding
&& !willSupportExpanding
) {
350 // No expanding is supported anymore. Take care to delete all items that have an expansion level
351 // that is not 0 (and hence are part of an expanded item).
352 removeExpandedItems();
359 QSetIterator
<QByteArray
> it(roles
);
360 while (it
.hasNext()) {
361 const QByteArray
& role
= it
.next();
362 m_requestRole
[typeForRole(role
)] = true;
366 // Update m_data with the changed requested roles
367 const int maxIndex
= count() - 1;
368 for (int i
= 0; i
<= maxIndex
; ++i
) {
369 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
);
372 kWarning() << "TODO: Emitting itemsChanged() with no information what has changed!";
373 emit
itemsChanged(KItemRangeList() << KItemRange(0, count()), QSet
<QByteArray
>());
377 QSet
<QByteArray
> KFileItemModel::roles() const
382 bool KFileItemModel::setExpanded(int index
, bool expanded
)
384 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
388 QHash
<QByteArray
, QVariant
> values
;
389 values
.insert("isExpanded", expanded
);
390 if (!setData(index
, values
)) {
394 KDirLister
* dirLister
= m_dirLister
.data();
395 const KUrl url
= m_itemData
.at(index
)->item
.url();
397 m_expandedUrls
.insert(url
);
400 dirLister
->openUrl(url
, KDirLister::Keep
);
404 m_expandedUrls
.remove(url
);
407 dirLister
->stop(url
);
410 KFileItemList itemsToRemove
;
411 const int expandedParentsCount
= data(index
)["expandedParentsCount"].toInt();
413 while (index
< count() && data(index
)["expandedParentsCount"].toInt() > expandedParentsCount
) {
414 itemsToRemove
.append(m_itemData
.at(index
)->item
);
417 removeItems(itemsToRemove
);
424 bool KFileItemModel::isExpanded(int index
) const
426 if (index
>= 0 && index
< count()) {
427 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
432 bool KFileItemModel::isExpandable(int index
) const
434 if (index
>= 0 && index
< count()) {
435 return m_itemData
.at(index
)->values
.value("isExpandable").toBool();
440 int KFileItemModel::expandedParentsCount(int index
) const
442 if (index
>= 0 && index
< count()) {
443 const int parentsCount
= m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt();
444 if (parentsCount
> 0) {
451 QSet
<KUrl
> KFileItemModel::expandedUrls() const
453 return m_expandedUrls
;
456 void KFileItemModel::restoreExpandedUrls(const QSet
<KUrl
>& urls
)
458 m_urlsToExpand
= urls
;
461 void KFileItemModel::expandParentItems(const KUrl
& url
)
463 const KDirLister
* dirLister
= m_dirLister
.data();
468 const int pos
= dirLister
->url().path().length();
470 // Assure that each sub-path of the URL that should be
471 // expanded is added to m_urlsToExpand. KDirLister
472 // does not care whether the parent-URL has already been
474 KUrl urlToExpand
= dirLister
->url();
475 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator());
476 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
477 urlToExpand
.addPath(subDirs
.at(i
));
478 m_urlsToExpand
.insert(urlToExpand
);
481 // KDirLister::open() must called at least once to trigger an initial
482 // loading. The pending URLs that must be restored are handled
483 // in slotCompleted().
484 QSetIterator
<KUrl
> it2(m_urlsToExpand
);
485 while (it2
.hasNext()) {
486 const int idx
= index(it2
.next());
487 if (idx
>= 0 && !isExpanded(idx
)) {
488 setExpanded(idx
, true);
494 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
496 if (m_filter
.pattern() != nameFilter
) {
497 dispatchPendingItemsToInsert();
499 m_filter
.setPattern(nameFilter
);
501 // Check which shown items from m_itemData must get
502 // hidden and hence moved to m_filteredItems.
503 KFileItemList newFilteredItems
;
505 foreach (ItemData
* itemData
, m_itemData
) {
506 if (!m_filter
.matches(itemData
->item
)) {
507 // Only filter non-expanded items as child items may never
508 // exist without a parent item
509 if (!itemData
->values
.value("isExpanded").toBool()) {
510 newFilteredItems
.append(itemData
->item
);
511 m_filteredItems
.insert(itemData
->item
);
516 removeItems(newFilteredItems
);
518 // Check which hidden items from m_filteredItems should
519 // get visible again and hence removed from m_filteredItems.
520 KFileItemList newVisibleItems
;
522 QMutableSetIterator
<KFileItem
> it(m_filteredItems
);
523 while (it
.hasNext()) {
524 const KFileItem item
= it
.next();
525 if (m_filter
.matches(item
)) {
526 newVisibleItems
.append(item
);
527 m_filteredItems
.remove(item
);
531 insertItems(newVisibleItems
);
535 QString
KFileItemModel::nameFilter() const
537 return m_filter
.pattern();
540 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
542 static QList
<RoleInfo
> rolesInfo
;
543 if (rolesInfo
.isEmpty()) {
545 const RoleInfoMap
* map
= rolesInfoMap(count
);
546 for (int i
= 0; i
< count
; ++i
) {
547 if (map
[i
].roleType
!= NoRole
) {
549 info
.role
= map
[i
].role
;
550 info
.translation
= map
[i
].roleTranslation
;
551 info
.group
= map
[i
].groupTranslation
;
552 info
.requiresNepomuk
= map
[i
].requiresNepomuk
;
553 info
.requiresIndexer
= map
[i
].requiresIndexer
;
554 rolesInfo
.append(info
);
562 void KFileItemModel::onGroupedSortingChanged(bool current
)
568 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
571 m_sortRole
= typeForRole(current
);
573 #ifdef KFILEITEMMODEL_DEBUG
574 if (!m_requestRole
[m_sortRole
]) {
575 kWarning() << "The sort-role has been changed to a role that has not been received yet";
582 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
589 void KFileItemModel::resortAllItems()
591 m_resortAllItemsTimer
->stop();
593 const int itemCount
= count();
594 if (itemCount
<= 0) {
598 #ifdef KFILEITEMMODEL_DEBUG
601 kDebug() << "===========================================================";
602 kDebug() << "Resorting" << itemCount
<< "items";
605 // Remember the order of the current URLs so
606 // that it can be determined which indexes have
607 // been moved because of the resorting.
609 oldUrls
.reserve(itemCount
);
610 foreach (const ItemData
* itemData
, m_itemData
) {
611 oldUrls
.append(itemData
->item
.url());
618 KFileItemModelSortAlgorithm::sort(this, m_itemData
.begin(), m_itemData
.end());
619 for (int i
= 0; i
< itemCount
; ++i
) {
620 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
623 // Determine the indexes that have been moved
624 QList
<int> movedToIndexes
;
625 movedToIndexes
.reserve(itemCount
);
626 for (int i
= 0; i
< itemCount
; i
++) {
627 const int newIndex
= m_items
.value(oldUrls
.at(i
).url());
628 movedToIndexes
.append(newIndex
);
631 // Don't check whether items have really been moved and always emit a
632 // itemsMoved() signal after resorting: In case of grouped items
633 // the groups might change even if the items themselves don't change their
634 // position. Let the receiver of the signal decide whether a check for moved
635 // items makes sense.
636 emit
itemsMoved(KItemRange(0, itemCount
), movedToIndexes
);
638 #ifdef KFILEITEMMODEL_DEBUG
639 kDebug() << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
643 void KFileItemModel::slotCompleted()
645 dispatchPendingItemsToInsert();
647 if (!m_urlsToExpand
.isEmpty()) {
648 // Try to find a URL that can be expanded.
649 // Note that the parent folder must be expanded before any of its subfolders become visible.
650 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
651 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
652 foreach(const KUrl
& url
, m_urlsToExpand
) {
653 const int index
= m_items
.value(url
, -1);
655 m_urlsToExpand
.remove(url
);
656 if (setExpanded(index
, true)) {
657 // The dir lister has been triggered. This slot will be called
658 // again after the directory has been expanded.
664 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
665 // if these URLs have been deleted in the meantime.
666 m_urlsToExpand
.clear();
669 emit
loadingCompleted();
672 void KFileItemModel::slotCanceled()
674 m_maximumUpdateIntervalTimer
->stop();
675 dispatchPendingItemsToInsert();
678 void KFileItemModel::slotNewItems(const KFileItemList
& items
)
680 Q_ASSERT(!items
.isEmpty());
682 if (m_requestRole
[ExpandedParentsCountRole
] && m_expandedParentsCountRoot
>= 0) {
683 // To be able to compare whether the new items may be inserted as children
684 // of a parent item the pending items must be added to the model first.
685 dispatchPendingItemsToInsert();
687 KFileItem item
= items
.first();
689 // If the expanding of items is enabled, the call
690 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
691 // might result in emitting the same items twice due to the Keep-parameter.
692 // This case happens if an item gets expanded, collapsed and expanded again
693 // before the items could be loaded for the first expansion.
694 const int index
= m_items
.value(item
.url(), -1);
696 // The items are already part of the model.
700 // KDirLister keeps the children of items that got expanded once even if
701 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
702 // checked whether the parent for new items is still expanded.
703 KUrl parentUrl
= item
.url().upUrl();
704 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
705 const int parentIndex
= m_items
.value(parentUrl
, -1);
706 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
707 // The parent is not expanded.
712 if (m_filter
.pattern().isEmpty()) {
713 m_pendingItemsToInsert
.append(items
);
715 // The name-filter is active. Hide filtered items
716 // before inserting them into the model and remember
717 // the filtered items in m_filteredItems.
718 KFileItemList filteredItems
;
719 foreach (const KFileItem
& item
, items
) {
720 if (m_filter
.matches(item
)) {
721 filteredItems
.append(item
);
723 m_filteredItems
.insert(item
);
727 m_pendingItemsToInsert
.append(filteredItems
);
730 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer
->isActive()) {
731 // Assure that items get dispatched if no completed() or canceled() signal is
732 // emitted during the maximum update interval.
733 m_maximumUpdateIntervalTimer
->start();
737 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
739 dispatchPendingItemsToInsert();
741 KFileItemList itemsToRemove
= items
;
742 if (m_requestRole
[ExpandedParentsCountRole
] && m_expandedParentsCountRoot
>= 0) {
743 // Assure that removing a parent item also results in removing all children
744 foreach (const KFileItem
& item
, items
) {
745 itemsToRemove
.append(childItems(item
));
749 if (!m_filteredItems
.isEmpty()) {
750 foreach (const KFileItem
& item
, itemsToRemove
) {
751 m_filteredItems
.remove(item
);
755 removeItems(itemsToRemove
);
758 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
760 Q_ASSERT(!items
.isEmpty());
761 #ifdef KFILEITEMMODEL_DEBUG
762 kDebug() << "Refreshing" << items
.count() << "items";
767 // Get the indexes of all items that have been refreshed
769 indexes
.reserve(items
.count());
771 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
772 while (it
.hasNext()) {
773 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
774 const KFileItem
& oldItem
= itemPair
.first
;
775 const KFileItem
& newItem
= itemPair
.second
;
776 const int index
= m_items
.value(oldItem
.url(), -1);
778 m_itemData
[index
]->item
= newItem
;
780 // Keep old values as long as possible if they could not retrieved synchronously yet.
781 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
782 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
));
783 while (it
.hasNext()) {
785 m_itemData
[index
]->values
.insert(it
.key(), it
.value());
788 m_items
.remove(oldItem
.url());
789 m_items
.insert(newItem
.url(), index
);
790 indexes
.append(index
);
794 // If the changed items have been created recently, they might not be in m_items yet.
795 // In that case, the list 'indexes' might be empty.
796 if (indexes
.isEmpty()) {
800 // Extract the item-ranges out of the changed indexes
803 KItemRangeList itemRangeList
;
804 int previousIndex
= indexes
.at(0);
805 int rangeIndex
= previousIndex
;
808 const int maxIndex
= indexes
.count() - 1;
809 for (int i
= 1; i
<= maxIndex
; ++i
) {
810 const int currentIndex
= indexes
.at(i
);
811 if (currentIndex
== previousIndex
+ 1) {
814 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
816 rangeIndex
= currentIndex
;
819 previousIndex
= currentIndex
;
822 if (rangeCount
> 0) {
823 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
826 emit
itemsChanged(itemRangeList
, m_roles
);
831 void KFileItemModel::slotClear()
833 #ifdef KFILEITEMMODEL_DEBUG
834 kDebug() << "Clearing all items";
837 m_filteredItems
.clear();
840 m_maximumUpdateIntervalTimer
->stop();
841 m_resortAllItemsTimer
->stop();
842 m_pendingItemsToInsert
.clear();
844 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
846 const int removedCount
= m_itemData
.count();
847 if (removedCount
> 0) {
848 qDeleteAll(m_itemData
);
851 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
854 m_expandedUrls
.clear();
857 void KFileItemModel::slotClear(const KUrl
& url
)
862 void KFileItemModel::slotNaturalSortingChanged()
864 m_naturalSorting
= KGlobalSettings::naturalSorting();
868 void KFileItemModel::dispatchPendingItemsToInsert()
870 if (!m_pendingItemsToInsert
.isEmpty()) {
871 insertItems(m_pendingItemsToInsert
);
872 m_pendingItemsToInsert
.clear();
876 void KFileItemModel::insertItems(const KFileItemList
& items
)
878 if (items
.isEmpty()) {
882 if (m_sortRole
== TypeRole
) {
883 // Try to resolve the MIME-types synchronously to prevent a reordering of
884 // the items when sorting by type (per default MIME-types are resolved
885 // asynchronously by KFileItemModelRolesUpdater).
886 determineMimeTypes(items
, 200);
889 #ifdef KFILEITEMMODEL_DEBUG
892 kDebug() << "===========================================================";
893 kDebug() << "Inserting" << items
.count() << "items";
898 QList
<ItemData
*> sortedItems
= createItemDataList(items
);
899 KFileItemModelSortAlgorithm::sort(this, sortedItems
.begin(), sortedItems
.end());
901 #ifdef KFILEITEMMODEL_DEBUG
902 kDebug() << "[TIME] Sorting:" << timer
.elapsed();
905 KItemRangeList itemRanges
;
908 int insertedAtIndex
= -1; // Index for the current item-range
909 int insertedCount
= 0; // Count for the current item-range
910 int previouslyInsertedCount
= 0; // Sum of previously inserted items for all ranges
911 while (sourceIndex
< sortedItems
.count()) {
912 // Find target index from m_items to insert the current item
914 const int previousTargetIndex
= targetIndex
;
915 while (targetIndex
< m_itemData
.count()) {
916 if (!lessThan(m_itemData
.at(targetIndex
), sortedItems
.at(sourceIndex
))) {
922 if (targetIndex
- previousTargetIndex
> 0 && insertedAtIndex
>= 0) {
923 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
924 previouslyInsertedCount
+= insertedCount
;
925 insertedAtIndex
= targetIndex
- previouslyInsertedCount
;
929 // Insert item at the position targetIndex by transfering
930 // the ownership of the item-data from sortedItems to m_itemData.
931 // m_items will be inserted after the loop (see comment below)
932 m_itemData
.insert(targetIndex
, sortedItems
.at(sourceIndex
));
935 if (insertedAtIndex
< 0) {
936 insertedAtIndex
= targetIndex
;
937 Q_ASSERT(previouslyInsertedCount
== 0);
943 // The indexes of all m_items must be adjusted, not only the index
945 const int itemDataCount
= m_itemData
.count();
946 for (int i
= 0; i
< itemDataCount
; ++i
) {
947 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
950 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
951 emit
itemsInserted(itemRanges
);
953 #ifdef KFILEITEMMODEL_DEBUG
954 kDebug() << "[TIME] Inserting of" << items
.count() << "items:" << timer
.elapsed();
958 void KFileItemModel::removeItems(const KFileItemList
& items
)
960 if (items
.isEmpty()) {
964 #ifdef KFILEITEMMODEL_DEBUG
965 kDebug() << "Removing " << items
.count() << "items";
970 QList
<ItemData
*> sortedItems
;
971 sortedItems
.reserve(items
.count());
972 foreach (const KFileItem
& item
, items
) {
973 const int index
= m_items
.value(item
.url(), -1);
975 sortedItems
.append(m_itemData
.at(index
));
978 KFileItemModelSortAlgorithm::sort(this, sortedItems
.begin(), sortedItems
.end());
980 QList
<int> indexesToRemove
;
981 indexesToRemove
.reserve(items
.count());
983 // Calculate the item ranges that will get deleted
984 KItemRangeList itemRanges
;
985 int removedAtIndex
= -1;
986 int removedCount
= 0;
988 foreach (const ItemData
* itemData
, sortedItems
) {
989 const KFileItem
& itemToRemove
= itemData
->item
;
991 const int previousTargetIndex
= targetIndex
;
992 while (targetIndex
< m_itemData
.count()) {
993 if (m_itemData
.at(targetIndex
)->item
.url() == itemToRemove
.url()) {
998 if (targetIndex
>= m_itemData
.count()) {
999 kWarning() << "Item that should be deleted has not been found!";
1003 if (targetIndex
- previousTargetIndex
> 0 && removedAtIndex
>= 0) {
1004 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
1005 removedAtIndex
= targetIndex
;
1009 indexesToRemove
.append(targetIndex
);
1010 if (removedAtIndex
< 0) {
1011 removedAtIndex
= targetIndex
;
1018 for (int i
= indexesToRemove
.count() - 1; i
>= 0; --i
) {
1019 const int indexToRemove
= indexesToRemove
.at(i
);
1020 ItemData
* data
= m_itemData
.at(indexToRemove
);
1022 m_items
.remove(data
->item
.url());
1025 m_itemData
.removeAt(indexToRemove
);
1028 // The indexes of all m_items must be adjusted, not only the index
1029 // of the removed items
1030 const int itemDataCount
= m_itemData
.count();
1031 for (int i
= 0; i
< itemDataCount
; ++i
) {
1032 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
1036 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
1039 itemRanges
<< KItemRange(removedAtIndex
, removedCount
);
1040 emit
itemsRemoved(itemRanges
);
1043 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const KFileItemList
& items
) const
1045 QList
<ItemData
*> itemDataList
;
1046 itemDataList
.reserve(items
.count());
1048 foreach (const KFileItem
& item
, items
) {
1049 ItemData
* itemData
= new ItemData();
1050 itemData
->item
= item
;
1051 itemData
->values
= retrieveData(item
);
1052 itemData
->parent
= 0;
1054 const bool determineParent
= m_requestRole
[ExpandedParentsCountRole
]
1055 && itemData
->values
["expandedParentsCount"].toInt() > 0;
1056 if (determineParent
) {
1057 KUrl parentUrl
= item
.url().upUrl();
1058 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
1059 const int parentIndex
= m_items
.value(parentUrl
, -1);
1060 if (parentIndex
>= 0) {
1061 itemData
->parent
= m_itemData
.at(parentIndex
);
1063 kWarning() << "Parent item not found for" << item
.url();
1067 itemDataList
.append(itemData
);
1070 return itemDataList
;
1073 void KFileItemModel::removeExpandedItems()
1075 KFileItemList expandedItems
;
1077 const int maxIndex
= m_itemData
.count() - 1;
1078 for (int i
= 0; i
<= maxIndex
; ++i
) {
1079 const ItemData
* itemData
= m_itemData
.at(i
);
1080 if (itemData
->values
.value("expandedParentsCount").toInt() > 0) {
1081 expandedItems
.append(itemData
->item
);
1085 // The m_expandedParentsCountRoot may not get reset before all items with
1086 // a bigger count have been removed.
1087 removeItems(expandedItems
);
1089 m_expandedParentsCountRoot
= UninitializedExpandedParentsCountRoot
;
1090 m_expandedUrls
.clear();
1093 void KFileItemModel::resetRoles()
1095 for (int i
= 0; i
< RolesCount
; ++i
) {
1096 m_requestRole
[i
] = false;
1100 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1102 static QHash
<QByteArray
, RoleType
> roles
;
1103 if (roles
.isEmpty()) {
1104 // Insert user visible roles that can be accessed with
1105 // KFileItemModel::roleInformation()
1107 const RoleInfoMap
* map
= rolesInfoMap(count
);
1108 for (int i
= 0; i
< count
; ++i
) {
1109 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1112 // Insert internal roles (take care to synchronize the implementation
1113 // with KFileItemModel::roleForType() in case if a change is done).
1114 roles
.insert("isDir", IsDirRole
);
1115 roles
.insert("isExpanded", IsExpandedRole
);
1116 roles
.insert("isExpandable", IsExpandableRole
);
1117 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1119 Q_ASSERT(roles
.count() == RolesCount
);
1122 return roles
.value(role
, NoRole
);
1125 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1127 static QHash
<RoleType
, QByteArray
> roles
;
1128 if (roles
.isEmpty()) {
1129 // Insert user visible roles that can be accessed with
1130 // KFileItemModel::roleInformation()
1132 const RoleInfoMap
* map
= rolesInfoMap(count
);
1133 for (int i
= 0; i
< count
; ++i
) {
1134 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1137 // Insert internal roles (take care to synchronize the implementation
1138 // with KFileItemModel::typeForRole() in case if a change is done).
1139 roles
.insert(IsDirRole
, "isDir");
1140 roles
.insert(IsExpandedRole
, "isExpanded");
1141 roles
.insert(IsExpandableRole
, "isExpandable");
1142 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1144 Q_ASSERT(roles
.count() == RolesCount
);
1147 return roles
.value(roleType
);
1150 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
) const
1152 // It is important to insert only roles that are fast to retrieve. E.g.
1153 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1154 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1155 QHash
<QByteArray
, QVariant
> data
;
1156 data
.insert("url", item
.url());
1158 const bool isDir
= item
.isDir();
1159 if (m_requestRole
[IsDirRole
]) {
1160 data
.insert("isDir", isDir
);
1163 if (m_requestRole
[NameRole
]) {
1164 data
.insert("name", item
.text());
1167 if (m_requestRole
[SizeRole
]) {
1169 data
.insert("size", QVariant());
1171 data
.insert("size", item
.size());
1175 if (m_requestRole
[DateRole
]) {
1176 // Don't use KFileItem::timeString() as this is too expensive when
1177 // having several thousands of items. Instead the formatting of the
1178 // date-time will be done on-demand by the view when the date will be shown.
1179 const KDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
1180 data
.insert("date", dateTime
.dateTime());
1183 if (m_requestRole
[PermissionsRole
]) {
1184 data
.insert("permissions", item
.permissionsString());
1187 if (m_requestRole
[OwnerRole
]) {
1188 data
.insert("owner", item
.user());
1191 if (m_requestRole
[GroupRole
]) {
1192 data
.insert("group", item
.group());
1195 if (m_requestRole
[DestinationRole
]) {
1196 QString destination
= item
.linkDest();
1197 if (destination
.isEmpty()) {
1198 destination
= QLatin1String("-");
1200 data
.insert("destination", destination
);
1203 if (m_requestRole
[PathRole
]) {
1205 if (item
.url().protocol() == QLatin1String("trash")) {
1206 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1208 path
= item
.localPath();
1211 const int index
= path
.lastIndexOf(item
.text());
1212 path
= path
.mid(0, index
- 1);
1213 data
.insert("path", path
);
1216 if (m_requestRole
[IsExpandedRole
]) {
1217 data
.insert("isExpanded", false);
1220 if (m_requestRole
[IsExpandableRole
]) {
1221 data
.insert("isExpandable", item
.isDir() && item
.url() == item
.targetUrl());
1224 if (m_requestRole
[ExpandedParentsCountRole
]) {
1225 if (m_expandedParentsCountRoot
== UninitializedExpandedParentsCountRoot
&& m_dirLister
.data()) {
1226 const KUrl rootUrl
= m_dirLister
.data()->url();
1227 const QString protocol
= rootUrl
.protocol();
1228 const bool forceExpandedParentsCountRoot
= (protocol
== QLatin1String("trash") ||
1229 protocol
== QLatin1String("nepomuk") ||
1230 protocol
== QLatin1String("remote") ||
1231 protocol
.contains(QLatin1String("search")));
1232 if (forceExpandedParentsCountRoot
) {
1233 m_expandedParentsCountRoot
= ForceExpandedParentsCountRoot
;
1235 const QString rootDir
= rootUrl
.path(KUrl::AddTrailingSlash
);
1236 m_expandedParentsCountRoot
= rootDir
.count('/');
1240 if (m_expandedParentsCountRoot
== ForceExpandedParentsCountRoot
) {
1241 data
.insert("expandedParentsCount", -1);
1243 const QString dir
= item
.url().directory(KUrl::AppendTrailingSlash
);
1244 const int level
= dir
.count('/') - m_expandedParentsCountRoot
;
1245 data
.insert("expandedParentsCount", level
);
1249 if (item
.isMimeTypeKnown()) {
1250 data
.insert("iconName", item
.iconName());
1252 if (m_requestRole
[TypeRole
]) {
1253 data
.insert("type", item
.mimeComment());
1260 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
) const
1264 if (m_expandedParentsCountRoot
>= 0) {
1265 result
= expandedParentsCountCompare(a
, b
);
1267 // The items have parents with different expansion levels
1268 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1272 if (m_sortFoldersFirst
|| m_sortRole
== SizeRole
) {
1273 const bool isDirA
= a
->item
.isDir();
1274 const bool isDirB
= b
->item
.isDir();
1275 if (isDirA
&& !isDirB
) {
1277 } else if (!isDirA
&& isDirB
) {
1282 result
= sortRoleCompare(a
, b
);
1284 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1287 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
) const
1289 const KFileItem
& itemA
= a
->item
;
1290 const KFileItem
& itemB
= b
->item
;
1294 switch (m_sortRole
) {
1296 // The name role is handled as default fallback after the switch
1300 if (itemA
.isDir()) {
1301 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1302 Q_ASSERT(itemB
.isDir());
1304 const QVariant valueA
= a
->values
.value("size");
1305 const QVariant valueB
= b
->values
.value("size");
1306 if (valueA
.isNull() && valueB
.isNull()) {
1308 } else if (valueA
.isNull()) {
1310 } else if (valueB
.isNull()) {
1313 result
= valueA
.toInt() - valueB
.toInt();
1316 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1317 Q_ASSERT(!itemB
.isDir());
1318 const KIO::filesize_t sizeA
= itemA
.size();
1319 const KIO::filesize_t sizeB
= itemB
.size();
1320 if (sizeA
> sizeB
) {
1322 } else if (sizeA
< sizeB
) {
1332 const KDateTime dateTimeA
= itemA
.time(KFileItem::ModificationTime
);
1333 const KDateTime dateTimeB
= itemB
.time(KFileItem::ModificationTime
);
1334 if (dateTimeA
< dateTimeB
) {
1336 } else if (dateTimeA
> dateTimeB
) {
1343 result
= a
->values
.value("rating").toInt() - b
->values
.value("rating").toInt();
1347 case ImageSizeRole
: {
1348 // Alway use a natural comparing to interpret the numbers of a string like
1349 // "1600 x 1200" for having a correct sorting.
1350 result
= KStringHandler::naturalCompare(a
->values
.value("imageSize").toString(),
1351 b
->values
.value("imageSize").toString(),
1356 case PermissionsRole
:
1360 case DestinationRole
:
1364 const QByteArray role
= roleForType(m_sortRole
);
1365 result
= QString::compare(a
->values
.value(role
).toString(),
1366 b
->values
.value(role
).toString());
1375 // The current sort role was sufficient to define an order
1379 // Fallback #1: Compare the text of the items
1380 result
= stringCompare(itemA
.text(), itemB
.text());
1385 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1386 result
= stringCompare(itemA
.name(m_caseSensitivity
== Qt::CaseInsensitive
),
1387 itemB
.name(m_caseSensitivity
== Qt::CaseInsensitive
));
1392 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1393 // equal. In this case a comparison of the URL is done which is unique in all cases
1394 // within KDirLister.
1395 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1398 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
) const
1400 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1401 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1402 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1403 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1405 if (m_caseSensitivity
== Qt::CaseInsensitive
) {
1406 const int result
= m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseInsensitive
)
1407 : QString::compare(a
, b
, Qt::CaseInsensitive
);
1409 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1410 // comparison, still a deterministic sort order is required. A case sensitive
1411 // comparison is done as fallback.
1416 return m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseSensitive
)
1417 : QString::compare(a
, b
, Qt::CaseSensitive
);
1420 int KFileItemModel::expandedParentsCountCompare(const ItemData
* a
, const ItemData
* b
) const
1422 const KUrl urlA
= a
->item
.url();
1423 const KUrl urlB
= b
->item
.url();
1424 if (urlA
.directory() == urlB
.directory()) {
1425 // Both items have the same directory as parent
1429 // Check whether one item is the parent of the other item
1430 if (urlA
.isParentOf(urlB
)) {
1431 return (sortOrder() == Qt::AscendingOrder
) ? -1 : +1;
1432 } else if (urlB
.isParentOf(urlA
)) {
1433 return (sortOrder() == Qt::AscendingOrder
) ? +1 : -1;
1436 // Determine the maximum common path of both items and
1437 // remember the index in 'index'
1438 const QString pathA
= urlA
.path();
1439 const QString pathB
= urlB
.path();
1441 const int maxIndex
= qMin(pathA
.length(), pathB
.length()) - 1;
1443 while (index
<= maxIndex
&& pathA
.at(index
) == pathB
.at(index
)) {
1446 if (index
> maxIndex
) {
1449 while ((pathA
.at(index
) != QLatin1Char('/') || pathB
.at(index
) != QLatin1Char('/')) && index
> 0) {
1453 // Determine the first sub-path after the common path and
1454 // check whether it represents a directory or already a file
1456 const QString subPathA
= subPath(a
->item
, pathA
, index
, &isDirA
);
1458 const QString subPathB
= subPath(b
->item
, pathB
, index
, &isDirB
);
1460 if (m_sortFoldersFirst
|| m_sortRole
== SizeRole
) {
1461 if (isDirA
&& !isDirB
) {
1462 return (sortOrder() == Qt::AscendingOrder
) ? -1 : +1;
1463 } else if (!isDirA
&& isDirB
) {
1464 return (sortOrder() == Qt::AscendingOrder
) ? +1 : -1;
1468 // Compare the items of the parents that represent the first
1469 // different path after the common path.
1470 const QString parentPathA
= pathA
.left(index
) + subPathA
;
1471 const QString parentPathB
= pathB
.left(index
) + subPathB
;
1473 const ItemData
* parentA
= a
;
1474 while (parentA
&& parentA
->item
.url().path() != parentPathA
) {
1475 parentA
= parentA
->parent
;
1478 const ItemData
* parentB
= b
;
1479 while (parentB
&& parentB
->item
.url().path() != parentPathB
) {
1480 parentB
= parentB
->parent
;
1483 if (parentA
&& parentB
) {
1484 return sortRoleCompare(parentA
, parentB
);
1487 kWarning() << "Child items without parent detected:" << a
->item
.url() << b
->item
.url();
1488 return QString::compare(urlA
.url(), urlB
.url(), Qt::CaseSensitive
);
1491 QString
KFileItemModel::subPath(const KFileItem
& item
,
1492 const QString
& itemPath
,
1497 const int pathIndex
= itemPath
.indexOf('/', start
+ 1);
1498 *isDir
= (pathIndex
> 0) || item
.isDir();
1499 return itemPath
.mid(start
, pathIndex
- start
);
1502 bool KFileItemModel::useMaximumUpdateInterval() const
1504 const KDirLister
* dirLister
= m_dirLister
.data();
1505 return dirLister
&& !dirLister
->url().isLocalFile();
1508 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1510 Q_ASSERT(!m_itemData
.isEmpty());
1512 const int maxIndex
= count() - 1;
1513 QList
<QPair
<int, QVariant
> > groups
;
1517 bool isLetter
= false;
1518 for (int i
= 0; i
<= maxIndex
; ++i
) {
1519 if (isChildItem(i
)) {
1523 const QString name
= m_itemData
.at(i
)->values
.value("name").toString();
1525 // Use the first character of the name as group indication
1526 QChar newFirstChar
= name
.at(0).toUpper();
1527 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1528 newFirstChar
= name
.at(1).toUpper();
1531 if (firstChar
!= newFirstChar
) {
1532 QString newGroupValue
;
1533 if (newFirstChar
>= QLatin1Char('A') && newFirstChar
<= QLatin1Char('Z')) {
1534 // Apply group 'A' - 'Z'
1535 newGroupValue
= newFirstChar
;
1537 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
1538 // Apply group '0 - 9' for any name that starts with a digit
1539 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
1543 // If the current group is 'A' - 'Z' check whether a locale character
1544 // fits into the existing group.
1545 // TODO: This does not work in the case if e.g. the group 'O' starts with
1546 // an umlaut 'O' -> provide unit-test to document this known issue
1547 const QChar
prevChar(firstChar
.unicode() - ushort(1));
1548 const QChar
nextChar(firstChar
.unicode() + ushort(1));
1549 const QString
currChar(newFirstChar
);
1550 const bool partOfCurrentGroup
= currChar
.localeAwareCompare(prevChar
) > 0 &&
1551 currChar
.localeAwareCompare(nextChar
) < 0;
1552 if (partOfCurrentGroup
) {
1556 newGroupValue
= i18nc("@title:group", "Others");
1560 if (newGroupValue
!= groupValue
) {
1561 groupValue
= newGroupValue
;
1562 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1565 firstChar
= newFirstChar
;
1571 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
1573 Q_ASSERT(!m_itemData
.isEmpty());
1575 const int maxIndex
= count() - 1;
1576 QList
<QPair
<int, QVariant
> > groups
;
1579 for (int i
= 0; i
<= maxIndex
; ++i
) {
1580 if (isChildItem(i
)) {
1584 const KFileItem
& item
= m_itemData
.at(i
)->item
;
1585 const KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
1586 QString newGroupValue
;
1587 if (!item
.isNull() && item
.isDir()) {
1588 newGroupValue
= i18nc("@title:group Size", "Folders");
1589 } else if (fileSize
< 5 * 1024 * 1024) {
1590 newGroupValue
= i18nc("@title:group Size", "Small");
1591 } else if (fileSize
< 10 * 1024 * 1024) {
1592 newGroupValue
= i18nc("@title:group Size", "Medium");
1594 newGroupValue
= i18nc("@title:group Size", "Big");
1597 if (newGroupValue
!= groupValue
) {
1598 groupValue
= newGroupValue
;
1599 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1606 QList
<QPair
<int, QVariant
> > KFileItemModel::dateRoleGroups() const
1608 Q_ASSERT(!m_itemData
.isEmpty());
1610 const int maxIndex
= count() - 1;
1611 QList
<QPair
<int, QVariant
> > groups
;
1613 const QDate currentDate
= KDateTime::currentLocalDateTime().date();
1615 int yearForCurrentWeek
= 0;
1616 int currentWeek
= currentDate
.weekNumber(&yearForCurrentWeek
);
1617 if (yearForCurrentWeek
== currentDate
.year() + 1) {
1621 QDate previousModifiedDate
;
1623 for (int i
= 0; i
<= maxIndex
; ++i
) {
1624 if (isChildItem(i
)) {
1628 const KDateTime modifiedTime
= m_itemData
.at(i
)->item
.time(KFileItem::ModificationTime
);
1629 const QDate modifiedDate
= modifiedTime
.date();
1630 if (modifiedDate
== previousModifiedDate
) {
1631 // The current item is in the same group as the previous item
1634 previousModifiedDate
= modifiedDate
;
1636 const int daysDistance
= modifiedDate
.daysTo(currentDate
);
1638 int yearForModifiedWeek
= 0;
1639 int modifiedWeek
= modifiedDate
.weekNumber(&yearForModifiedWeek
);
1640 if (yearForModifiedWeek
== modifiedDate
.year() + 1) {
1644 QString newGroupValue
;
1645 if (currentDate
.year() == modifiedDate
.year() && currentDate
.month() == modifiedDate
.month()) {
1646 if (modifiedWeek
> currentWeek
) {
1647 // Usecase: modified date = 2010-01-01, current date = 2010-01-22
1648 // modified week = 53, current week = 3
1651 switch (currentWeek
- modifiedWeek
) {
1653 switch (daysDistance
) {
1654 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
1655 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
1656 default: newGroupValue
= modifiedTime
.toString(i18nc("@title:group The week day name: %A", "%A"));
1660 newGroupValue
= i18nc("@title:group Date", "Last Week");
1663 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
1666 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
1670 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
1676 const QDate lastMonthDate
= currentDate
.addMonths(-1);
1677 if (lastMonthDate
.year() == modifiedDate
.year() && lastMonthDate
.month() == modifiedDate
.month()) {
1678 if (daysDistance
== 1) {
1679 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Yesterday (%B, %Y)"));
1680 } else if (daysDistance
<= 7) {
1681 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)"));
1682 } else if (daysDistance
<= 7 * 2) {
1683 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)"));
1684 } else if (daysDistance
<= 7 * 3) {
1685 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)"));
1686 } else if (daysDistance
<= 7 * 4) {
1687 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)"));
1689 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"));
1692 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"));
1696 if (newGroupValue
!= groupValue
) {
1697 groupValue
= newGroupValue
;
1698 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1705 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
1707 Q_ASSERT(!m_itemData
.isEmpty());
1709 const int maxIndex
= count() - 1;
1710 QList
<QPair
<int, QVariant
> > groups
;
1712 QString permissionsString
;
1714 for (int i
= 0; i
<= maxIndex
; ++i
) {
1715 if (isChildItem(i
)) {
1719 const ItemData
* itemData
= m_itemData
.at(i
);
1720 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
1721 if (newPermissionsString
== permissionsString
) {
1724 permissionsString
= newPermissionsString
;
1726 const QFileInfo
info(itemData
->item
.url().pathOrUrl());
1730 if (info
.permission(QFile::ReadUser
)) {
1731 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1733 if (info
.permission(QFile::WriteUser
)) {
1734 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1736 if (info
.permission(QFile::ExeUser
)) {
1737 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1739 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
1743 if (info
.permission(QFile::ReadGroup
)) {
1744 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1746 if (info
.permission(QFile::WriteGroup
)) {
1747 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1749 if (info
.permission(QFile::ExeGroup
)) {
1750 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1752 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
1754 // Set others string
1756 if (info
.permission(QFile::ReadOther
)) {
1757 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1759 if (info
.permission(QFile::WriteOther
)) {
1760 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1762 if (info
.permission(QFile::ExeOther
)) {
1763 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1765 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
1767 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
1768 if (newGroupValue
!= groupValue
) {
1769 groupValue
= newGroupValue
;
1770 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1777 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
1779 Q_ASSERT(!m_itemData
.isEmpty());
1781 const int maxIndex
= count() - 1;
1782 QList
<QPair
<int, QVariant
> > groups
;
1784 int groupValue
= -1;
1785 for (int i
= 0; i
<= maxIndex
; ++i
) {
1786 if (isChildItem(i
)) {
1789 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
1790 if (newGroupValue
!= groupValue
) {
1791 groupValue
= newGroupValue
;
1792 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1799 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
1801 Q_ASSERT(!m_itemData
.isEmpty());
1803 const int maxIndex
= count() - 1;
1804 QList
<QPair
<int, QVariant
> > groups
;
1806 bool isFirstGroupValue
= true;
1808 for (int i
= 0; i
<= maxIndex
; ++i
) {
1809 if (isChildItem(i
)) {
1812 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
1813 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
1814 groupValue
= newGroupValue
;
1815 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1816 isFirstGroupValue
= false;
1823 KFileItemList
KFileItemModel::childItems(const KFileItem
& item
) const
1825 KFileItemList items
;
1827 int index
= m_items
.value(item
.url(), -1);
1829 const int parentLevel
= m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt();
1831 while (index
< m_itemData
.count() && m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt() > parentLevel
) {
1832 items
.append(m_itemData
.at(index
)->item
);
1840 void KFileItemModel::emitSortProgress(int resolvedCount
)
1842 // Be tolerant against a resolvedCount with a wrong range.
1843 // Although there should not be a case where KFileItemModelRolesUpdater
1844 // (= caller) provides a wrong range, it is important to emit
1845 // a useful progress information even if there is an unexpected
1846 // implementation issue.
1848 const int itemCount
= count();
1849 if (resolvedCount
>= itemCount
) {
1850 m_sortProgressPercent
= -1;
1851 if (m_resortAllItemsTimer
->isActive()) {
1852 m_resortAllItemsTimer
->stop();
1856 emit
sortProgress(100);
1857 } else if (itemCount
> 0) {
1858 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
1860 const int progress
= resolvedCount
* 100 / itemCount
;
1861 if (m_sortProgressPercent
!= progress
) {
1862 m_sortProgressPercent
= progress
;
1863 emit
sortProgress(progress
);
1868 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
1870 static const RoleInfoMap rolesInfoMap
[] = {
1871 // | role | roleType | role translation | group translation | requires Nepomuk | requires indexer
1872 { 0, NoRole
, 0, 0, 0, 0, false, false },
1873 { "name", NameRole
, I18N_NOOP2_NOSTRIP("@label", "Name"), 0, 0, false, false },
1874 { "size", SizeRole
, I18N_NOOP2_NOSTRIP("@label", "Size"), 0, 0, false, false },
1875 { "date", DateRole
, I18N_NOOP2_NOSTRIP("@label", "Date"), 0, 0, false, false },
1876 { "type", TypeRole
, I18N_NOOP2_NOSTRIP("@label", "Type"), 0, 0, false, false },
1877 { "rating", RatingRole
, I18N_NOOP2_NOSTRIP("@label", "Rating"), 0, 0, true, false },
1878 { "tags", TagsRole
, I18N_NOOP2_NOSTRIP("@label", "Tags"), 0, 0, true, false },
1879 { "comment", CommentRole
, I18N_NOOP2_NOSTRIP("@label", "Comment"), 0, 0, true, false },
1880 { "wordCount", WordCountRole
, I18N_NOOP2_NOSTRIP("@label", "Word Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
1881 { "lineCount", LineCountRole
, I18N_NOOP2_NOSTRIP("@label", "Line Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
1882 { "imageSize", ImageSizeRole
, I18N_NOOP2_NOSTRIP("@label", "Image Size"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
1883 { "orientation", OrientationRole
, I18N_NOOP2_NOSTRIP("@label", "Orientation"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
1884 { "artist", ArtistRole
, I18N_NOOP2_NOSTRIP("@label", "Artist"), I18N_NOOP2_NOSTRIP("@label", "Music"), true, true },
1885 { "album", AlbumRole
, I18N_NOOP2_NOSTRIP("@label", "Album"), I18N_NOOP2_NOSTRIP("@label", "Music"), true, true },
1886 { "duration", DurationRole
, I18N_NOOP2_NOSTRIP("@label", "Duration"), I18N_NOOP2_NOSTRIP("@label", "Music"), true, true },
1887 { "track", TrackRole
, I18N_NOOP2_NOSTRIP("@label", "Track"), I18N_NOOP2_NOSTRIP("@label", "Music"), true, true },
1888 { "path", PathRole
, I18N_NOOP2_NOSTRIP("@label", "Path"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1889 { "destination", DestinationRole
, I18N_NOOP2_NOSTRIP("@label", "Link Destination"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1890 { "copiedFrom", CopiedFromRole
, I18N_NOOP2_NOSTRIP("@label", "Copied From"), I18N_NOOP2_NOSTRIP("@label", "Other"), true, false },
1891 { "permissions", PermissionsRole
, I18N_NOOP2_NOSTRIP("@label", "Permissions"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1892 { "owner", OwnerRole
, I18N_NOOP2_NOSTRIP("@label", "Owner"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1893 { "group", GroupRole
, I18N_NOOP2_NOSTRIP("@label", "User Group"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1896 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
1897 return rolesInfoMap
;
1900 void KFileItemModel::determineMimeTypes(const KFileItemList
& items
, int timeout
)
1902 QElapsedTimer timer
;
1904 foreach (KFileItem item
, items
) {
1905 item
.determineMimeType();
1906 if (timer
.elapsed() > timeout
) {
1907 // Don't block the user interface, let the remaining items
1908 // be resolved asynchronously.
1914 #include "kfileitemmodel.moc"