X-Git-Url: https://cloud.milkyroute.net/gitweb/dolphin.git/blobdiff_plain/f63daef339dde16c7ef598f6fdaa5d2191da4685..e7390eba86f123fe3899d1f42c8e148aba52cf4d:/src/kitemviews/kfileitemmodel.cpp diff --git a/src/kitemviews/kfileitemmodel.cpp b/src/kitemviews/kfileitemmodel.cpp index 272654872..c0c442e23 100644 --- a/src/kitemviews/kfileitemmodel.cpp +++ b/src/kitemviews/kfileitemmodel.cpp @@ -36,13 +36,14 @@ KFileItemModel::KFileItemModel(KDirLister* dirLister, QObject* parent) : m_naturalSorting(true), m_sortFoldersFirst(true), m_sortRole(NameRole), + m_roles(), m_caseSensitivity(Qt::CaseInsensitive), - m_sortedItems(), + m_itemData(), m_items(), - m_data(), m_requestRole(), m_minimumUpdateIntervalTimer(0), m_maximumUpdateIntervalTimer(0), + m_resortAllItemsTimer(0), m_pendingItemsToInsert(), m_pendingEmitLoadingCompleted(false), m_groups(), @@ -50,9 +51,12 @@ KFileItemModel::KFileItemModel(KDirLister* dirLister, QObject* parent) : m_expandedUrls(), m_restoredExpandedUrls() { + // Apply default roles that should be determined resetRoles(); m_requestRole[NameRole] = true; m_requestRole[IsDirRole] = true; + m_roles.insert("name"); + m_roles.insert("isDir"); Q_ASSERT(dirLister); @@ -78,53 +82,72 @@ KFileItemModel::KFileItemModel(KDirLister* dirLister, QObject* parent) : m_maximumUpdateIntervalTimer->setInterval(2000); m_maximumUpdateIntervalTimer->setSingleShot(true); connect(m_maximumUpdateIntervalTimer, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert())); + + // When changing the value of an item which represents the sort-role a resorting must be + // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done + // for a lot of items within a quite small timeslot. To prevent expensive resortings the + // resorting is postponed until the timer has been exceeded. + m_resortAllItemsTimer = new QTimer(this); + m_resortAllItemsTimer->setInterval(500); + m_resortAllItemsTimer->setSingleShot(true); + connect(m_resortAllItemsTimer, SIGNAL(timeout()), this, SLOT(resortAllItems())); Q_ASSERT(m_minimumUpdateIntervalTimer->interval() <= m_maximumUpdateIntervalTimer->interval()); } KFileItemModel::~KFileItemModel() { + qDeleteAll(m_itemData); + m_itemData.clear(); } int KFileItemModel::count() const { - return m_data.count(); + return m_itemData.count(); } QHash KFileItemModel::data(int index) const { if (index >= 0 && index < count()) { - return m_data.at(index); + return m_itemData.at(index)->values; } return QHash(); } bool KFileItemModel::setData(int index, const QHash& values) { - if (index >= 0 && index < count()) { - QHash currentValue = m_data.at(index); - - QSet changedRoles; - QHashIterator it(values); - while (it.hasNext()) { - it.next(); - const QByteArray role = it.key(); - const QVariant value = it.value(); - - if (currentValue[role] != value) { - currentValue[role] = value; - changedRoles.insert(role); - } - } + if (index < 0 || index >= count()) { + return false; + } + + QHash currentValues = m_itemData.at(index)->values; + + // Determine which roles have been changed + QSet changedRoles; + QHashIterator it(values); + while (it.hasNext()) { + it.next(); + const QByteArray role = it.key(); + const QVariant value = it.value(); - if (!changedRoles.isEmpty()) { - m_data[index] = currentValue; - emit itemsChanged(KItemRangeList() << KItemRange(index, 1), changedRoles); + if (currentValues[role] != value) { + currentValues[role] = value; + changedRoles.insert(role); } + } - return true; + if (changedRoles.isEmpty()) { + return false; } - return false; + + m_itemData[index]->values = currentValues; + emit itemsChanged(KItemRangeList() << KItemRange(index, 1), changedRoles); + + if (changedRoles.contains(sortRole())) { + m_resortAllItemsTimer->start(); + } + + return true; } void KFileItemModel::setSortFoldersFirst(bool foldersFirst) @@ -214,6 +237,9 @@ QString KFileItemModel::roleDescription(const QByteArray& role) const case TypeRole: descr = i18nc("@item:intable", "Type"); break; case DestinationRole: descr = i18nc("@item:intable", "Destination"); break; case PathRole: descr = i18nc("@item:intable", "Path"); break; + case CommentRole: descr = i18nc("@item:intable", "Comment"); break; + case TagsRole: descr = i18nc("@item:intable", "Tags"); break; + case RatingRole: descr = i18nc("@item:intable", "Rating"); break; case NoRole: break; case IsDirRole: break; case IsExpandedRole: break; @@ -226,7 +252,7 @@ QString KFileItemModel::roleDescription(const QByteArray& role) const QList > KFileItemModel::groups() const { - if (!m_data.isEmpty() && m_groups.isEmpty()) { + if (!m_itemData.isEmpty() && m_groups.isEmpty()) { #ifdef KFILEITEMMODEL_DEBUG QElapsedTimer timer; timer.start(); @@ -236,11 +262,14 @@ QList > KFileItemModel::groups() const case SizeRole: m_groups = sizeRoleGroups(); break; case DateRole: m_groups = dateRoleGroups(); break; case PermissionsRole: m_groups = permissionRoleGroups(); break; - case OwnerRole: m_groups = ownerRoleGroups(); break; - case GroupRole: m_groups = groupRoleGroups(); break; - case TypeRole: m_groups = typeRoleGroups(); break; - case DestinationRole: m_groups = destinationRoleGroups(); break; - case PathRole: m_groups = pathRoleGroups(); break; + case OwnerRole: m_groups = genericStringRoleGroups("owner"); break; + case GroupRole: m_groups = genericStringRoleGroups("group"); break; + case TypeRole: m_groups = genericStringRoleGroups("type"); break; + case DestinationRole: m_groups = genericStringRoleGroups("destination"); break; + case PathRole: m_groups = genericStringRoleGroups("path"); break; + case CommentRole: m_groups = genericStringRoleGroups("comment"); break; + case TagsRole: m_groups = genericStringRoleGroups("tags"); break; + case RatingRole: m_groups = ratingRoleGroups(); break; case NoRole: break; case IsDirRole: break; case IsExpandedRole: break; @@ -259,7 +288,7 @@ QList > KFileItemModel::groups() const KFileItem KFileItemModel::fileItem(int index) const { if (index >= 0 && index < count()) { - return m_sortedItems.at(index); + return m_itemData.at(index)->item; } return KFileItem(); @@ -269,7 +298,7 @@ KFileItem KFileItemModel::fileItem(const KUrl& url) const { const int index = m_items.value(url, -1); if (index >= 0) { - return m_sortedItems.at(index); + return m_itemData.at(index)->item; } return KFileItem(); } @@ -306,6 +335,8 @@ void KFileItemModel::clear() void KFileItemModel::setRoles(const QSet& roles) { + m_roles = roles; + if (count() > 0) { const bool supportedExpanding = m_requestRole[IsExpandedRole] && m_requestRole[ExpansionLevelRole]; const bool willSupportExpanding = roles.contains("isExpanded") && roles.contains("expansionLevel"); @@ -317,6 +348,7 @@ void KFileItemModel::setRoles(const QSet& roles) } resetRoles(); + QSetIterator it(roles); while (it.hasNext()) { const QByteArray& role = it.next(); @@ -327,7 +359,7 @@ void KFileItemModel::setRoles(const QSet& roles) // Update m_data with the changed requested roles const int maxIndex = count() - 1; for (int i = 0; i <= maxIndex; ++i) { - m_data[i] = retrieveData(m_sortedItems.at(i)); + m_itemData[i]->values = retrieveData(m_itemData.at(i)->item); } kWarning() << "TODO: Emitting itemsChanged() with no information what has changed!"; @@ -337,28 +369,7 @@ void KFileItemModel::setRoles(const QSet& roles) QSet KFileItemModel::roles() const { - QSet roles; - for (int i = 0; i < RolesCount; ++i) { - if (m_requestRole[i]) { - switch (i) { - case NoRole: break; - case NameRole: roles.insert("name"); break; - case SizeRole: roles.insert("size"); break; - case DateRole: roles.insert("date"); break; - case PermissionsRole: roles.insert("permissions"); break; - case OwnerRole: roles.insert("owner"); break; - case GroupRole: roles.insert("group"); break; - case TypeRole: roles.insert("type"); break; - case DestinationRole: roles.insert("destination"); break; - case PathRole: roles.insert("path"); break; - case IsDirRole: roles.insert("isDir"); break; - case IsExpandedRole: roles.insert("isExpanded"); break; - case ExpansionLevelRole: roles.insert("expansionLevel"); break; - default: Q_ASSERT(false); break; - } - } - } - return roles; + return m_roles; } bool KFileItemModel::setExpanded(int index, bool expanded) @@ -373,7 +384,7 @@ bool KFileItemModel::setExpanded(int index, bool expanded) return false; } - const KUrl url = m_sortedItems.at(index).url(); + const KUrl url = m_itemData.at(index)->item.url(); if (expanded) { m_expandedUrls.insert(url); @@ -389,7 +400,7 @@ bool KFileItemModel::setExpanded(int index, bool expanded) const int expansionLevel = data(index)["expansionLevel"].toInt(); ++index; while (index < count() && data(index)["expansionLevel"].toInt() > expansionLevel) { - itemsToRemove.append(m_sortedItems.at(index)); + itemsToRemove.append(m_itemData.at(index)->item); ++index; } removeItems(itemsToRemove); @@ -402,7 +413,7 @@ bool KFileItemModel::setExpanded(int index, bool expanded) bool KFileItemModel::isExpanded(int index) const { if (index >= 0 && index < count()) { - return m_data.at(index).value("isExpanded").toBool(); + return m_itemData.at(index)->values.value("isExpanded").toBool(); } return false; } @@ -410,7 +421,7 @@ bool KFileItemModel::isExpanded(int index) const bool KFileItemModel::isExpandable(int index) const { if (index >= 0 && index < count()) { - return m_sortedItems.at(index).isDir(); + return m_itemData.at(index)->item.isDir(); } return false; } @@ -435,6 +446,13 @@ void KFileItemModel::onSortRoleChanged(const QByteArray& current, const QByteArr { Q_UNUSED(previous); m_sortRole = roleIndex(current); + +#ifdef KFILEITEMMODEL_DEBUG + if (!m_requestRole[m_sortRole]) { + kWarning() << "The sort-role has been changed to a role that has not been received yet"; + } +#endif + resortAllItems(); } @@ -442,7 +460,62 @@ void KFileItemModel::onSortOrderChanged(Qt::SortOrder current, Qt::SortOrder pre { Q_UNUSED(current); Q_UNUSED(previous); - resortAllItems(); + resortAllItems(); +} + +void KFileItemModel::resortAllItems() +{ + m_resortAllItemsTimer->stop(); + + const int itemCount = count(); + if (itemCount <= 0) { + return; + } + +#ifdef KFILEITEMMODEL_DEBUG + QElapsedTimer timer; + timer.start(); + kDebug() << "==========================================================="; + kDebug() << "Resorting" << itemCount << "items"; +#endif + + // Remember the order of the current URLs so + // that it can be determined which indexes have + // been moved because of the resorting. + QList oldUrls; + oldUrls.reserve(itemCount); + foreach (const ItemData* itemData, m_itemData) { + oldUrls.append(itemData->item.url()); + } + + m_groups.clear(); + m_items.clear(); + + // Resort the items + sort(m_itemData.begin(), m_itemData.end()); + for (int i = 0; i < itemCount; ++i) { + m_items.insert(m_itemData.at(i)->item.url(), i); + } + + // Determine the indexes that have been moved + bool emitItemsMoved = false; + QList movedToIndexes; + movedToIndexes.reserve(itemCount); + for (int i = 0; i < itemCount; i++) { + const int newIndex = m_items.value(oldUrls.at(i).url()); + movedToIndexes.append(newIndex); + if (!emitItemsMoved && newIndex != i) { + emitItemsMoved = true; + } + } + + if (emitItemsMoved) { + emit itemsMoved(KItemRange(0, itemCount), movedToIndexes); + } + +#ifdef KFILEITEMMODEL_DEBUG + kDebug() << "[TIME] Resorting of" << itemCount << "items:" << timer.elapsed(); +#endif } void KFileItemModel::slotCompleted() @@ -576,15 +649,16 @@ void KFileItemModel::slotClear() m_minimumUpdateIntervalTimer->stop(); m_maximumUpdateIntervalTimer->stop(); + m_resortAllItemsTimer->stop(); m_pendingItemsToInsert.clear(); m_rootExpansionLevel = -1; - const int removedCount = m_data.count(); + const int removedCount = m_itemData.count(); if (removedCount > 0) { - m_sortedItems.clear(); + qDeleteAll(m_itemData); + m_itemData.clear(); m_items.clear(); - m_data.clear(); emit itemsRemoved(KItemRangeList() << KItemRange(0, removedCount)); } @@ -623,7 +697,7 @@ void KFileItemModel::insertItems(const KFileItemList& items) m_groups.clear(); - KFileItemList sortedItems = items; + QList sortedItems = createItemDataList(items); sort(sortedItems.begin(), sortedItems.end()); #ifdef KFILEITEMMODEL_DEBUG @@ -633,15 +707,15 @@ void KFileItemModel::insertItems(const KFileItemList& items) KItemRangeList itemRanges; int targetIndex = 0; int sourceIndex = 0; - int insertedAtIndex = -1; // Index for the current item-range - int insertedCount = 0; // Count for the current item-range - int previouslyInsertedCount = 0; // Sum of previously inserted items for all ranges + int insertedAtIndex = -1; // Index for the current item-range + int insertedCount = 0; // Count for the current item-range + int previouslyInsertedCount = 0; // Sum of previously inserted items for all ranges while (sourceIndex < sortedItems.count()) { // Find target index from m_items to insert the current item // in a sorted order const int previousTargetIndex = targetIndex; - while (targetIndex < m_sortedItems.count()) { - if (!lessThan(m_sortedItems.at(targetIndex), sortedItems.at(sourceIndex))) { + while (targetIndex < m_itemData.count()) { + if (!lessThan(m_itemData.at(targetIndex), sortedItems.at(sourceIndex))) { break; } ++targetIndex; @@ -654,11 +728,10 @@ void KFileItemModel::insertItems(const KFileItemList& items) insertedCount = 0; } - // Insert item at the position targetIndex - const KFileItem item = sortedItems.at(sourceIndex); - m_sortedItems.insert(targetIndex, item); - m_data.insert(targetIndex, retrieveData(item)); + // Insert item at the position targetIndex by transfering + // the ownership of the item-data from sortedItems to m_itemData. // m_items will be inserted after the loop (see comment below) + m_itemData.insert(targetIndex, sortedItems.at(sourceIndex)); ++insertedCount; if (insertedAtIndex < 0) { @@ -671,8 +744,9 @@ void KFileItemModel::insertItems(const KFileItemList& items) // The indexes of all m_items must be adjusted, not only the index // of the new items - for (int i = 0; i < m_sortedItems.count(); ++i) { - m_items.insert(m_sortedItems.at(i).url(), i); + const int itemDataCount = m_itemData.count(); + for (int i = 0; i < itemDataCount; ++i) { + m_items.insert(m_itemData.at(i)->item.url(), i); } itemRanges << KItemRange(insertedAtIndex, insertedCount); @@ -695,7 +769,7 @@ void KFileItemModel::removeItems(const KFileItemList& items) m_groups.clear(); - KFileItemList sortedItems = items; + QList sortedItems = createItemDataList(items); sort(sortedItems.begin(), sortedItems.end()); QList indexesToRemove; @@ -706,15 +780,17 @@ void KFileItemModel::removeItems(const KFileItemList& items) int removedAtIndex = -1; int removedCount = 0; int targetIndex = 0; - foreach (const KFileItem& itemToRemove, sortedItems) { + foreach (const ItemData* itemData, sortedItems) { + const KFileItem& itemToRemove = itemData->item; + const int previousTargetIndex = targetIndex; - while (targetIndex < m_sortedItems.count()) { - if (m_sortedItems.at(targetIndex).url() == itemToRemove.url()) { + while (targetIndex < m_itemData.count()) { + if (m_itemData.at(targetIndex)->item.url() == itemToRemove.url()) { break; } ++targetIndex; } - if (targetIndex >= m_sortedItems.count()) { + if (targetIndex >= m_itemData.count()) { kWarning() << "Item that should be deleted has not been found!"; return; } @@ -732,19 +808,21 @@ void KFileItemModel::removeItems(const KFileItemList& items) ++removedCount; ++targetIndex; } + qDeleteAll(sortedItems); + sortedItems.clear(); // Delete the items for (int i = indexesToRemove.count() - 1; i >= 0; --i) { const int indexToRemove = indexesToRemove.at(i); - m_items.remove(m_sortedItems.at(indexToRemove).url()); - m_sortedItems.removeAt(indexToRemove); - m_data.removeAt(indexToRemove); + delete m_itemData.at(indexToRemove); + m_itemData.removeAt(indexToRemove); } // The indexes of all m_items must be adjusted, not only the index // of the removed items - for (int i = 0; i < m_sortedItems.count(); ++i) { - m_items.insert(m_sortedItems.at(i).url(), i); + const int itemDataCount = m_itemData.count(); + for (int i = 0; i < itemDataCount; ++i) { + m_items.insert(m_itemData.at(i)->item.url(), i); } if (count() <= 0) { @@ -755,58 +833,30 @@ void KFileItemModel::removeItems(const KFileItemList& items) emit itemsRemoved(itemRanges); } -void KFileItemModel::resortAllItems() +QList KFileItemModel::createItemDataList(const KFileItemList& items) const { - const int itemCount = count(); - if (itemCount <= 0) { - return; - } - - m_groups.clear(); - - const KFileItemList oldSortedItems = m_sortedItems; - const QHash oldItems = m_items; - const QList > oldData = m_data; - - m_items.clear(); - m_data.clear(); - - sort(m_sortedItems.begin(), m_sortedItems.end()); - int index = 0; - foreach (const KFileItem& item, m_sortedItems) { - m_items.insert(item.url(), index); - - const int oldItemIndex = oldItems.value(item.url()); - m_data.append(oldData.at(oldItemIndex)); - - ++index; - } - - bool emitItemsMoved = false; - QList movedToIndexes; - movedToIndexes.reserve(m_sortedItems.count()); - for (int i = 0; i < itemCount; i++) { - const int newIndex = m_items.value(oldSortedItems.at(i).url()); - movedToIndexes.append(newIndex); - if (!emitItemsMoved && newIndex != i) { - emitItemsMoved = true; - } - } + QList itemDataList; + itemDataList.reserve(items.count()); - if (emitItemsMoved) { - emit itemsMoved(KItemRange(0, itemCount), movedToIndexes); + foreach (const KFileItem& item, items) { + ItemData* itemData = new ItemData(); + itemData->item = item; + itemData->values = retrieveData(item); + itemDataList.append(itemData); } + + return itemDataList; } void KFileItemModel::removeExpandedItems() { KFileItemList expandedItems; - const int maxIndex = m_data.count() - 1; + const int maxIndex = m_itemData.count() - 1; for (int i = 0; i <= maxIndex; ++i) { - if (m_data.at(i).value("expansionLevel").toInt() > 0) { - const KFileItem fileItem = m_sortedItems.at(i); - expandedItems.append(fileItem); + const ItemData* itemData = m_itemData.at(i); + if (itemData->values.value("expansionLevel").toInt() > 0) { + expandedItems.append(itemData->item); } } @@ -839,6 +889,9 @@ KFileItemModel::Role KFileItemModel::roleIndex(const QByteArray& role) const rolesHash.insert("type", TypeRole); rolesHash.insert("destination", DestinationRole); rolesHash.insert("path", PathRole); + rolesHash.insert("comment", CommentRole); + rolesHash.insert("tags", TagsRole); + rolesHash.insert("rating", RatingRole); rolesHash.insert("isDir", IsDirRole); rolesHash.insert("isExpanded", IsExpandedRole); rolesHash.insert("expansionLevel", ExpansionLevelRole); @@ -847,7 +900,7 @@ KFileItemModel::Role KFileItemModel::roleIndex(const QByteArray& role) const } QHash KFileItemModel::retrieveData(const KFileItem& item) const -{ +{ // It is important to insert only roles that are fast to retrieve. E.g. // KFileItem::iconName() can be very expensive if the MIME-type is unknown // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater. @@ -931,12 +984,15 @@ QHash KFileItemModel::retrieveData(const KFileItem& item) return data; } -bool KFileItemModel::lessThan(const KFileItem& a, const KFileItem& b) const +bool KFileItemModel::lessThan(const ItemData* a, const ItemData* b) const { + const KFileItem& itemA = a->item; + const KFileItem& itemB = b->item; + int result = 0; if (m_rootExpansionLevel >= 0) { - result = expansionLevelsCompare(a, b); + result = expansionLevelsCompare(itemA, itemB); if (result != 0) { // The items have parents with different expansion levels return (sortOrder() == Qt::AscendingOrder) ? result < 0 : result > 0; @@ -944,8 +1000,8 @@ bool KFileItemModel::lessThan(const KFileItem& a, const KFileItem& b) const } if (m_sortFoldersFirst || m_sortRole == SizeRole) { - const bool isDirA = a.isDir(); - const bool isDirB = b.isDir(); + const bool isDirA = itemA.isDir(); + const bool isDirB = itemB.isDir(); if (isDirA && !isDirB) { return true; } else if (!isDirA && isDirB) { @@ -955,18 +1011,18 @@ bool KFileItemModel::lessThan(const KFileItem& a, const KFileItem& b) const switch (m_sortRole) { case NameRole: { - result = stringCompare(a.text(), b.text()); + result = stringCompare(itemA.text(), itemB.text()); if (result == 0) { // KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used - result = stringCompare(a.name(m_caseSensitivity == Qt::CaseInsensitive), - b.name(m_caseSensitivity == Qt::CaseInsensitive)); + result = stringCompare(itemA.name(m_caseSensitivity == Qt::CaseInsensitive), + itemB.name(m_caseSensitivity == Qt::CaseInsensitive)); } break; } case DateRole: { - const KDateTime dateTimeA = a.time(KFileItem::ModificationTime); - const KDateTime dateTimeB = b.time(KFileItem::ModificationTime); + const KDateTime dateTimeA = itemA.time(KFileItem::ModificationTime); + const KDateTime dateTimeB = itemB.time(KFileItem::ModificationTime); if (dateTimeA < dateTimeB) { result = -1; } else if (dateTimeA > dateTimeB) { @@ -976,19 +1032,49 @@ bool KFileItemModel::lessThan(const KFileItem& a, const KFileItem& b) const } case SizeRole: { - // TODO: Implement sorting folders by the number of items inside. - // This is more tricky to get right because this number is retrieved - // asynchronously by KFileItemModelRolesUpdater. - const KIO::filesize_t sizeA = a.size(); - const KIO::filesize_t sizeB = b.size(); - if (sizeA < sizeB) { - result = -1; - } else if (sizeA > sizeB) { - result = +1; + if (itemA.isDir()) { + Q_ASSERT(itemB.isDir()); // see "if (m_sortFoldersFirst || m_sortRole == SizeRole)" above + + const QVariant valueA = a->values.value("size"); + const QVariant valueB = b->values.value("size"); + + if (valueA.isNull()) { + result = -1; + } else if (valueB.isNull()) { + result = +1; + } else { + result = valueA.value() - valueB.value(); + } + } else { + Q_ASSERT(!itemB.isDir()); // see "if (m_sortFoldersFirst || m_sortRole == SizeRole)" above + result = itemA.size() - itemB.size(); } break; } + case TypeRole: { + result = QString::compare(a->values.value("type").toString(), + b->values.value("type").toString()); + break; + } + + case CommentRole: { + result = QString::compare(a->values.value("comment").toString(), + b->values.value("comment").toString()); + break; + } + + case TagsRole: { + result = QString::compare(a->values.value("tags").toString(), + b->values.value("tags").toString()); + break; + } + + case RatingRole: { + result = a->values.value("rating").toInt() - b->values.value("rating").toInt(); + break; + } + default: break; } @@ -997,76 +1083,132 @@ bool KFileItemModel::lessThan(const KFileItem& a, const KFileItem& b) const // It must be assured that the sort order is always unique even if two values have been // equal. In this case a comparison of the URL is done which is unique in all cases // within KDirLister. - result = QString::compare(a.url().url(), b.url().url(), Qt::CaseSensitive); + result = QString::compare(itemA.url().url(), itemB.url().url(), Qt::CaseSensitive); } return (sortOrder() == Qt::AscendingOrder) ? result < 0 : result > 0; } -void KFileItemModel::sort(const KFileItemList::iterator& startIterator, const KFileItemList::iterator& endIterator) -{ - KFileItemList::iterator start = startIterator; - KFileItemList::iterator end = endIterator; - - // The implementation is based on qSortHelper() from qalgorithms.h +void KFileItemModel::sort(QList::iterator begin, + QList::iterator end) +{ + // The implementation is based on qStableSortHelper() from qalgorithms.h // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). - // In opposite to qSort() it allows to use a member-function for the comparison of elements. - while (1) { - int span = int(end - start); - if (span < 2) { - return; - } - - --end; - KFileItemList::iterator low = start, high = end - 1; - KFileItemList::iterator pivot = start + span / 2; - - if (lessThan(*end, *start)) { - qSwap(*end, *start); - } - if (span == 2) { - return; - } + // In opposite to qStableSort() it allows to use a member-function for the comparison of elements. + + const int span = end - begin; + if (span < 2) { + return; + } + + const QList::iterator middle = begin + span / 2; + sort(begin, middle); + sort(middle, end); + merge(begin, middle, end); +} - if (lessThan(*pivot, *start)) { - qSwap(*pivot, *start); - } - if (lessThan(*end, *pivot)) { - qSwap(*end, *pivot); - } - if (span == 3) { - return; +void KFileItemModel::merge(QList::iterator begin, + QList::iterator pivot, + QList::iterator end) +{ + // The implementation is based on qMerge() from qalgorithms.h + // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). + + const int len1 = pivot - begin; + const int len2 = end - pivot; + + if (len1 == 0 || len2 == 0) { + return; + } + + if (len1 + len2 == 2) { + if (lessThan(*(begin + 1), *(begin))) { + qSwap(*begin, *(begin + 1)); } + return; + } + + QList::iterator firstCut; + QList::iterator secondCut; + int len2Half; + if (len1 > len2) { + const int len1Half = len1 / 2; + firstCut = begin + len1Half; + secondCut = lowerBound(pivot, end, *firstCut); + len2Half = secondCut - pivot; + } else { + len2Half = len2 / 2; + secondCut = pivot + len2Half; + firstCut = upperBound(begin, pivot, *secondCut); + } + + reverse(firstCut, pivot); + reverse(pivot, secondCut); + reverse(firstCut, secondCut); + + const QList::iterator newPivot = firstCut + len2Half; + merge(begin, firstCut, newPivot); + merge(newPivot, secondCut, end); +} - qSwap(*pivot, *end); - - while (low < high) { - while (low < high && lessThan(*low, *end)) { - ++low; - } - - while (high > low && lessThan(*end, *high)) { - --high; - } - if (low < high) { - qSwap(*low, *high); - ++low; - --high; - } else { - break; - } +QList::iterator KFileItemModel::lowerBound(QList::iterator begin, + QList::iterator end, + const ItemData* value) +{ + // The implementation is based on qLowerBound() from qalgorithms.h + // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). + + QList::iterator middle; + int n = int(end - begin); + int half; + + while (n > 0) { + half = n >> 1; + middle = begin + half; + if (lessThan(*middle, value)) { + begin = middle + 1; + n -= half + 1; + } else { + n = half; } + } + return begin; +} - if (lessThan(*low, *end)) { - ++low; +QList::iterator KFileItemModel::upperBound(QList::iterator begin, + QList::iterator end, + const ItemData* value) +{ + // The implementation is based on qUpperBound() from qalgorithms.h + // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). + + QList::iterator middle; + int n = end - begin; + int half; + + while (n > 0) { + half = n >> 1; + middle = begin + half; + if (lessThan(value, *middle)) { + n = half; + } else { + begin = middle + 1; + n -= half + 1; } - - qSwap(*end, *low); - sort(start, low); - - start = low + 1; - ++end; } + return begin; +} + +void KFileItemModel::reverse(QList::iterator begin, + QList::iterator end) +{ + // The implementation is based on qReverse() from qalgorithms.h + // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). + + --end; + while (begin < end) { + qSwap(*begin++, *end--); + } } int KFileItemModel::stringCompare(const QString& a, const QString& b) const @@ -1159,7 +1301,7 @@ bool KFileItemModel::useMaximumUpdateInterval() const QList > KFileItemModel::nameRoleGroups() const { - Q_ASSERT(!m_data.isEmpty()); + Q_ASSERT(!m_itemData.isEmpty()); const int maxIndex = count() - 1; QList > groups; @@ -1168,14 +1310,11 @@ QList > KFileItemModel::nameRoleGroups() const QChar firstChar; bool isLetter = false; for (int i = 0; i <= maxIndex; ++i) { - if (m_requestRole[ExpansionLevelRole] && m_data.at(i).value("expansionLevel").toInt() > 0) { - // KItemListView would be capable to show sub-groups in groups but - // in typical usecases this results in visual clutter, hence we - // just ignore sub-groups. + if (isChildItem(i)) { continue; } - const QString name = m_data.at(i).value("name").toString(); + const QString name = m_itemData.at(i)->values.value("name").toString(); // Use the first character of the name as group indication QChar newFirstChar = name.at(0).toUpper(); @@ -1225,51 +1364,252 @@ QList > KFileItemModel::nameRoleGroups() const QList > KFileItemModel::sizeRoleGroups() const { - Q_ASSERT(!m_data.isEmpty()); + Q_ASSERT(!m_itemData.isEmpty()); + + const int maxIndex = count() - 1; + QList > groups; + + QString groupValue; + for (int i = 0; i <= maxIndex; ++i) { + if (isChildItem(i)) { + continue; + } + + const KFileItem& item = m_itemData.at(i)->item; + const KIO::filesize_t fileSize = !item.isNull() ? item.size() : ~0U; + QString newGroupValue; + if (!item.isNull() && item.isDir()) { + newGroupValue = i18nc("@title:group Size", "Folders"); + } else if (fileSize < 5 * 1024 * 1024) { + newGroupValue = i18nc("@title:group Size", "Small"); + } else if (fileSize < 10 * 1024 * 1024) { + newGroupValue = i18nc("@title:group Size", "Medium"); + } else { + newGroupValue = i18nc("@title:group Size", "Big"); + } - return QList >(); + if (newGroupValue != groupValue) { + groupValue = newGroupValue; + groups.append(QPair(i, newGroupValue)); + } + } + + return groups; } QList > KFileItemModel::dateRoleGroups() const { - Q_ASSERT(!m_data.isEmpty()); - return QList >(); + Q_ASSERT(!m_itemData.isEmpty()); + + const int maxIndex = count() - 1; + QList > groups; + + const QDate currentDate = KDateTime::currentLocalDateTime().date(); + + int yearForCurrentWeek = 0; + int currentWeek = currentDate.weekNumber(&yearForCurrentWeek); + if (yearForCurrentWeek == currentDate.year() + 1) { + currentWeek = 53; + } + + QDate previousModifiedDate; + QString groupValue; + for (int i = 0; i <= maxIndex; ++i) { + if (isChildItem(i)) { + continue; + } + + const KDateTime modifiedTime = m_itemData.at(i)->item.time(KFileItem::ModificationTime); + const QDate modifiedDate = modifiedTime.date(); + if (modifiedDate == previousModifiedDate) { + // The current item is in the same group as the previous item + continue; + } + previousModifiedDate = modifiedDate; + + const int daysDistance = modifiedDate.daysTo(currentDate); + + int yearForModifiedWeek = 0; + int modifiedWeek = modifiedDate.weekNumber(&yearForModifiedWeek); + if (yearForModifiedWeek == modifiedDate.year() + 1) { + modifiedWeek = 53; + } + + QString newGroupValue; + if (currentDate.year() == modifiedDate.year() && currentDate.month() == modifiedDate.month()) { + if (modifiedWeek > currentWeek) { + // Usecase: modified date = 2010-01-01, current date = 2010-01-22 + // modified week = 53, current week = 3 + modifiedWeek = 0; + } + switch (currentWeek - modifiedWeek) { + case 0: + switch (daysDistance) { + case 0: newGroupValue = i18nc("@title:group Date", "Today"); break; + case 1: newGroupValue = i18nc("@title:group Date", "Yesterday"); break; + default: newGroupValue = modifiedTime.toString(i18nc("@title:group The week day name: %A", "%A")); + } + break; + case 1: + newGroupValue = i18nc("@title:group Date", "Last Week"); + break; + case 2: + newGroupValue = i18nc("@title:group Date", "Two Weeks Ago"); + break; + case 3: + newGroupValue = i18nc("@title:group Date", "Three Weeks Ago"); + break; + case 4: + case 5: + newGroupValue = i18nc("@title:group Date", "Earlier this Month"); + break; + default: + Q_ASSERT(false); + } + } else { + const QDate lastMonthDate = currentDate.addMonths(-1); + if (lastMonthDate.year() == modifiedDate.year() && lastMonthDate.month() == modifiedDate.month()) { + if (daysDistance == 1) { + newGroupValue = modifiedTime.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Yesterday (%B, %Y)")); + } else if (daysDistance <= 7) { + 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)")); + } else if (daysDistance <= 7 * 2) { + 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)")); + } else if (daysDistance <= 7 * 3) { + 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)")); + } else if (daysDistance <= 7 * 4) { + 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)")); + } else { + 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")); + } + } else { + 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")); + } + } + + if (newGroupValue != groupValue) { + groupValue = newGroupValue; + groups.append(QPair(i, newGroupValue)); + } + } + + return groups; } QList > KFileItemModel::permissionRoleGroups() const { - Q_ASSERT(!m_data.isEmpty()); - return QList >(); -} + Q_ASSERT(!m_itemData.isEmpty()); -QList > KFileItemModel::ownerRoleGroups() const -{ - Q_ASSERT(!m_data.isEmpty()); - return QList >(); -} + const int maxIndex = count() - 1; + QList > groups; -QList > KFileItemModel::groupRoleGroups() const -{ - Q_ASSERT(!m_data.isEmpty()); - return QList >(); -} + QString permissionsString; + QString groupValue; + for (int i = 0; i <= maxIndex; ++i) { + if (isChildItem(i)) { + continue; + } -QList > KFileItemModel::typeRoleGroups() const -{ - Q_ASSERT(!m_data.isEmpty()); - return QList >(); + const ItemData* itemData = m_itemData.at(i); + const QString newPermissionsString = itemData->values.value("permissions").toString(); + if (newPermissionsString == permissionsString) { + continue; + } + permissionsString = newPermissionsString; + + const QFileInfo info(itemData->item.url().pathOrUrl()); + + // Set user string + QString user; + if (info.permission(QFile::ReadUser)) { + user = i18nc("@item:intext Access permission, concatenated", "Read, "); + } + if (info.permission(QFile::WriteUser)) { + user += i18nc("@item:intext Access permission, concatenated", "Write, "); + } + if (info.permission(QFile::ExeUser)) { + user += i18nc("@item:intext Access permission, concatenated", "Execute, "); + } + user = user.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user.mid(0, user.count() - 2); + + // Set group string + QString group; + if (info.permission(QFile::ReadGroup)) { + group = i18nc("@item:intext Access permission, concatenated", "Read, "); + } + if (info.permission(QFile::WriteGroup)) { + group += i18nc("@item:intext Access permission, concatenated", "Write, "); + } + if (info.permission(QFile::ExeGroup)) { + group += i18nc("@item:intext Access permission, concatenated", "Execute, "); + } + group = group.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group.mid(0, group.count() - 2); + + // Set others string + QString others; + if (info.permission(QFile::ReadOther)) { + others = i18nc("@item:intext Access permission, concatenated", "Read, "); + } + if (info.permission(QFile::WriteOther)) { + others += i18nc("@item:intext Access permission, concatenated", "Write, "); + } + if (info.permission(QFile::ExeOther)) { + others += i18nc("@item:intext Access permission, concatenated", "Execute, "); + } + others = others.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others.mid(0, others.count() - 2); + + const QString newGroupValue = i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user, group, others); + if (newGroupValue != groupValue) { + groupValue = newGroupValue; + groups.append(QPair(i, newGroupValue)); + } + } + + return groups; } -QList > KFileItemModel::destinationRoleGroups() const +QList > KFileItemModel::ratingRoleGroups() const { - Q_ASSERT(!m_data.isEmpty()); - return QList >(); + Q_ASSERT(!m_itemData.isEmpty()); + + const int maxIndex = count() - 1; + QList > groups; + + int groupValue; + for (int i = 0; i <= maxIndex; ++i) { + if (isChildItem(i)) { + continue; + } + const int newGroupValue = m_itemData.at(i)->values.value("rating").toInt(); + if (newGroupValue != groupValue) { + groupValue = newGroupValue; + groups.append(QPair(i, newGroupValue)); + } + } + + return groups; } -QList > KFileItemModel::pathRoleGroups() const +QList > KFileItemModel::genericStringRoleGroups(const QByteArray& role) const { - Q_ASSERT(!m_data.isEmpty()); - return QList >(); + Q_ASSERT(!m_itemData.isEmpty()); + + const int maxIndex = count() - 1; + QList > groups; + + QString groupValue; + for (int i = 0; i <= maxIndex; ++i) { + if (isChildItem(i)) { + continue; + } + const QString newGroupValue = m_itemData.at(i)->values.value(role).toString(); + if (newGroupValue != groupValue) { + groupValue = newGroupValue; + groups.append(QPair(i, newGroupValue)); + } + } + + return groups; } #include "kfileitemmodel.moc"