X-Git-Url: https://cloud.milkyroute.net/gitweb/dolphin.git/blobdiff_plain/eb21254eef1f314fdd3f57896c65a826f749c4ad..982ce7ae203de9142ca3e79e6fdeacd003fb0414:/src/kitemviews/kfileitemmodel.cpp diff --git a/src/kitemviews/kfileitemmodel.cpp b/src/kitemviews/kfileitemmodel.cpp index c0adce986..7a4323fea 100644 --- a/src/kitemviews/kfileitemmodel.cpp +++ b/src/kitemviews/kfileitemmodel.cpp @@ -21,6 +21,7 @@ #include #include +#include #include #include #include @@ -28,28 +29,26 @@ #include #include -#define KFILEITEMMODEL_DEBUG +// #define KFILEITEMMODEL_DEBUG KFileItemModel::KFileItemModel(KDirLister* dirLister, QObject* parent) : KItemModelBase("name", parent), m_dirLister(dirLister), - m_naturalSorting(true), + m_naturalSorting(KGlobalSettings::naturalSorting()), m_sortFoldersFirst(true), m_sortRole(NameRole), m_roles(), m_caseSensitivity(Qt::CaseInsensitive), m_itemData(), m_items(), - m_nameFilter(), + m_filter(), m_filteredItems(), m_requestRole(), - m_minimumUpdateIntervalTimer(0), m_maximumUpdateIntervalTimer(0), m_resortAllItemsTimer(0), m_pendingItemsToInsert(), - m_pendingEmitLoadingCompleted(false), m_groups(), - m_rootExpansionLevel(-1), + m_expandedParentsCountRoot(UninitializedExpandedParentsCountRoot), m_expandedUrls(), m_urlsToExpand() { @@ -63,28 +62,20 @@ KFileItemModel::KFileItemModel(KDirLister* dirLister, QObject* parent) : Q_ASSERT(dirLister); connect(dirLister, SIGNAL(canceled()), this, SLOT(slotCanceled())); - connect(dirLister, SIGNAL(completed()), this, SLOT(slotCompleted())); + connect(dirLister, SIGNAL(completed(KUrl)), this, SLOT(slotCompleted())); connect(dirLister, SIGNAL(newItems(KFileItemList)), this, SLOT(slotNewItems(KFileItemList))); connect(dirLister, SIGNAL(itemsDeleted(KFileItemList)), this, SLOT(slotItemsDeleted(KFileItemList))); connect(dirLister, SIGNAL(refreshItems(QList >)), this, SLOT(slotRefreshItems(QList >))); connect(dirLister, SIGNAL(clear()), this, SLOT(slotClear())); connect(dirLister, SIGNAL(clear(KUrl)), this, SLOT(slotClear(KUrl))); - // Although the layout engine of KItemListView is fast it is very inefficient to e.g. - // emit 50 itemsInserted()-signals each 100 ms. m_minimumUpdateIntervalTimer assures that updates - // are done in 1 second intervals for equal operations. - m_minimumUpdateIntervalTimer = new QTimer(this); - m_minimumUpdateIntervalTimer->setInterval(1000); - m_minimumUpdateIntervalTimer->setSingleShot(true); - connect(m_minimumUpdateIntervalTimer, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert())); - // For slow KIO-slaves like used for searching it makes sense to show results periodically even // before the completed() or canceled() signal has been emitted. m_maximumUpdateIntervalTimer = new QTimer(this); 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 @@ -94,7 +85,7 @@ KFileItemModel::KFileItemModel(KDirLister* dirLister, QObject* parent) : m_resortAllItemsTimer->setSingleShot(true); connect(m_resortAllItemsTimer, SIGNAL(timeout()), this, SLOT(resortAllItems())); - Q_ASSERT(m_minimumUpdateIntervalTimer->interval() <= m_maximumUpdateIntervalTimer->interval()); + connect(KGlobalSettings::self(), SIGNAL(naturalSortingChanged()), this, SLOT(slotNaturalSortingChanged())); } KFileItemModel::~KFileItemModel() @@ -148,7 +139,7 @@ bool KFileItemModel::setData(int index, const QHash& value if (changedRoles.contains(sortRole())) { m_resortAllItemsTimer->start(); } - + return true; } @@ -165,6 +156,38 @@ bool KFileItemModel::sortFoldersFirst() const return m_sortFoldersFirst; } +void KFileItemModel::setShowHiddenFiles(bool show) +{ + KDirLister* dirLister = m_dirLister.data(); + if (dirLister) { + dirLister->setShowingDotFiles(show); + dirLister->emitChanges(); + if (show) { + slotCompleted(); + } + } +} + +bool KFileItemModel::showHiddenFiles() const +{ + const KDirLister* dirLister = m_dirLister.data(); + return dirLister ? dirLister->showingDotFiles() : false; +} + +void KFileItemModel::setShowFoldersOnly(bool enabled) +{ + KDirLister* dirLister = m_dirLister.data(); + if (dirLister) { + dirLister->setDirOnlyMode(enabled); + } +} + +bool KFileItemModel::showFoldersOnly() const +{ + KDirLister* dirLister = m_dirLister.data(); + return dirLister ? dirLister->dirOnlyMode() : false; +} + QMimeData* KFileItemModel::createMimeData(const QSet& indexes) const { QMimeData* data = new QMimeData(); @@ -222,34 +245,21 @@ int KFileItemModel::indexForKeyboardSearch(const QString& text, int startFromInd bool KFileItemModel::supportsDropping(int index) const { const KFileItem item = fileItem(index); - return item.isNull() ? false : item.isDir(); + return !item.isNull() && (item.isDir() || item.isDesktopFile()); } QString KFileItemModel::roleDescription(const QByteArray& role) const { - QString descr; - - switch (roleIndex(role)) { - case NameRole: descr = i18nc("@item:intable", "Name"); break; - case SizeRole: descr = i18nc("@item:intable", "Size"); break; - case DateRole: descr = i18nc("@item:intable", "Date"); break; - case PermissionsRole: descr = i18nc("@item:intable", "Permissions"); break; - case OwnerRole: descr = i18nc("@item:intable", "Owner"); break; - case GroupRole: descr = i18nc("@item:intable", "Group"); break; - 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; - case ExpansionLevelRole: break; - default: Q_ASSERT(false); break; + static QHash description; + if (description.isEmpty()) { + int count = 0; + const RoleInfoMap* map = rolesInfoMap(count); + for (int i = 0; i < count; ++i) { + description.insert(map[i].role, map[i].roleTranslation); + } } - return descr; + return description.value(role); } QList > KFileItemModel::groups() const @@ -259,23 +269,23 @@ QList > KFileItemModel::groups() const QElapsedTimer timer; timer.start(); #endif - switch (roleIndex(sortRole())) { - case NameRole: m_groups = nameRoleGroups(); break; - case SizeRole: m_groups = sizeRoleGroups(); break; - case DateRole: m_groups = dateRoleGroups(); break; - case PermissionsRole: m_groups = permissionRoleGroups(); 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; - case ExpansionLevelRole: break; + switch (typeForRole(sortRole())) { + case NameRole: m_groups = nameRoleGroups(); break; + case SizeRole: m_groups = sizeRoleGroups(); break; + case DateRole: m_groups = dateRoleGroups(); break; + case PermissionsRole: m_groups = permissionRoleGroups(); 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; + case ExpandedParentsCountRole: break; default: Q_ASSERT(false); break; } @@ -337,11 +347,14 @@ void KFileItemModel::clear() void KFileItemModel::setRoles(const QSet& roles) { + if (m_roles == roles) { + return; + } m_roles = roles; if (count() > 0) { - const bool supportedExpanding = m_requestRole[IsExpandedRole] && m_requestRole[ExpansionLevelRole]; - const bool willSupportExpanding = roles.contains("isExpanded") && roles.contains("expansionLevel"); + const bool supportedExpanding = m_requestRole[ExpandedParentsCountRole]; + const bool willSupportExpanding = roles.contains("expandedParentsCount"); if (supportedExpanding && !willSupportExpanding) { // No expanding is supported anymore. Take care to delete all items that have an expansion level // that is not 0 (and hence are part of an expanded item). @@ -349,12 +362,13 @@ void KFileItemModel::setRoles(const QSet& roles) } } + m_groups.clear(); resetRoles(); QSetIterator it(roles); while (it.hasNext()) { const QByteArray& role = it.next(); - m_requestRole[roleIndex(role)] = true; + m_requestRole[typeForRole(role)] = true; } if (count() > 0) { @@ -376,7 +390,7 @@ QSet KFileItemModel::roles() const bool KFileItemModel::setExpanded(int index, bool expanded) { - if (isExpanded(index) == expanded || index < 0 || index >= count()) { + if (!isExpandable(index) || isExpanded(index) == expanded) { return false; } @@ -386,11 +400,11 @@ bool KFileItemModel::setExpanded(int index, bool expanded) return false; } + KDirLister* dirLister = m_dirLister.data(); const KUrl url = m_itemData.at(index)->item.url(); if (expanded) { m_expandedUrls.insert(url); - KDirLister* dirLister = m_dirLister.data(); if (dirLister) { dirLister->openUrl(url, KDirLister::Keep); return true; @@ -398,10 +412,14 @@ bool KFileItemModel::setExpanded(int index, bool expanded) } else { m_expandedUrls.remove(url); + if (dirLister) { + dirLister->stop(url); + } + KFileItemList itemsToRemove; - const int expansionLevel = data(index)["expansionLevel"].toInt(); + const int expandedParentsCount = data(index)["expandedParentsCount"].toInt(); ++index; - while (index < count() && data(index)["expansionLevel"].toInt() > expansionLevel) { + while (index < count() && data(index)["expandedParentsCount"].toInt() > expandedParentsCount) { itemsToRemove.append(m_itemData.at(index)->item); ++index; } @@ -423,11 +441,22 @@ bool KFileItemModel::isExpanded(int index) const bool KFileItemModel::isExpandable(int index) const { if (index >= 0 && index < count()) { - return m_itemData.at(index)->item.isDir(); + return m_itemData.at(index)->values.value("isExpandable").toBool(); } return false; } +int KFileItemModel::expandedParentsCount(int index) const +{ + if (index >= 0 && index < count()) { + const int parentsCount = m_itemData.at(index)->values.value("expandedParentsCount").toInt(); + if (parentsCount > 0) { + return parentsCount; + } + } + return 0; +} + QSet KFileItemModel::expandedUrls() const { return m_expandedUrls; @@ -438,30 +467,24 @@ void KFileItemModel::restoreExpandedUrls(const QSet& urls) m_urlsToExpand = urls; } -void KFileItemModel::setExpanded(const QSet& urls) +void KFileItemModel::expandParentItems(const KUrl& url) { - const KDirLister* dirLister = m_dirLister.data(); if (!dirLister) { return; } - const int pos = dirLister->url().url().length(); + const int pos = dirLister->url().path().length(); - // Assure that each sub-path of the URLs that should be - // expanded is added to m_urlsToExpand too. KDirLister + // Assure that each sub-path of the URL that should be + // expanded is added to m_urlsToExpand. KDirLister // does not care whether the parent-URL has already been // expanded. - QSetIterator it1(urls); - while (it1.hasNext()) { - const KUrl& url = it1.next(); - - KUrl urlToExpand = dirLister->url(); - const QStringList subDirs = url.url().mid(pos).split(QDir::separator()); - for (int i = 0; i < subDirs.count(); ++i) { - urlToExpand.addPath(subDirs.at(i)); - m_urlsToExpand.insert(urlToExpand); - } + KUrl urlToExpand = dirLister->url(); + const QStringList subDirs = url.path().mid(pos).split(QDir::separator()); + for (int i = 0; i < subDirs.count() - 1; ++i) { + urlToExpand.addPath(subDirs.at(i)); + m_urlsToExpand.insert(urlToExpand); } // KDirLister::open() must called at least once to trigger an initial @@ -479,19 +502,23 @@ void KFileItemModel::setExpanded(const QSet& urls) void KFileItemModel::setNameFilter(const QString& nameFilter) { - if (m_nameFilter != nameFilter) { + if (m_filter.pattern() != nameFilter) { dispatchPendingItemsToInsert(); - m_nameFilter = nameFilter; + m_filter.setPattern(nameFilter); // Check which shown items from m_itemData must get // hidden and hence moved to m_filteredItems. KFileItemList newFilteredItems; foreach (ItemData* itemData, m_itemData) { - if (!matchesNameFilter(itemData->item)) { - newFilteredItems.append(itemData->item); - m_filteredItems.insert(itemData->item); + if (!m_filter.matches(itemData->item)) { + // Only filter non-expanded items as child items may never + // exist without a parent item + if (!itemData->values.value("isExpanded").toBool()) { + newFilteredItems.append(itemData->item); + m_filteredItems.insert(itemData->item); + } } } @@ -504,7 +531,7 @@ void KFileItemModel::setNameFilter(const QString& nameFilter) QMutableSetIterator it(m_filteredItems); while (it.hasNext()) { const KFileItem item = it.next(); - if (matchesNameFilter(item)) { + if (m_filter.matches(item)) { newVisibleItems.append(item); m_filteredItems.remove(item); } @@ -516,7 +543,27 @@ void KFileItemModel::setNameFilter(const QString& nameFilter) QString KFileItemModel::nameFilter() const { - return m_nameFilter; + return m_filter.pattern(); +} + +QList KFileItemModel::rolesInformation() +{ + static QList rolesInfo; + if (rolesInfo.isEmpty()) { + int count = 0; + const RoleInfoMap* map = rolesInfoMap(count); + for (int i = 0; i < count; ++i) { + if (map[i].roleType != NoRole) { + RoleInfo info; + info.role = map[i].role; + info.translation = map[i].roleTranslation; + info.group = map[i].groupTranslation; + rolesInfo.append(info); + } + } + } + + return rolesInfo; } void KFileItemModel::onGroupedSortingChanged(bool current) @@ -528,7 +575,7 @@ void KFileItemModel::onGroupedSortingChanged(bool current) void KFileItemModel::onSortRoleChanged(const QByteArray& current, const QByteArray& previous) { Q_UNUSED(previous); - m_sortRole = roleIndex(current); + m_sortRole = typeForRole(current); #ifdef KFILEITEMMODEL_DEBUG if (!m_requestRole[m_sortRole]) { @@ -543,13 +590,13 @@ 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; @@ -570,47 +617,38 @@ void KFileItemModel::resortAllItems() 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()); + 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); } - + + // Don't check whether items have really been moved and always emit a + // itemsMoved() signal after resorting: In case of grouped items + // the groups might change even if the items themselves don't change their + // position. Let the receiver of the signal decide whether a check for moved + // items makes sense. + emit itemsMoved(KItemRange(0, itemCount), movedToIndexes); + #ifdef KFILEITEMMODEL_DEBUG kDebug() << "[TIME] Resorting of" << itemCount << "items:" << timer.elapsed(); -#endif +#endif } void KFileItemModel::slotCompleted() { - if (m_urlsToExpand.isEmpty() && m_minimumUpdateIntervalTimer->isActive()) { - // dispatchPendingItems() will be called when the timer - // has been expired. - m_pendingEmitLoadingCompleted = true; - return; - } - - m_pendingEmitLoadingCompleted = false; dispatchPendingItemsToInsert(); if (!m_urlsToExpand.isEmpty()) { @@ -636,19 +674,49 @@ void KFileItemModel::slotCompleted() } emit loadingCompleted(); - m_minimumUpdateIntervalTimer->start(); } void KFileItemModel::slotCanceled() { - m_minimumUpdateIntervalTimer->stop(); m_maximumUpdateIntervalTimer->stop(); dispatchPendingItemsToInsert(); } void KFileItemModel::slotNewItems(const KFileItemList& items) { - if (m_nameFilter.isEmpty()) { + Q_ASSERT(!items.isEmpty()); + + if (m_requestRole[ExpandedParentsCountRole] && m_expandedParentsCountRoot >= 0) { + // To be able to compare whether the new items may be inserted as children + // of a parent item the pending items must be added to the model first. + dispatchPendingItemsToInsert(); + + KFileItem item = items.first(); + + // If the expanding of items is enabled, the call + // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded() + // might result in emitting the same items twice due to the Keep-parameter. + // This case happens if an item gets expanded, collapsed and expanded again + // before the items could be loaded for the first expansion. + const int index = m_items.value(item.url(), -1); + if (index >= 0) { + // The items are already part of the model. + return; + } + + // KDirLister keeps the children of items that got expanded once even if + // they got collapsed again with KFileItemModel::setExpanded(false). So it must be + // checked whether the parent for new items is still expanded. + KUrl parentUrl = item.url().upUrl(); + parentUrl.adjustPath(KUrl::RemoveTrailingSlash); + const int parentIndex = m_items.value(parentUrl, -1); + if (parentIndex >= 0 && !m_itemData[parentIndex]->values.value("isExpanded").toBool()) { + // The parent is not expanded. + return; + } + } + + if (m_filter.pattern().isEmpty()) { m_pendingItemsToInsert.append(items); } else { // The name-filter is active. Hide filtered items @@ -656,7 +724,7 @@ void KFileItemModel::slotNewItems(const KFileItemList& items) // the filtered items in m_filteredItems. KFileItemList filteredItems; foreach (const KFileItem& item, items) { - if (matchesNameFilter(item)) { + if (m_filter.matches(item)) { filteredItems.append(item); } else { m_filteredItems.insert(item); @@ -677,13 +745,21 @@ void KFileItemModel::slotItemsDeleted(const KFileItemList& items) { dispatchPendingItemsToInsert(); - if (!m_filteredItems.isEmpty()) { + KFileItemList itemsToRemove = items; + if (m_requestRole[ExpandedParentsCountRole] && m_expandedParentsCountRoot >= 0) { + // Assure that removing a parent item also results in removing all children foreach (const KFileItem& item, items) { + itemsToRemove.append(childItems(item)); + } + } + + if (!m_filteredItems.isEmpty()) { + foreach (const KFileItem& item, itemsToRemove) { m_filteredItems.remove(item); } } - removeItems(items); + removeItems(itemsToRemove); } void KFileItemModel::slotRefreshItems(const QList >& items) @@ -707,7 +783,15 @@ void KFileItemModel::slotRefreshItems(const QList >& const int index = m_items.value(oldItem.url(), -1); if (index >= 0) { m_itemData[index]->item = newItem; - m_itemData[index]->values = retrieveData(newItem); + + // Keep old values as long as possible if they could not retrieved synchronously yet. + // The update of the values will be done asynchronously by KFileItemModelRolesUpdater. + QHashIterator it(retrieveData(newItem)); + while (it.hasNext()) { + it.next(); + m_itemData[index]->values.insert(it.key(), it.value()); + } + m_items.remove(oldItem.url()); m_items.insert(newItem.url(), index); indexes.append(index); @@ -747,6 +831,8 @@ void KFileItemModel::slotRefreshItems(const QList >& } emit itemsChanged(itemRangeList, m_roles); + + resortAllItems(); } void KFileItemModel::slotClear() @@ -758,12 +844,11 @@ void KFileItemModel::slotClear() m_filteredItems.clear(); m_groups.clear(); - m_minimumUpdateIntervalTimer->stop(); m_maximumUpdateIntervalTimer->stop(); m_resortAllItemsTimer->stop(); m_pendingItemsToInsert.clear(); - m_rootExpansionLevel = -1; + m_expandedParentsCountRoot = UninitializedExpandedParentsCountRoot; const int removedCount = m_itemData.count(); if (removedCount > 0) { @@ -781,16 +866,18 @@ void KFileItemModel::slotClear(const KUrl& url) Q_UNUSED(url); } +void KFileItemModel::slotNaturalSortingChanged() +{ + m_naturalSorting = KGlobalSettings::naturalSorting(); + resortAllItems(); +} + void KFileItemModel::dispatchPendingItemsToInsert() { if (!m_pendingItemsToInsert.isEmpty()) { insertItems(m_pendingItemsToInsert); m_pendingItemsToInsert.clear(); } - - if (m_pendingEmitLoadingCompleted) { - emit loadingCompleted(); - } } void KFileItemModel::insertItems(const KFileItemList& items) @@ -842,7 +929,7 @@ void KFileItemModel::insertItems(const KFileItemList& items) // 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)); + m_itemData.insert(targetIndex, sortedItems.at(sourceIndex)); ++insertedCount; if (insertedAtIndex < 0) { @@ -880,7 +967,14 @@ void KFileItemModel::removeItems(const KFileItemList& items) m_groups.clear(); - QList sortedItems = createItemDataList(items); + QList sortedItems; + sortedItems.reserve(items.count()); + foreach (const KFileItem& item, items) { + const int index = m_items.value(item.url(), -1); + if (index >= 0) { + sortedItems.append(m_itemData.at(index)); + } + } sort(sortedItems.begin(), sortedItems.end()); QList indexesToRemove; @@ -893,7 +987,7 @@ void KFileItemModel::removeItems(const KFileItemList& items) int targetIndex = 0; foreach (const ItemData* itemData, sortedItems) { const KFileItem& itemToRemove = itemData->item; - + const int previousTargetIndex = targetIndex; while (targetIndex < m_itemData.count()) { if (m_itemData.at(targetIndex)->item.url() == itemToRemove.url()) { @@ -919,8 +1013,6 @@ void KFileItemModel::removeItems(const KFileItemList& items) ++removedCount; ++targetIndex; } - qDeleteAll(sortedItems); - sortedItems.clear(); // Delete the items for (int i = indexesToRemove.count() - 1; i >= 0; --i) { @@ -941,7 +1033,7 @@ void KFileItemModel::removeItems(const KFileItemList& items) } if (count() <= 0) { - m_rootExpansionLevel = -1; + m_expandedParentsCountRoot = UninitializedExpandedParentsCountRoot; } itemRanges << KItemRange(removedAtIndex, removedCount); @@ -957,9 +1049,24 @@ QList KFileItemModel::createItemDataList(const KFileI ItemData* itemData = new ItemData(); itemData->item = item; itemData->values = retrieveData(item); + itemData->parent = 0; + + const bool determineParent = m_requestRole[ExpandedParentsCountRole] + && itemData->values["expandedParentsCount"].toInt() > 0; + if (determineParent) { + KUrl parentUrl = item.url().upUrl(); + parentUrl.adjustPath(KUrl::RemoveTrailingSlash); + const int parentIndex = m_items.value(parentUrl, -1); + if (parentIndex >= 0) { + itemData->parent = m_itemData.at(parentIndex); + } else { + kWarning() << "Parent item not found for" << item.url(); + } + } + itemDataList.append(itemData); } - + return itemDataList; } @@ -970,17 +1077,17 @@ void KFileItemModel::removeExpandedItems() const int maxIndex = m_itemData.count() - 1; for (int i = 0; i <= maxIndex; ++i) { const ItemData* itemData = m_itemData.at(i); - if (itemData->values.value("expansionLevel").toInt() > 0) { + if (itemData->values.value("expandedParentsCount").toInt() > 0) { expandedItems.append(itemData->item); } } - // The m_rootExpansionLevel may not get reset before all items with - // a bigger expansionLevel have been removed. - Q_ASSERT(m_rootExpansionLevel >= 0); + // The m_expandedParentsCountRoot may not get reset before all items with + // a bigger count have been removed. + Q_ASSERT(m_expandedParentsCountRoot >= 0); removeItems(expandedItems); - m_rootExpansionLevel = -1; + m_expandedParentsCountRoot = UninitializedExpandedParentsCountRoot; m_expandedUrls.clear(); } @@ -991,36 +1098,62 @@ void KFileItemModel::resetRoles() } } -KFileItemModel::Role KFileItemModel::roleIndex(const QByteArray& role) const +KFileItemModel::RoleType KFileItemModel::typeForRole(const QByteArray& role) const { - static QHash rolesHash; - if (rolesHash.isEmpty()) { - rolesHash.insert("name", NameRole); - rolesHash.insert("size", SizeRole); - rolesHash.insert("date", DateRole); - rolesHash.insert("permissions", PermissionsRole); - rolesHash.insert("owner", OwnerRole); - rolesHash.insert("group", GroupRole); - 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); + static QHash roles; + if (roles.isEmpty()) { + // Insert user visible roles that can be accessed with + // KFileItemModel::roleInformation() + int count = 0; + const RoleInfoMap* map = rolesInfoMap(count); + for (int i = 0; i < count; ++i) { + roles.insert(map[i].role, map[i].roleType); + } + + // Insert internal roles (take care to synchronize the implementation + // with KFileItemModel::roleForType() in case if a change is done). + roles.insert("isDir", IsDirRole); + roles.insert("isExpanded", IsExpandedRole); + roles.insert("isExpandable", IsExpandableRole); + roles.insert("expandedParentsCount", ExpandedParentsCountRole); + + Q_ASSERT(roles.count() == RolesCount); } - return rolesHash.value(role, NoRole); + + return roles.value(role, NoRole); +} + +QByteArray KFileItemModel::roleForType(RoleType roleType) const +{ + static QHash roles; + if (roles.isEmpty()) { + // Insert user visible roles that can be accessed with + // KFileItemModel::roleInformation() + int count = 0; + const RoleInfoMap* map = rolesInfoMap(count); + for (int i = 0; i < count; ++i) { + roles.insert(map[i].roleType, map[i].role); + } + + // Insert internal roles (take care to synchronize the implementation + // with KFileItemModel::typeForRole() in case if a change is done). + roles.insert(IsDirRole, "isDir"); + roles.insert(IsExpandedRole, "isExpanded"); + roles.insert(IsExpandableRole, "isExpandable"); + roles.insert(ExpandedParentsCountRole, "expandedParentsCount"); + + Q_ASSERT(roles.count() == RolesCount); + }; + + return roles.value(roleType); } 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. QHash data; - data.insert("iconPixmap", QPixmap()); data.insert("url", item.url()); const bool isDir = item.isDir(); @@ -1069,25 +1202,49 @@ QHash KFileItemModel::retrieveData(const KFileItem& item) } if (m_requestRole[PathRole]) { - data.insert("path", item.localPath()); + QString path; + if (item.url().protocol() == QLatin1String("trash")) { + path = item.entry().stringValue(KIO::UDSEntry::UDS_EXTRA); + } else { + path = item.localPath(); + } + + const int index = path.lastIndexOf(item.text()); + path = path.mid(0, index - 1); + data.insert("path", path); } if (m_requestRole[IsExpandedRole]) { data.insert("isExpanded", false); } - if (m_requestRole[ExpansionLevelRole]) { - if (m_rootExpansionLevel < 0 && m_dirLister.data()) { - const QString rootDir = m_dirLister.data()->url().directory(KUrl::AppendTrailingSlash); - m_rootExpansionLevel = rootDir.count('/'); - if (m_rootExpansionLevel == 1) { - // Special case: The root is already reached and no parent is available - --m_rootExpansionLevel; + if (m_requestRole[IsExpandableRole]) { + data.insert("isExpandable", item.isDir() && item.url() == item.targetUrl()); + } + + if (m_requestRole[ExpandedParentsCountRole]) { + if (m_expandedParentsCountRoot == UninitializedExpandedParentsCountRoot && m_dirLister.data()) { + const KUrl rootUrl = m_dirLister.data()->url(); + const QString protocol = rootUrl.protocol(); + const bool forceExpandedParentsCountRoot = (protocol == QLatin1String("trash") || + protocol == QLatin1String("nepomuk") || + protocol == QLatin1String("remote") || + protocol.contains(QLatin1String("search"))); + if (forceExpandedParentsCountRoot) { + m_expandedParentsCountRoot = ForceExpandedParentsCountRoot; + } else { + const QString rootDir = rootUrl.path(KUrl::AddTrailingSlash); + m_expandedParentsCountRoot = rootDir.count('/'); } } - const QString dir = item.url().directory(KUrl::AppendTrailingSlash); - const int level = dir.count('/') - m_rootExpansionLevel - 1; - data.insert("expansionLevel", level); + + if (m_expandedParentsCountRoot == ForceExpandedParentsCountRoot) { + data.insert("expandedParentsCount", -1); + } else { + const QString dir = item.url().directory(KUrl::AppendTrailingSlash); + const int level = dir.count('/') - m_expandedParentsCountRoot; + data.insert("expandedParentsCount", level); + } } if (item.isMimeTypeKnown()) { @@ -1103,13 +1260,10 @@ QHash KFileItemModel::retrieveData(const KFileItem& item) 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(itemA, itemB); + if (m_expandedParentsCountRoot >= 0) { + result = expandedParentsCountCompare(a, b); if (result != 0) { // The items have parents with different expansion levels return (sortOrder() == Qt::AscendingOrder) ? result < 0 : result > 0; @@ -1117,8 +1271,8 @@ bool KFileItemModel::lessThan(const ItemData* a, const ItemData* b) const } if (m_sortFoldersFirst || m_sortRole == SizeRole) { - const bool isDirA = itemA.isDir(); - const bool isDirB = itemB.isDir(); + const bool isDirA = a->item.isDir(); + const bool isDirB = b->item.isDir(); if (isDirA && !isDirB) { return true; } else if (!isDirA && isDirB) { @@ -1126,69 +1280,82 @@ bool KFileItemModel::lessThan(const ItemData* a, const ItemData* b) const } } - switch (m_sortRole) { - case NameRole: { - result = stringCompare(itemA.text(), itemB.text()); - if (result == 0) { - // KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used - result = stringCompare(itemA.name(m_caseSensitivity == Qt::CaseInsensitive), - itemB.name(m_caseSensitivity == Qt::CaseInsensitive)); - } - break; - } + result = sortRoleCompare(a, b); - case DateRole: { - const KDateTime dateTimeA = itemA.time(KFileItem::ModificationTime); - const KDateTime dateTimeB = itemB.time(KFileItem::ModificationTime); - if (dateTimeA < dateTimeB) { - result = -1; - } else if (dateTimeA > dateTimeB) { - result = +1; - } + return (sortOrder() == Qt::AscendingOrder) ? result < 0 : result > 0; +} + +int KFileItemModel::sortRoleCompare(const ItemData* a, const ItemData* b) const +{ + const KFileItem& itemA = a->item; + const KFileItem& itemB = b->item; + + int result = 0; + + switch (m_sortRole) { + case NameRole: + // The name role is handled as default fallback after the switch break; - } case SizeRole: { if (itemA.isDir()) { - Q_ASSERT(itemB.isDir()); // see "if (m_sortFoldersFirst || m_sortRole == SizeRole)" above + // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan(): + Q_ASSERT(itemB.isDir()); const QVariant valueA = a->values.value("size"); const QVariant valueB = b->values.value("size"); - - if (valueA.isNull()) { + if (valueA.isNull() && valueB.isNull()) { + result = 0; + } else if (valueA.isNull()) { result = -1; } else if (valueB.isNull()) { result = +1; } else { - result = valueA.value() - valueB.value(); + result = valueA.toInt() - valueB.toInt(); } } else { - Q_ASSERT(!itemB.isDir()); // see "if (m_sortFoldersFirst || m_sortRole == SizeRole)" above - result = itemA.size() - itemB.size(); + // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan(): + Q_ASSERT(!itemB.isDir()); + const KIO::filesize_t sizeA = itemA.size(); + const KIO::filesize_t sizeB = itemB.size(); + if (sizeA > sizeB) { + result = +1; + } else if (sizeA < sizeB) { + result = -1; + } else { + result = 0; + } } break; } - case TypeRole: { - result = QString::compare(a->values.value("type").toString(), - b->values.value("type").toString()); + case DateRole: { + const KDateTime dateTimeA = itemA.time(KFileItem::ModificationTime); + const KDateTime dateTimeB = itemB.time(KFileItem::ModificationTime); + if (dateTimeA < dateTimeB) { + result = -1; + } else if (dateTimeA > dateTimeB) { + result = +1; + } break; } - case CommentRole: { - result = QString::compare(a->values.value("comment").toString(), - b->values.value("comment").toString()); + case RatingRole: { + result = a->values.value("rating").toInt() - b->values.value("rating").toInt(); break; - } + } + case PermissionsRole: + case OwnerRole: + case GroupRole: + case TypeRole: + case DestinationRole: + case PathRole: + case CommentRole: 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(); + const QByteArray role = roleForType(m_sortRole); + result = QString::compare(a->values.value(role).toString(), + b->values.value(role).toString()); break; } @@ -1196,28 +1363,42 @@ bool KFileItemModel::lessThan(const ItemData* a, const ItemData* b) const break; } - if (result == 0) { - // 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(itemA.url().url(), itemB.url().url(), Qt::CaseSensitive); + if (result != 0) { + // The current sort role was sufficient to define an order + return result; } - return (sortOrder() == Qt::AscendingOrder) ? result < 0 : result > 0; + // Fallback #1: Compare the text of the items + result = stringCompare(itemA.text(), itemB.text()); + if (result != 0) { + return result; + } + + // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used + result = stringCompare(itemA.name(m_caseSensitivity == Qt::CaseInsensitive), + itemB.name(m_caseSensitivity == Qt::CaseInsensitive)); + if (result != 0) { + return result; + } + + // Fallback #3: 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. + return QString::compare(itemA.url().url(), itemB.url().url(), Qt::CaseSensitive); } 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 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); @@ -1230,21 +1411,21 @@ void KFileItemModel::merge(QList::iterator begin, { // 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; @@ -1258,11 +1439,11 @@ void KFileItemModel::merge(QList::iterator begin, 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); @@ -1274,7 +1455,7 @@ QList::iterator KFileItemModel::lowerBound(QList::iterator middle; int n = int(end - begin); int half; @@ -1298,7 +1479,7 @@ QList::iterator KFileItemModel::upperBound(QList::iterator middle; int n = end - begin; int half; @@ -1321,11 +1502,11 @@ void KFileItemModel::reverse(QList::iterator begin, { // 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 @@ -1350,10 +1531,10 @@ int KFileItemModel::stringCompare(const QString& a, const QString& b) const : QString::compare(a, b, Qt::CaseSensitive); } -int KFileItemModel::expansionLevelsCompare(const KFileItem& a, const KFileItem& b) const +int KFileItemModel::expandedParentsCountCompare(const ItemData* a, const ItemData* b) const { - const KUrl urlA = a.url(); - const KUrl urlB = b.url(); + const KUrl urlA = a->item.url(); + const KUrl urlB = b->item.url(); if (urlA.directory() == urlB.directory()) { // Both items have the same directory as parent return 0; @@ -1361,9 +1542,9 @@ int KFileItemModel::expansionLevelsCompare(const KFileItem& a, const KFileItem& // Check whether one item is the parent of the other item if (urlA.isParentOf(urlB)) { - return -1; + return (sortOrder() == Qt::AscendingOrder) ? -1 : +1; } else if (urlB.isParentOf(urlA)) { - return +1; + return (sortOrder() == Qt::AscendingOrder) ? +1 : -1; } // Determine the maximum common path of both items and @@ -1386,17 +1567,39 @@ int KFileItemModel::expansionLevelsCompare(const KFileItem& a, const KFileItem& // Determine the first sub-path after the common path and // check whether it represents a directory or already a file bool isDirA = true; - const QString subPathA = subPath(a, pathA, index, &isDirA); + const QString subPathA = subPath(a->item, pathA, index, &isDirA); bool isDirB = true; - const QString subPathB = subPath(b, pathB, index, &isDirB); + const QString subPathB = subPath(b->item, pathB, index, &isDirB); - if (isDirA && !isDirB) { - return -1; - } else if (!isDirA && isDirB) { - return +1; + if (m_sortFoldersFirst || m_sortRole == SizeRole) { + if (isDirA && !isDirB) { + return (sortOrder() == Qt::AscendingOrder) ? -1 : +1; + } else if (!isDirA && isDirB) { + return (sortOrder() == Qt::AscendingOrder) ? +1 : -1; + } + } + + // Compare the items of the parents that represent the first + // different path after the common path. + const QString parentPathA = pathA.left(index) + subPathA; + const QString parentPathB = pathB.left(index) + subPathB; + + const ItemData* parentA = a; + while (parentA && parentA->item.url().path() != parentPathA) { + parentA = parentA->parent; + } + + const ItemData* parentB = b; + while (parentB && parentB->item.url().path() != parentPathB) { + parentB = parentB->parent; } - return stringCompare(subPathA, subPathB); + if (parentA && parentB) { + return sortRoleCompare(parentA, parentB); + } + + kWarning() << "Child items without parent detected:" << a->item.url() << b->item.url(); + return QString::compare(urlA.url(), urlB.url(), Qt::CaseSensitive); } QString KFileItemModel::subPath(const KFileItem& item, @@ -1436,7 +1639,7 @@ QList > KFileItemModel::nameRoleGroups() const // Use the first character of the name as group indication QChar newFirstChar = name.at(0).toUpper(); if (newFirstChar == QLatin1Char('~') && name.length() > 1) { - newFirstChar = name.at(1); + newFirstChar = name.at(1).toUpper(); } if (firstChar != newFirstChar) { @@ -1692,12 +1895,12 @@ QList > KFileItemModel::ratingRoleGroups() const const int maxIndex = count() - 1; QList > groups; - int groupValue; + int groupValue = -1; for (int i = 0; i <= maxIndex; ++i) { if (isChildItem(i)) { continue; } - const int newGroupValue = m_itemData.at(i)->values.value("rating").toInt(); + const int newGroupValue = m_itemData.at(i)->values.value("rating", 0).toInt(); if (newGroupValue != groupValue) { groupValue = newGroupValue; groups.append(QPair(i, newGroupValue)); @@ -1714,30 +1917,70 @@ QList > KFileItemModel::genericStringRoleGroups(const QByte const int maxIndex = count() - 1; QList > groups; + bool isFirstGroupValue = true; 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) { + if (newGroupValue != groupValue || isFirstGroupValue) { groupValue = newGroupValue; groups.append(QPair(i, newGroupValue)); + isFirstGroupValue = false; } } return groups; } -bool KFileItemModel::matchesNameFilter(const KFileItem& item) const +KFileItemList KFileItemModel::childItems(const KFileItem& item) const { - // TODO #1: A performance improvement would be possible by caching m_nameFilter.toLower(). - // Before adding yet-another-member it should be checked whether it brings a noticable - // improvement at all. + KFileItemList items; + + int index = m_items.value(item.url(), -1); + if (index >= 0) { + const int parentLevel = m_itemData.at(index)->values.value("expandedParentsCount").toInt(); + ++index; + while (index < m_itemData.count() && m_itemData.at(index)->values.value("expandedParentsCount").toInt() > parentLevel) { + items.append(m_itemData.at(index)->item); + ++index; + } + } - // TODO #2: If the user entered a '*' use a regular expression - const QString itemText = item.text().toLower(); - return itemText.contains(m_nameFilter.toLower()); + return items; +} + +const KFileItemModel::RoleInfoMap* KFileItemModel::rolesInfoMap(int& count) +{ + static const RoleInfoMap rolesInfoMap[] = { + // role roleType role translation group translation + { 0, NoRole, 0, 0, 0, 0 }, + { "name", NameRole, I18N_NOOP2_NOSTRIP("@label", "Name"), 0, 0 }, + { "size", SizeRole, I18N_NOOP2_NOSTRIP("@label", "Size"), 0, 0 }, + { "date", DateRole, I18N_NOOP2_NOSTRIP("@label", "Date"), 0, 0 }, + { "type", TypeRole, I18N_NOOP2_NOSTRIP("@label", "Type"), 0, 0 }, + { "rating", RatingRole, I18N_NOOP2_NOSTRIP("@label", "Rating"), 0, 0 }, + { "tags", TagsRole, I18N_NOOP2_NOSTRIP("@label", "Tags"), 0, 0 }, + { "comment", CommentRole, I18N_NOOP2_NOSTRIP("@label", "Comment"), 0, 0 }, + { "wordCount", WordCountRole, I18N_NOOP2_NOSTRIP("@label", "Word Count"), I18N_NOOP2_NOSTRIP("@label", "Document") }, + { "lineCount", LineCountRole, I18N_NOOP2_NOSTRIP("@label", "Line Count"), I18N_NOOP2_NOSTRIP("@label", "Document") }, + { "imageSize", ImageSizeRole, I18N_NOOP2_NOSTRIP("@label", "Image Size"), I18N_NOOP2_NOSTRIP("@label", "Image") }, + { "orientation", OrientationRole, I18N_NOOP2_NOSTRIP("@label", "Orientation"), I18N_NOOP2_NOSTRIP("@label", "Image") }, + { "artist", ArtistRole, I18N_NOOP2_NOSTRIP("@label", "Artist"), I18N_NOOP2_NOSTRIP("@label", "Music") }, + { "album", AlbumRole, I18N_NOOP2_NOSTRIP("@label", "Album"), I18N_NOOP2_NOSTRIP("@label", "Music") }, + { "duration", DurationRole, I18N_NOOP2_NOSTRIP("@label", "Duration"), I18N_NOOP2_NOSTRIP("@label", "Music") }, + { "track", TrackRole, I18N_NOOP2_NOSTRIP("@label", "Track"), I18N_NOOP2_NOSTRIP("@label", "Music") }, + { "path", PathRole, I18N_NOOP2_NOSTRIP("@label", "Path"), I18N_NOOP2_NOSTRIP("@label", "Other") }, + { "destination", DestinationRole, I18N_NOOP2_NOSTRIP("@label", "Link Destination"), I18N_NOOP2_NOSTRIP("@label", "Other") }, + { "copiedFrom", CopiedFromRole, I18N_NOOP2_NOSTRIP("@label", "Copied From"), I18N_NOOP2_NOSTRIP("@label", "Other") }, + { "permissions", PermissionsRole, I18N_NOOP2_NOSTRIP("@label", "Permissions"), I18N_NOOP2_NOSTRIP("@label", "Other") }, + { "owner", OwnerRole, I18N_NOOP2_NOSTRIP("@label", "Owner"), I18N_NOOP2_NOSTRIP("@label", "Other") }, + { "group", GroupRole, I18N_NOOP2_NOSTRIP("@label", "Group"), I18N_NOOP2_NOSTRIP("@label", "Other") }, + }; + + count = sizeof(rolesInfoMap) / sizeof(RoleInfoMap); + return rolesInfoMap; } #include "kfileitemmodel.moc"