diff options
Diffstat (limited to 'src/kitemviews')
22 files changed, 669 insertions, 602 deletions
diff --git a/src/kitemviews/kfileitemmodel.cpp b/src/kitemviews/kfileitemmodel.cpp index 87006718a..fd773e1e9 100644 --- a/src/kitemviews/kfileitemmodel.cpp +++ b/src/kitemviews/kfileitemmodel.cpp @@ -21,7 +21,6 @@ #include "kfileitemmodel.h" -#include <KDirModel> #include <KGlobalSettings> #include <KLocale> #include <KStringHandler> @@ -76,7 +75,6 @@ KFileItemModel::KFileItemModel(QObject* parent) : connect(m_dirLister, SIGNAL(itemsDeleted(KFileItemList)), this, SLOT(slotItemsDeleted(KFileItemList))); connect(m_dirLister, SIGNAL(refreshItems(QList<QPair<KFileItem,KFileItem> >)), this, SLOT(slotRefreshItems(QList<QPair<KFileItem,KFileItem> >))); connect(m_dirLister, SIGNAL(clear()), this, SLOT(slotClear())); - connect(m_dirLister, SIGNAL(clear(KUrl)), this, SLOT(slotClear(KUrl))); connect(m_dirLister, SIGNAL(infoMessage(QString)), this, SIGNAL(infoMessage(QString))); connect(m_dirLister, SIGNAL(errorMessage(QString)), this, SIGNAL(errorMessage(QString))); connect(m_dirLister, SIGNAL(redirection(KUrl,KUrl)), this, SIGNAL(directoryRedirection(KUrl,KUrl))); @@ -247,9 +245,23 @@ QMimeData* KFileItemModel::createMimeData(const KItemSet& indexes) const KUrl::List urls; KUrl::List mostLocalUrls; bool canUseMostLocalUrls = true; + const ItemData* lastAddedItem = 0; foreach (int index, indexes) { - const KFileItem item = fileItem(index); + const ItemData* itemData = m_itemData.at(index); + const ItemData* parent = itemData->parent; + + while (parent && parent != lastAddedItem) { + parent = parent->parent; + } + + if (parent && parent == lastAddedItem) { + // A parent of 'itemData' has been added already. + continue; + } + + lastAddedItem = itemData; + const KFileItem& item = itemData->item; if (!item.isNull()) { urls << item.targetUrl(); @@ -262,9 +274,7 @@ QMimeData* KFileItemModel::createMimeData(const KItemSet& indexes) const } const bool different = canUseMostLocalUrls && mostLocalUrls != urls; - urls = KDirModel::simplifiedUrlList(urls); // TODO: Check if we still need KDirModel for this in KDE 5.0 if (different) { - mostLocalUrls = KDirModel::simplifiedUrlList(mostLocalUrls); urls.populateMimeData(mostLocalUrls, data); } else { urls.populateMimeData(data); @@ -344,27 +354,50 @@ KFileItem KFileItemModel::fileItem(int index) const KFileItem KFileItemModel::fileItem(const KUrl& url) const { - const int index = m_items.value(url, -1); - if (index >= 0) { - return m_itemData.at(index)->item; + const int indexForUrl = index(url); + if (indexForUrl >= 0) { + return m_itemData.at(indexForUrl)->item; } return KFileItem(); } int KFileItemModel::index(const KFileItem& item) const { - if (item.isNull()) { - return -1; - } - - return m_items.value(item.url(), -1); + return index(item.url()); } int KFileItemModel::index(const KUrl& url) const { KUrl urlToFind = url; urlToFind.adjustPath(KUrl::RemoveTrailingSlash); - return m_items.value(urlToFind, -1); + + const int itemCount = m_itemData.count(); + int itemsInHash = m_items.count(); + + int index = m_items.value(urlToFind, -1); + while (index < 0 && itemsInHash < itemCount) { + // Not all URLs are stored yet in m_items. We grow m_items until either + // urlToFind is found, or all URLs have been stored in m_items. + // Note that we do not add the URLs to m_items one by one, but in + // larger blocks. After each block, we check if urlToFind is in + // m_items. We could in principle compare urlToFind with each URL while + // we are going through m_itemData, but comparing two QUrls will, + // unlike calling qHash for the URLs, trigger a parsing of the URLs + // which costs both CPU cycles and memory. + const int blockSize = 1000; + const int currentBlockEnd = qMin(itemsInHash + blockSize, itemCount); + for (int i = itemsInHash; i < currentBlockEnd; ++i) { + const KUrl nextUrl = m_itemData.at(i)->item.url(); + m_items.insert(nextUrl, i); + } + + itemsInHash = currentBlockEnd; + index = m_items.value(urlToFind, -1); + } + + Q_ASSERT(index >= 0 || m_items.count() == m_itemData.count()); + + return index; } KFileItem KFileItemModel::rootItem() const @@ -662,7 +695,7 @@ QList<KFileItemModel::RoleInfo> KFileItemModel::rolesInformation() // menus tries to put the actions into sub menus otherwise. info.group = QString(); } - info.requiresNepomuk = map[i].requiresNepomuk; + info.requiresBaloo = map[i].requiresBaloo; info.requiresIndexer = map[i].requiresIndexer; rolesInfo.append(info); } @@ -725,6 +758,7 @@ void KFileItemModel::resortAllItems() } m_items.clear(); + m_items.reserve(itemCount); // Resort the items sort(m_itemData.begin(), m_itemData.end()); @@ -787,10 +821,10 @@ void KFileItemModel::slotCompleted() // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet // -> we expand the first visible URL we find in m_restoredExpandedUrls. foreach (const KUrl& url, m_urlsToExpand) { - const int index = m_items.value(url, -1); - if (index >= 0) { + const int indexForUrl = index(url); + if (indexForUrl >= 0) { m_urlsToExpand.remove(url); - if (setExpanded(index, true)) { + if (setExpanded(indexForUrl, true)) { // The dir lister has been triggered. This slot will be called // again after the directory has been expanded. return; @@ -827,15 +861,12 @@ void KFileItemModel::slotItemsAdded(const KUrl& directoryUrl, const KFileItemLis } if (m_requestRole[ExpandedParentsCountRole]) { - 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) { + if (index(items.first().url()) >= 0) { // The items are already part of the model. return; } @@ -849,7 +880,7 @@ void KFileItemModel::slotItemsAdded(const KUrl& directoryUrl, const KFileItemLis // 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. - const int parentIndex = m_items.value(parentUrl, -1); + const int parentIndex = index(parentUrl); if (parentIndex >= 0 && !m_itemData[parentIndex]->values.value("isExpanded").toBool()) { // The parent is not expanded. return; @@ -888,10 +919,9 @@ void KFileItemModel::slotItemsDeleted(const KFileItemList& items) indexesToRemove.reserve(items.count()); foreach (const KFileItem& item, items) { - const KUrl url = item.url(); - const int index = m_items.value(url, -1); - if (index >= 0) { - indexesToRemove.append(index); + const int indexForItem = index(item); + if (indexForItem >= 0) { + indexesToRemove.append(indexForItem); } else { // Probably the item has been filtered. QHash<KFileItem, ItemData*>::iterator it = m_filteredItems.find(item); @@ -907,7 +937,7 @@ void KFileItemModel::slotItemsDeleted(const KFileItemList& items) if (m_requestRole[ExpandedParentsCountRole] && !m_expandedDirs.isEmpty()) { // Assure that removing a parent item also results in removing all children QVector<int> indexesToRemoveWithChildren; - indexesToRemoveWithChildren.reserve(m_items.count()); + indexesToRemoveWithChildren.reserve(m_itemData.count()); const int itemCount = m_itemData.count(); foreach (int index, indexesToRemove) { @@ -947,14 +977,14 @@ void KFileItemModel::slotRefreshItems(const QList<QPair<KFileItem, KFileItem> >& const QPair<KFileItem, KFileItem>& itemPair = it.next(); const KFileItem& oldItem = itemPair.first; const KFileItem& newItem = itemPair.second; - const int index = m_items.value(oldItem.url(), -1); - if (index >= 0) { - m_itemData[index]->item = newItem; + const int indexForItem = index(oldItem); + if (indexForItem >= 0) { + m_itemData[indexForItem]->item = 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<QByteArray, QVariant> it(retrieveData(newItem, m_itemData.at(index)->parent)); - QHash<QByteArray, QVariant>& values = m_itemData[index]->values; + QHashIterator<QByteArray, QVariant> it(retrieveData(newItem, m_itemData.at(indexForItem)->parent)); + QHash<QByteArray, QVariant>& values = m_itemData[indexForItem]->values; while (it.hasNext()) { it.next(); const QByteArray& role = it.key(); @@ -965,8 +995,8 @@ void KFileItemModel::slotRefreshItems(const QList<QPair<KFileItem, KFileItem> >& } m_items.remove(oldItem.url()); - m_items.insert(newItem.url(), index); - indexes.append(index); + m_items.insert(newItem.url(), indexForItem); + indexes.append(indexForItem); } else { // Check if 'oldItem' is one of the filtered items. QHash<KFileItem, ItemData*>::iterator it = m_filteredItems.find(oldItem); @@ -1023,11 +1053,6 @@ void KFileItemModel::slotClear() m_expandedDirs.clear(); } -void KFileItemModel::slotClear(const KUrl& url) -{ - Q_UNUSED(url); -} - void KFileItemModel::slotNaturalSortingChanged() { m_naturalSorting = KGlobalSettings::naturalSorting(); @@ -1088,7 +1113,7 @@ void KFileItemModel::insertItems(QList<ItemData*>& newItems) m_itemData.append(0); } - // We build the new list m_items in reverse order to minimize + // We build the new list m_itemData in reverse order to minimize // the number of moves and guarantee O(N) complexity. int targetIndex = totalItemCount - 1; int sourceIndexExistingItems = existingItemCount - 1; @@ -1126,11 +1151,9 @@ void KFileItemModel::insertItems(QList<ItemData*>& newItems) std::reverse(itemRanges.begin(), itemRanges.end()); } - // The indexes starting from the first inserted item must be adjusted. - m_items.reserve(totalItemCount); - for (int i = itemRanges.front().index; i < totalItemCount; ++i) { - m_items.insert(m_itemData.at(i)->item.url(), i); - } + // The indexes in m_items are not correct anymore. Therefore, we clear m_items. + // It will be re-populated with the updated indices if index(const KUrl&) is called. + m_items.clear(); emit itemsInserted(itemRanges); @@ -1147,19 +1170,12 @@ void KFileItemModel::removeItems(const KItemRangeList& itemRanges, RemoveItemsBe m_groups.clear(); - // Step 1: Remove the items from the hash m_items, and free the ItemData. + // Step 1: Remove the items from m_itemData, and free the ItemData. int removedItemsCount = 0; foreach (const KItemRange& range, itemRanges) { removedItemsCount += range.count; for (int index = range.index; index < range.index + range.count; ++index) { - const KUrl url = m_itemData.at(index)->item.url(); - - // Prevent repeated expensive rehashing by using QHash::erase(), - // rather than QHash::remove(). - QHash<KUrl, int>::iterator it = m_items.find(url); - m_items.erase(it); - if (behavior == DeleteItemData) { delete m_itemData.at(index); } @@ -1188,12 +1204,9 @@ void KFileItemModel::removeItems(const KItemRangeList& itemRanges, RemoveItemsBe m_itemData.erase(m_itemData.end() - removedItemsCount, m_itemData.end()); - // Step 3: Adjust indexes in the hash m_items, starting from the - // index of the first removed item. - const int newItemDataCount = m_itemData.count(); - for (int i = itemRanges.front().index; i < newItemDataCount; ++i) { - m_items.insert(m_itemData.at(i)->item.url(), i); - } + // The indexes in m_items are not correct anymore. Therefore, we clear m_items. + // It will be re-populated with the updated indices if index(const KUrl&) is called. + m_items.clear(); emit itemsRemoved(itemRanges); } @@ -1207,7 +1220,7 @@ QList<KFileItemModel::ItemData*> KFileItemModel::createItemDataList(const KUrl& determineMimeTypes(items, 200); } - const int parentIndex = m_items.value(parentUrl, -1); + const int parentIndex = index(parentUrl); ItemData* parentItem = parentIndex < 0 ? 0 : m_itemData.at(parentIndex); QList<ItemData*> itemDataList; @@ -2070,7 +2083,7 @@ void KFileItemModel::emitSortProgress(int resolvedCount) const KFileItemModel::RoleInfoMap* KFileItemModel::rolesInfoMap(int& count) { static const RoleInfoMap rolesInfoMap[] = { - // | role | roleType | role translation | group translation | requires Nepomuk | requires indexer + // | role | roleType | role translation | group translation | requires Baloo | requires indexer { 0, NoRole, 0, 0, 0, 0, false, false }, { "text", NameRole, I18N_NOOP2_NOSTRIP("@label", "Name"), 0, 0, false, false }, { "size", SizeRole, I18N_NOOP2_NOSTRIP("@label", "Size"), 0, 0, false, false }, @@ -2136,7 +2149,9 @@ QByteArray KFileItemModel::sharedValue(const QByteArray& value) bool KFileItemModel::isConsistent() const { - if (m_items.count() != m_itemData.count()) { + // m_items may contain less items than m_itemData because m_items + // is populated lazily, see KFileItemModel::index(const KUrl& url). + if (m_items.count() > m_itemData.count()) { return false; } diff --git a/src/kitemviews/kfileitemmodel.h b/src/kitemviews/kfileitemmodel.h index 022429023..62a283d33 100644 --- a/src/kitemviews/kfileitemmodel.h +++ b/src/kitemviews/kfileitemmodel.h @@ -130,14 +130,14 @@ public: /** * @return The index for the file-item \a item. -1 is returned if no file-item - * is found or if the file-item is null. The runtime + * is found or if the file-item is null. The amortized runtime * complexity of this call is O(1). */ int index(const KFileItem& item) const; /** * @return The index for the URL \a url. -1 is returned if no file-item - * is found. The runtime complexity of this call is O(1). + * is found. The amortized runtime complexity of this call is O(1). */ int index(const KUrl& url) const; @@ -187,14 +187,14 @@ public: { QByteArray role; QString translation; QString group; - bool requiresNepomuk; + bool requiresBaloo; bool requiresIndexer; }; /** * @return Provides static information for all available roles that * are supported by KFileItemModel. Some roles can only be - * determined if Nepomuk is enabled and/or the Nepomuk + * determined if Baloo is enabled and/or the Baloo * indexing is enabled. */ static QList<RoleInfo> rolesInformation(); @@ -277,7 +277,6 @@ private slots: void slotItemsDeleted(const KFileItemList& items); void slotRefreshItems(const QList<QPair<KFileItem, KFileItem> >& items); void slotClear(); - void slotClear(const KUrl& url); void slotNaturalSortingChanged(); void dispatchPendingItemsToInsert(); @@ -287,7 +286,7 @@ private: // User visible roles: NoRole, NameRole, SizeRole, DateRole, PermissionsRole, OwnerRole, GroupRole, TypeRole, DestinationRole, PathRole, - // User visible roles available with Nepomuk: + // User visible roles available with Baloo: CommentRole, TagsRole, RatingRole, ImageSizeRole, OrientationRole, WordCountRole, LineCountRole, ArtistRole, AlbumRole, DurationRole, TrackRole, CopiedFromRole, @@ -432,7 +431,7 @@ private: const char* const roleTranslation; const char* const groupTranslationContext; const char* const groupTranslation; - const bool requiresNepomuk; + const bool requiresBaloo; const bool requiresIndexer; }; @@ -470,7 +469,12 @@ private: Qt::CaseSensitivity m_caseSensitivity; QList<ItemData*> m_itemData; - QHash<KUrl, int> m_items; // Allows O(1) access for KFileItemModel::index(const KFileItem& item) + + // m_items is a cache for the method index(const KUrl&). If it contains N + // entries, it is guaranteed that these correspond to the first N items in + // the model, i.e., that (for every i between 0 and N - 1) + // m_items.value(fileItem(i).url()) == i + mutable QHash<KUrl, int> m_items; KFileItemModelFilter m_filter; QHash<KFileItem, ItemData*> m_filteredItems; // Items that got hidden by KFileItemModel::setNameFilter() diff --git a/src/kitemviews/kfileitemmodelrolesupdater.cpp b/src/kitemviews/kfileitemmodelrolesupdater.cpp index d6445c981..0865d40e7 100644 --- a/src/kitemviews/kfileitemmodelrolesupdater.cpp +++ b/src/kitemviews/kfileitemmodelrolesupdater.cpp @@ -40,10 +40,11 @@ #include <algorithm> -#ifdef HAVE_NEPOMUK - #include "private/knepomukrolesprovider.h" - #include <Nepomuk2/ResourceWatcher> - #include <Nepomuk2/ResourceManager> +#ifdef HAVE_BALOO + #include "private/kbaloorolesprovider.h" + #include <baloo/file.h> + #include <baloo/filefetchjob.h> + #include <baloo/filemonitor.h> #endif // #define KFILEITEMMODELROLESUPDATER_DEBUG @@ -88,9 +89,8 @@ KFileItemModelRolesUpdater::KFileItemModelRolesUpdater(KFileItemModel* model, QO m_recentlyChangedItems(), m_changedItems(), m_directoryContentsCounter(0) - #ifdef HAVE_NEPOMUK - , m_nepomukResourceWatcher(0), - m_nepomukUriItems() + #ifdef HAVE_BALOO + , m_balooFileMonitor(0) #endif { Q_ASSERT(model); @@ -122,8 +122,8 @@ KFileItemModelRolesUpdater::KFileItemModelRolesUpdater(KFileItemModel* model, QO m_resolvableRoles.insert("size"); m_resolvableRoles.insert("type"); m_resolvableRoles.insert("isExpandable"); -#ifdef HAVE_NEPOMUK - m_resolvableRoles += KNepomukRolesProvider::instance().roles(); +#ifdef HAVE_BALOO + m_resolvableRoles += KBalooRolesProvider::instance().roles(); #endif m_directoryContentsCounter = new KDirectoryContentsCounter(m_model, this); @@ -262,34 +262,29 @@ void KFileItemModelRolesUpdater::setRoles(const QSet<QByteArray>& roles) if (m_roles != roles) { m_roles = roles; -#ifdef HAVE_NEPOMUK - if (Nepomuk2::ResourceManager::instance()->initialized()) { - // Check whether there is at least one role that must be resolved - // with the help of Nepomuk. If this is the case, a (quite expensive) - // resolving will be done in KFileItemModelRolesUpdater::rolesData() and - // the role gets watched for changes. - const KNepomukRolesProvider& rolesProvider = KNepomukRolesProvider::instance(); - bool hasNepomukRole = false; - QSetIterator<QByteArray> it(roles); - while (it.hasNext()) { - const QByteArray& role = it.next(); - if (rolesProvider.roles().contains(role)) { - hasNepomukRole = true; - break; - } +#ifdef HAVE_BALOO + // Check whether there is at least one role that must be resolved + // with the help of Baloo. If this is the case, a (quite expensive) + // resolving will be done in KFileItemModelRolesUpdater::rolesData() and + // the role gets watched for changes. + const KBalooRolesProvider& rolesProvider = KBalooRolesProvider::instance(); + bool hasBalooRole = false; + QSetIterator<QByteArray> it(roles); + while (it.hasNext()) { + const QByteArray& role = it.next(); + if (rolesProvider.roles().contains(role)) { + hasBalooRole = true; + break; } + } - if (hasNepomukRole && !m_nepomukResourceWatcher) { - Q_ASSERT(m_nepomukUriItems.isEmpty()); - - m_nepomukResourceWatcher = new Nepomuk2::ResourceWatcher(this); - connect(m_nepomukResourceWatcher, SIGNAL(propertyChanged(Nepomuk2::Resource,Nepomuk2::Types::Property,QVariantList,QVariantList)), - this, SLOT(applyChangedNepomukRoles(Nepomuk2::Resource,Nepomuk2::Types::Property))); - } else if (!hasNepomukRole && m_nepomukResourceWatcher) { - delete m_nepomukResourceWatcher; - m_nepomukResourceWatcher = 0; - m_nepomukUriItems.clear(); - } + if (hasBalooRole && !m_balooFileMonitor) { + m_balooFileMonitor = new Baloo::FileMonitor(this); + connect(m_balooFileMonitor, SIGNAL(fileMetaDataChanged(QString)), + this, SLOT(applyChangedBalooRoles(QString))); + } else if (!hasBalooRole && m_balooFileMonitor) { + delete m_balooFileMonitor; + m_balooFileMonitor = 0; } #endif @@ -357,30 +352,19 @@ void KFileItemModelRolesUpdater::slotItemsRemoved(const KItemRangeList& itemRang const bool allItemsRemoved = (m_model->count() == 0); -#ifdef HAVE_NEPOMUK - if (m_nepomukResourceWatcher) { - // Don't let the ResourceWatcher watch for removed items +#ifdef HAVE_BALOO + if (m_balooFileMonitor) { + // Don't let the FileWatcher watch for removed items if (allItemsRemoved) { - m_nepomukResourceWatcher->setResources(QList<Nepomuk2::Resource>()); - m_nepomukResourceWatcher->stop(); - m_nepomukUriItems.clear(); + m_balooFileMonitor->clear(); } else { - QList<Nepomuk2::Resource> newResources; - const QList<Nepomuk2::Resource> oldResources = m_nepomukResourceWatcher->resources(); - foreach (const Nepomuk2::Resource& resource, oldResources) { - const QUrl uri = resource.uri(); - const KUrl itemUrl = m_nepomukUriItems.value(uri); + QStringList newFileList; + foreach (const QString& itemUrl, m_balooFileMonitor->files()) { if (m_model->index(itemUrl) >= 0) { - newResources.append(resource); - } else { - m_nepomukUriItems.remove(uri); + newFileList.append(itemUrl); } } - m_nepomukResourceWatcher->setResources(newResources); - if (newResources.isEmpty()) { - Q_ASSERT(m_nepomukUriItems.isEmpty()); - m_nepomukResourceWatcher->stop(); - } + m_balooFileMonitor->setFiles(newFileList); } } #endif @@ -587,7 +571,7 @@ void KFileItemModelRolesUpdater::slotPreviewFailed(const KFileItem& item) connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)), this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>))); - applyResolvedRoles(item, ResolveAll); + applyResolvedRoles(index, ResolveAll); m_finishedItems.insert(item); } } @@ -664,7 +648,7 @@ void KFileItemModelRolesUpdater::resolveNextPendingRoles() continue; } - applyResolvedRoles(item, ResolveAll); + applyResolvedRoles(index, ResolveAll); m_finishedItems.insert(item); m_changedItems.remove(item); break; @@ -708,14 +692,9 @@ void KFileItemModelRolesUpdater::resolveRecentlyChangedItems() updateChangedItems(); } -void KFileItemModelRolesUpdater::applyChangedNepomukRoles(const Nepomuk2::Resource& resource, const Nepomuk2::Types::Property& property) +void KFileItemModelRolesUpdater::applyChangedBalooRoles(const QString& itemUrl) { -#ifdef HAVE_NEPOMUK - if (!Nepomuk2::ResourceManager::instance()->initialized()) { - return; - } - - const KUrl itemUrl = m_nepomukUriItems.value(resource.uri()); +#ifdef HAVE_BALOO const KFileItem item = m_model->fileItem(itemUrl); if (item.isNull()) { @@ -724,18 +703,34 @@ void KFileItemModelRolesUpdater::applyChangedNepomukRoles(const Nepomuk2::Resour return; } - QHash<QByteArray, QVariant> data = rolesData(item); + Baloo::FileFetchJob* job = new Baloo::FileFetchJob(item.localPath()); + connect(job, SIGNAL(finished(KJob*)), this, SLOT(applyChangedBalooRolesJobFinished(KJob*))); + job->setProperty("item", QVariant::fromValue(item)); + job->start(); +#else +#ifndef Q_CC_MSVC + Q_UNUSED(itemUrl); +#endif +#endif +} - const KNepomukRolesProvider& rolesProvider = KNepomukRolesProvider::instance(); - const QByteArray role = rolesProvider.roleForPropertyUri(property.uri()); - if (!role.isEmpty() && m_roles.contains(role)) { - // Overwrite the changed role value with an empty QVariant, because the roles +void KFileItemModelRolesUpdater::applyChangedBalooRolesJobFinished(KJob* kjob) +{ +#ifdef HAVE_BALOO + const KFileItem item = kjob->property("item").value<KFileItem>(); + + const KBalooRolesProvider& rolesProvider = KBalooRolesProvider::instance(); + QHash<QByteArray, QVariant> data; + + foreach (const QByteArray& role, rolesProvider.roles()) { + // Overwrite all the role values with an empty QVariant, because the roles // provider doesn't overwrite it when the property value list is empty. // See bug 322348 data.insert(role, QVariant()); } - QHashIterator<QByteArray, QVariant> it(rolesProvider.roleValues(resource, m_roles)); + Baloo::FileFetchJob* job = static_cast<Baloo::FileFetchJob*>(kjob); + QHashIterator<QByteArray, QVariant> it(rolesProvider.roleValues(job->file(), m_roles)); while (it.hasNext()) { it.next(); data.insert(it.key(), it.value()); @@ -747,10 +742,6 @@ void KFileItemModelRolesUpdater::applyChangedNepomukRoles(const Nepomuk2::Resour m_model->setData(index, data); connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)), this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>))); -#else -#ifndef Q_CC_MSVC - Q_UNUSED(resource); -#endif #endif } @@ -762,7 +753,6 @@ void KFileItemModelRolesUpdater::slotDirectoryContentsCountReceived(const QStrin if (getSizeRole || getIsExpandableRole) { const int index = m_model->index(KUrl(path)); if (index >= 0) { - QHash<QByteArray, QVariant> data; if (getSizeRole) { @@ -850,8 +840,7 @@ void KFileItemModelRolesUpdater::updateVisibleIcons() // Try to determine the final icons for all visible items. int index; for (index = m_firstVisibleIndex; index <= lastVisibleIndex && timer.elapsed() < MaxBlockTimeout; ++index) { - const KFileItem item = m_model->fileItem(index); - applyResolvedRoles(item, ResolveFast); + applyResolvedRoles(index, ResolveFast); } // KFileItemListView::initializeItemListWidget(KItemListWidget*) will load @@ -1005,7 +994,7 @@ void KFileItemModelRolesUpdater::applySortRole(int index) const QString path = item.localPath(); data.insert("size", m_directoryContentsCounter->countDirectoryContentsSynchronously(path)); } else { - // Probably the sort role is a Nepomuk role - just determine all roles. + // Probably the sort role is a baloo role - just determine all roles. data = rolesData(item); } @@ -1024,27 +1013,20 @@ void KFileItemModelRolesUpdater::applySortProgressToModel() m_model->emitSortProgress(resolvedCount); } -bool KFileItemModelRolesUpdater::applyResolvedRoles(const KFileItem& item, ResolveHint hint) +bool KFileItemModelRolesUpdater::applyResolvedRoles(int index, ResolveHint hint) { - if (item.isNull()) { - return false; - } - + const KFileItem item = m_model->fileItem(index); const bool resolveAll = (hint == ResolveAll); bool iconChanged = false; if (!item.isMimeTypeKnown() || !item.isFinalIconKnown()) { item.determineMimeType(); iconChanged = true; - } else { - const int index = m_model->index(item); - if (!m_model->data(index).contains("iconName")) { - iconChanged = true; - } + } else if (!m_model->data(index).contains("iconName")) { + iconChanged = true; } if (iconChanged || resolveAll || m_clearPreviews) { - const int index = m_model->index(item); if (index < 0) { return false; } @@ -1095,35 +1077,12 @@ QHash<QByteArray, QVariant> KFileItemModelRolesUpdater::rolesData(const KFileIte data.insert("iconOverlays", item.overlays()); -#ifdef HAVE_NEPOMUK - if (m_nepomukResourceWatcher) { - const KNepomukRolesProvider& rolesProvider = KNepomukRolesProvider::instance(); - Nepomuk2::Resource resource(item.nepomukUri()); - QHashIterator<QByteArray, QVariant> it(rolesProvider.roleValues(resource, m_roles)); - while (it.hasNext()) { - it.next(); - data.insert(it.key(), it.value()); - } - - QUrl uri = resource.uri(); - if (uri.isEmpty()) { - // TODO: Is there another way to explicitly create a resource? - // We need a resource to be able to track it for changes. - resource.setRating(0); - uri = resource.uri(); - } - if (!uri.isEmpty() && !m_nepomukUriItems.contains(uri)) { - m_nepomukResourceWatcher->addResource(resource); - - if (m_nepomukUriItems.isEmpty()) { - m_nepomukResourceWatcher->start(); - } - - m_nepomukUriItems.insert(uri, item.url()); - } +#ifdef HAVE_BALOO + if (m_balooFileMonitor) { + m_balooFileMonitor->addFile(item.localPath()); + applyChangedBalooRoles(item.localPath()); } #endif - return data; } diff --git a/src/kitemviews/kfileitemmodelrolesupdater.h b/src/kitemviews/kfileitemmodelrolesupdater.h index fced44a85..a9e979ae1 100644 --- a/src/kitemviews/kfileitemmodelrolesupdater.h +++ b/src/kitemviews/kfileitemmodelrolesupdater.h @@ -20,7 +20,7 @@ #ifndef KFILEITEMMODELROLESUPDATER_H #define KFILEITEMMODELROLESUPDATER_H -#include <config-nepomuk.h> +#include <config-baloo.h> #include <KFileItem> #include <kitemviews/kitemmodelbase.h> @@ -38,26 +38,10 @@ class KJob; class QPixmap; class QTimer; -#ifdef HAVE_NEPOMUK - namespace Nepomuk2 +#ifdef HAVE_BALOO + namespace Baloo { - class ResourceWatcher; - class Resource; - namespace Types - { - class Property; - } - } -#else - // Required for the slot applyChangedNepomukRoles() that - // cannot be ifdefined due to moc. - namespace Nepomuk2 - { - class Resource; - namespace Types - { - class Property; - } + class FileMonitor; } #endif @@ -216,7 +200,8 @@ private slots: */ void resolveRecentlyChangedItems(); - void applyChangedNepomukRoles(const Nepomuk2::Resource& resource, const Nepomuk2::Types::Property& property); + void applyChangedBalooRoles(const QString& file); + void applyChangedBalooRolesJobFinished(KJob* job); void slotDirectoryContentsCountReceived(const QString& path, int count); @@ -261,7 +246,7 @@ private: ResolveFast, ResolveAll }; - bool applyResolvedRoles(const KFileItem& item, ResolveHint hint); + bool applyResolvedRoles(int index, ResolveHint hint); QHash<QByteArray, QVariant> rolesData(const KFileItem& item); /** @@ -346,9 +331,8 @@ private: KDirectoryContentsCounter* m_directoryContentsCounter; -#ifdef HAVE_NEPOMUK - Nepomuk2::ResourceWatcher* m_nepomukResourceWatcher; - mutable QHash<QUrl, KUrl> m_nepomukUriItems; +#ifdef HAVE_BALOO + Baloo::FileMonitor* m_balooFileMonitor; #endif }; diff --git a/src/kitemviews/kitemliststyleoption.cpp b/src/kitemviews/kitemliststyleoption.cpp index ac2587962..edd6363c8 100644 --- a/src/kitemviews/kitemliststyleoption.cpp +++ b/src/kitemviews/kitemliststyleoption.cpp @@ -31,7 +31,8 @@ KItemListStyleOption::KItemListStyleOption() : verticalMargin(-1), iconSize(-1), extendedSelectionRegion(false), - maxTextSize() + maxTextLines(0), + maxTextWidth(0) { } @@ -45,7 +46,8 @@ KItemListStyleOption::KItemListStyleOption(const KItemListStyleOption& other) : verticalMargin(other.verticalMargin), iconSize(other.iconSize), extendedSelectionRegion(other.extendedSelectionRegion), - maxTextSize(other.maxTextSize) + maxTextLines(other.maxTextLines), + maxTextWidth(other.maxTextWidth) { } diff --git a/src/kitemviews/kitemliststyleoption.h b/src/kitemviews/kitemliststyleoption.h index 1a304fc28..782dd0ec2 100644 --- a/src/kitemviews/kitemliststyleoption.h +++ b/src/kitemviews/kitemliststyleoption.h @@ -43,7 +43,8 @@ public: int verticalMargin; int iconSize; bool extendedSelectionRegion; - QSize maxTextSize; + int maxTextLines; + int maxTextWidth; }; #endif diff --git a/src/kitemviews/kitemlistview.cpp b/src/kitemviews/kitemlistview.cpp index 7f497210c..f1b35fa53 100644 --- a/src/kitemviews/kitemlistview.cpp +++ b/src/kitemviews/kitemlistview.cpp @@ -111,8 +111,7 @@ KItemListView::KItemListView(QGraphicsWidget* parent) : m_sizeHintResolver = new KItemListSizeHintResolver(this); - m_layouter = new KItemListViewLayouter(this); - m_layouter->setSizeHintResolver(m_sizeHintResolver); + m_layouter = new KItemListViewLayouter(m_sizeHintResolver, this); m_animation = new KItemListViewAnimation(this); connect(m_animation, SIGNAL(finished(QGraphicsWidget*,KItemListViewAnimation::AnimationType)), @@ -460,9 +459,9 @@ int KItemListView::lastVisibleIndex() const return m_layouter->lastVisibleIndex(); } -QSizeF KItemListView::itemSizeHint(int index) const +void KItemListView::calculateItemSizeHints(QVector<QSizeF>& sizeHints) const { - return widgetCreator()->itemSizeHint(index, this); + widgetCreator()->calculateItemSizeHints(sizeHints, this); } void KItemListView::setSupportsItemExpanding(bool supportsExpanding) @@ -761,7 +760,8 @@ void KItemListView::setStyleOption(const KItemListStyleOption& option) updateGroupHeaderHeight(); } - if (animate && previousOption.maxTextSize != option.maxTextSize) { + if (animate && + (previousOption.maxTextLines != option.maxTextLines || previousOption.maxTextWidth != option.maxTextWidth)) { // Animating a change of the maximum text size just results in expensive // temporary eliding and clipping operations and does not look good visually. animate = false; @@ -894,11 +894,23 @@ void KItemListView::onTransactionEnd() bool KItemListView::event(QEvent* event) { - // Forward all events to the controller and handle them there - if (!m_editingRole && m_controller && m_controller->processEvent(event, transform())) { - event->accept(); - return true; + switch (event->type()) { + case QEvent::PaletteChange: + updatePalette(); + break; + + case QEvent::FontChange: + updateFont(); + break; + + default: + // Forward all other events to the controller and handle them there + if (!m_editingRole && m_controller && m_controller->processEvent(event, transform())) { + event->accept(); + return true; + } } + return QGraphicsWidget::event(event); } @@ -951,6 +963,27 @@ QList<KItemListWidget*> KItemListView::visibleItemListWidgets() const return m_visibleItems.values(); } +void KItemListView::updateFont() +{ + if (scene() && !scene()->views().isEmpty()) { + KItemListStyleOption option = styleOption(); + option.font = scene()->views().first()->font(); + option.fontMetrics = QFontMetrics(option.font); + + setStyleOption(option); + } +} + +void KItemListView::updatePalette() +{ + if (scene() && !scene()->views().isEmpty()) { + KItemListStyleOption option = styleOption(); + option.palette = scene()->views().first()->palette(); + + setStyleOption(option); + } +} + void KItemListView::slotItemsInserted(const KItemRangeList& itemRanges) { if (m_itemSize.isEmpty()) { diff --git a/src/kitemviews/kitemlistview.h b/src/kitemviews/kitemlistview.h index dbe923086..8a522a686 100644 --- a/src/kitemviews/kitemlistview.h +++ b/src/kitemviews/kitemlistview.h @@ -194,12 +194,12 @@ public: int lastVisibleIndex() const; /** - * @return Required size for the item with the index \p index. + * @return Required size for all items in the model. * The returned value might be larger than KItemListView::itemSize(). * In this case the layout grid will be stretched to assure an * unclipped item. */ - QSizeF itemSizeHint(int index) const; + void calculateItemSizeHints(QVector<QSizeF>& sizeHints) const; /** * If set to true, items having child-items can be expanded to show the child-items as @@ -388,6 +388,9 @@ protected: QList<KItemListWidget*> visibleItemListWidgets() const; + virtual void updateFont(); + virtual void updatePalette(); + protected slots: virtual void slotItemsInserted(const KItemRangeList& itemRanges); virtual void slotItemsRemoved(const KItemRangeList& itemRanges); @@ -802,7 +805,7 @@ public: virtual void recycle(KItemListWidget* widget); - virtual QSizeF itemSizeHint(int index, const KItemListView* view) const = 0; + virtual void calculateItemSizeHints(QVector<QSizeF>& sizeHints, const KItemListView* view) const = 0; virtual qreal preferredRoleColumnWidth(const QByteArray& role, int index, @@ -821,7 +824,7 @@ public: virtual KItemListWidget* create(KItemListView* view); - virtual QSizeF itemSizeHint(int index, const KItemListView* view) const; + virtual void calculateItemSizeHints(QVector<QSizeF>& sizeHints, const KItemListView* view) const; virtual qreal preferredRoleColumnWidth(const QByteArray& role, int index, @@ -854,9 +857,9 @@ KItemListWidget* KItemListWidgetCreator<T>::create(KItemListView* view) } template<class T> -QSizeF KItemListWidgetCreator<T>::itemSizeHint(int index, const KItemListView* view) const +void KItemListWidgetCreator<T>::calculateItemSizeHints(QVector<QSizeF>& sizeHints, const KItemListView* view) const { - return m_informant->itemSizeHint(index, view); + return m_informant->calculateItemSizeHints(sizeHints, view); } template<class T> diff --git a/src/kitemviews/kitemlistwidget.h b/src/kitemviews/kitemlistwidget.h index 55181faa8..954629ddd 100644 --- a/src/kitemviews/kitemlistwidget.h +++ b/src/kitemviews/kitemlistwidget.h @@ -49,7 +49,7 @@ public: KItemListWidgetInformant(); virtual ~KItemListWidgetInformant(); - virtual QSizeF itemSizeHint(int index, const KItemListView* view) const = 0; + virtual void calculateItemSizeHints(QVector<QSizeF>& sizeHints, const KItemListView* view) const = 0; virtual qreal preferredRoleColumnWidth(const QByteArray& role, int index, diff --git a/src/kitemviews/kstandarditemlistwidget.cpp b/src/kitemviews/kstandarditemlistwidget.cpp index acdf839ac..9f7b26959 100644 --- a/src/kitemviews/kstandarditemlistwidget.cpp +++ b/src/kitemviews/kstandarditemlistwidget.cpp @@ -55,84 +55,25 @@ KStandardItemListWidgetInformant::~KStandardItemListWidgetInformant() { } -QSizeF KStandardItemListWidgetInformant::itemSizeHint(int index, const KItemListView* view) const +void KStandardItemListWidgetInformant::calculateItemSizeHints(QVector<QSizeF>& sizeHints, const KItemListView* view) const { - const KItemListStyleOption& option = view->styleOption(); - const int additionalRolesCount = qMax(view->visibleRoles().count() - 1, 0); - switch (static_cast<const KStandardItemListView*>(view)->itemLayout()) { - case KStandardItemListWidget::IconsLayout: { - const QString text = KStringHandler::preProcessWrap(itemText(index, view)); - - const qreal itemWidth = view->itemSize().width(); - const qreal maxWidth = itemWidth - 2 * option.padding; - QTextLine line; - - // Calculate the number of lines required for wrapping the name - QTextOption textOption(Qt::AlignHCenter); - textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); - - qreal textHeight = 0; - QTextLayout layout(text, option.font); - layout.setTextOption(textOption); - layout.beginLayout(); - while ((line = layout.createLine()).isValid()) { - line.setLineWidth(maxWidth); - line.naturalTextWidth(); - textHeight += line.height(); - } - layout.endLayout(); - - // Add one line for each additional information - textHeight += additionalRolesCount * option.fontMetrics.lineSpacing(); - - const qreal maxTextHeight = option.maxTextSize.height(); - if (maxTextHeight > 0 && textHeight > maxTextHeight) { - textHeight = maxTextHeight; - } - - return QSizeF(itemWidth, textHeight + option.iconSize + option.padding * 3); - } - - case KStandardItemListWidget::CompactLayout: { - // For each row exactly one role is shown. Calculate the maximum required width that is necessary - // to show all roles without horizontal clipping. - qreal maximumRequiredWidth = 0.0; - - const QList<QByteArray>& visibleRoles = view->visibleRoles(); - const bool showOnlyTextRole = (visibleRoles.count() == 1) && (visibleRoles.first() == "text"); - - if (showOnlyTextRole) { - maximumRequiredWidth = option.fontMetrics.width(itemText(index, view)); - } else { - const QHash<QByteArray, QVariant> values = view->model()->data(index); - foreach (const QByteArray& role, view->visibleRoles()) { - const QString text = roleText(role, values); - const qreal requiredWidth = option.fontMetrics.width(text); - maximumRequiredWidth = qMax(maximumRequiredWidth, requiredWidth); - } - } + case KStandardItemListWidget::IconsLayout: + calculateIconsLayoutItemSizeHints(sizeHints, view); + break; - qreal width = option.padding * 4 + option.iconSize + maximumRequiredWidth; - const qreal maxWidth = option.maxTextSize.width(); - if (maxWidth > 0 && width > maxWidth) { - width = maxWidth; - } - const qreal height = option.padding * 2 + qMax(option.iconSize, (1 + additionalRolesCount) * option.fontMetrics.lineSpacing()); - return QSizeF(width, height); - } + case KStandardItemListWidget::CompactLayout: + calculateCompactLayoutItemSizeHints(sizeHints, view); + break; - case KStandardItemListWidget::DetailsLayout: { - const qreal height = option.padding * 2 + qMax(option.iconSize, option.fontMetrics.height()); - return QSizeF(-1, height); - } + case KStandardItemListWidget::DetailsLayout: + calculateDetailsLayoutItemSizeHints(sizeHints, view); + break; default: Q_ASSERT(false); break; } - - return QSize(); } qreal KStandardItemListWidgetInformant::preferredRoleColumnWidth(const QByteArray& role, @@ -181,6 +122,108 @@ QString KStandardItemListWidgetInformant::roleText(const QByteArray& role, return values.value(role).toString(); } +void KStandardItemListWidgetInformant::calculateIconsLayoutItemSizeHints(QVector<QSizeF>& sizeHints, const KItemListView* view) const +{ + const KItemListStyleOption& option = view->styleOption(); + const QFont& font = option.font; + const int additionalRolesCount = qMax(view->visibleRoles().count() - 1, 0); + + const qreal itemWidth = view->itemSize().width(); + const qreal maxWidth = itemWidth - 2 * option.padding; + const qreal additionalRolesSpacing = additionalRolesCount * option.fontMetrics.lineSpacing(); + const qreal spacingAndIconHeight = option.iconSize + option.padding * 3; + + QTextOption textOption(Qt::AlignHCenter); + textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); + + for (int index = 0; index < sizeHints.count(); ++index) { + if (!sizeHints.at(index).isEmpty()) { + continue; + } + + const QString& text = KStringHandler::preProcessWrap(itemText(index, view)); + + // Calculate the number of lines required for wrapping the name + qreal textHeight = 0; + QTextLayout layout(text, font); + layout.setTextOption(textOption); + layout.beginLayout(); + QTextLine line; + int lineCount = 0; + while ((line = layout.createLine()).isValid()) { + line.setLineWidth(maxWidth); + line.naturalTextWidth(); + textHeight += line.height(); + + ++lineCount; + if (lineCount == option.maxTextLines) { + break; + } + } + layout.endLayout(); + + // Add one line for each additional information + textHeight += additionalRolesSpacing; + + sizeHints[index] = QSizeF(itemWidth, textHeight + spacingAndIconHeight); + } +} + +void KStandardItemListWidgetInformant::calculateCompactLayoutItemSizeHints(QVector<QSizeF>& sizeHints, const KItemListView* view) const +{ + const KItemListStyleOption& option = view->styleOption(); + const QFontMetrics& fontMetrics = option.fontMetrics; + const int additionalRolesCount = qMax(view->visibleRoles().count() - 1, 0); + + const QList<QByteArray>& visibleRoles = view->visibleRoles(); + const bool showOnlyTextRole = (visibleRoles.count() == 1) && (visibleRoles.first() == "text"); + const qreal maxWidth = option.maxTextWidth; + const qreal paddingAndIconWidth = option.padding * 4 + option.iconSize; + const qreal height = option.padding * 2 + qMax(option.iconSize, (1 + additionalRolesCount) * option.fontMetrics.lineSpacing()); + + for (int index = 0; index < sizeHints.count(); ++index) { + if (!sizeHints.at(index).isEmpty()) { + continue; + } + + // For each row exactly one role is shown. Calculate the maximum required width that is necessary + // to show all roles without horizontal clipping. + qreal maximumRequiredWidth = 0.0; + + if (showOnlyTextRole) { + maximumRequiredWidth = fontMetrics.width(itemText(index, view)); + } else { + const QHash<QByteArray, QVariant>& values = view->model()->data(index); + foreach (const QByteArray& role, visibleRoles) { + const QString& text = roleText(role, values); + const qreal requiredWidth = fontMetrics.width(text); + maximumRequiredWidth = qMax(maximumRequiredWidth, requiredWidth); + } + } + + qreal width = paddingAndIconWidth + maximumRequiredWidth; + if (maxWidth > 0 && width > maxWidth) { + width = maxWidth; + } + + sizeHints[index] = QSizeF(width, height); + } +} + +void KStandardItemListWidgetInformant::calculateDetailsLayoutItemSizeHints(QVector<QSizeF>& sizeHints, const KItemListView* view) const +{ + const KItemListStyleOption& option = view->styleOption(); + const qreal height = option.padding * 2 + qMax(option.iconSize, option.fontMetrics.height()); + + for (int index = 0; index < sizeHints.count(); ++index) { + if (!sizeHints.at(index).isEmpty()) { + continue; + } + + sizeHints[index] = QSizeF(-1, height); + } +} + KStandardItemListWidget::KStandardItemListWidget(KItemListWidgetInformant* informant, QGraphicsItem* parent) : KItemListWidget(informant, parent), m_isCut(false), @@ -1024,9 +1067,6 @@ void KStandardItemListWidget::updateIconsLayoutTextCache() qreal nameHeight = 0; QTextLine line; - const int additionalRolesCount = qMax(visibleRoles().count() - 1, 0); - const int maxNameLines = (option.maxTextSize.height() / int(lineSpacing)) - additionalRolesCount; - QTextLayout layout(nameTextInfo->staticText.text(), m_customizedFont); layout.setTextOption(nameTextInfo->staticText.textOption()); layout.beginLayout(); @@ -1037,7 +1077,7 @@ void KStandardItemListWidget::updateIconsLayoutTextCache() nameHeight += line.height(); ++nameLineIndex; - if (nameLineIndex == maxNameLines) { + if (nameLineIndex == option.maxTextLines) { // The maximum number of textlines has been reached. If this is // the case provide an elided text if necessary. const int textLength = line.textStart() + line.textLength(); @@ -1059,6 +1099,7 @@ void KStandardItemListWidget::updateIconsLayoutTextCache() layout.endLayout(); // Use one line for each additional information + const int additionalRolesCount = qMax(visibleRoles().count() - 1, 0); nameTextInfo->staticText.setTextWidth(maxWidth); nameTextInfo->pos = QPointF(padding, widgetHeight - nameHeight - diff --git a/src/kitemviews/kstandarditemlistwidget.h b/src/kitemviews/kstandarditemlistwidget.h index 7dd93b2b8..ca198c36b 100644 --- a/src/kitemviews/kstandarditemlistwidget.h +++ b/src/kitemviews/kstandarditemlistwidget.h @@ -38,7 +38,7 @@ public: KStandardItemListWidgetInformant(); virtual ~KStandardItemListWidgetInformant(); - virtual QSizeF itemSizeHint(int index, const KItemListView* view) const; + virtual void calculateItemSizeHints(QVector<QSizeF>& sizeHints, const KItemListView* view) const; virtual qreal preferredRoleColumnWidth(const QByteArray& role, int index, @@ -61,6 +61,10 @@ protected: virtual QString roleText(const QByteArray& role, const QHash<QByteArray, QVariant>& values) const; + void calculateIconsLayoutItemSizeHints(QVector<QSizeF>& sizeHints, const KItemListView* view) const; + void calculateCompactLayoutItemSizeHints(QVector<QSizeF>& sizeHints, const KItemListView* view) const; + void calculateDetailsLayoutItemSizeHints(QVector<QSizeF>& sizeHints, const KItemListView* view) const; + friend class KStandardItemListWidget; // Accesses roleText() }; diff --git a/src/kitemviews/private/kbaloorolesprovider.cpp b/src/kitemviews/private/kbaloorolesprovider.cpp new file mode 100644 index 000000000..c0ae0c544 --- /dev/null +++ b/src/kitemviews/private/kbaloorolesprovider.cpp @@ -0,0 +1,184 @@ +/*************************************************************************** + * Copyright (C) 2012 by Peter Penz <[email protected]> * + * Copyright (C) 2013 by Vishesh Handa <[email protected]> * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * + ***************************************************************************/ + +#include "kbaloorolesprovider.h" + +#include <KDebug> +#include <KGlobal> +#include <KLocale> + +#include <baloo/file.h> +#include <kfilemetadata/propertyinfo.h> + +#include <QTime> +#include <QMap> + +struct KBalooRolesProviderSingleton +{ + KBalooRolesProvider instance; +}; +K_GLOBAL_STATIC(KBalooRolesProviderSingleton, s_balooRolesProvider) + + +KBalooRolesProvider& KBalooRolesProvider::instance() +{ + return s_balooRolesProvider->instance; +} + +KBalooRolesProvider::~KBalooRolesProvider() +{ +} + +QSet<QByteArray> KBalooRolesProvider::roles() const +{ + return m_roles; +} + +QHash<QByteArray, QVariant> KBalooRolesProvider::roleValues(const Baloo::File& file, + const QSet<QByteArray>& roles) const +{ + QHash<QByteArray, QVariant> values; + + int width = -1; + int height = -1; + + QMapIterator<KFileMetaData::Property::Property, QVariant> it(file.properties()); + while (it.hasNext()) { + it.next(); + + const KFileMetaData::PropertyInfo pi(it.key()); + const QString property = pi.name(); + const QByteArray role = roleForProperty(property); + if (role.isEmpty() || !roles.contains(role)) { + continue; + } + + const QVariant value = it.value(); + + if (role == "imageSize") { + // Merge the two properties for width and height + // as one string into the "imageSize" role + if (property == QLatin1String("width")) { + width = value.toInt(); + } + else if (property == QLatin1String("height")) { + height = value.toInt(); + } + + if (width >= 0 && height >= 0) { + QString widthAndHeight = QString::number(width); + widthAndHeight += QLatin1String(" x "); + widthAndHeight += QString::number(height); + values.insert(role, widthAndHeight); + } + } else if (role == "orientation") { + const QString orientation = orientationFromValue(value.toInt()); + values.insert(role, orientation); + } else if (role == "duration") { + const QString duration = durationFromValue(value.toInt()); + values.insert(role, duration); + } else { + values.insert(role, value.toString()); + } + } + + if (roles.contains("tags")) { + values.insert("tags", tagsFromValues(file.tags())); + } + if (roles.contains("rating")) { + values.insert("rating", QString::number(file.rating())); + } + if (roles.contains("comment")) { + values.insert("comment", file.userComment()); + } + + return values; +} + +QByteArray KBalooRolesProvider::roleForProperty(const QString& property) const +{ + return m_roleForProperty.value(property); +} + +KBalooRolesProvider::KBalooRolesProvider() : + m_roles(), + m_roleForProperty() +{ + struct PropertyInfo + { + const char* const property; + const char* const role; + }; + + // Mapping from the URIs to the KFileItemModel roles. Note that this must not be + // a 1:1 mapping: One role may contain several URI-values (e.g. the URIs for height and + // width of an image are mapped to the role "imageSize") + static const PropertyInfo propertyInfoList[] = { + { "rating", "rating" }, + { "tag", "tags" }, + { "comment", "comment" }, + { "wordCount", "wordCount" }, + { "lineCount", "lineCount" }, + { "width", "imageSize" }, + { "height", "imageSize" }, + { "nexif.orientation", "orientation", }, + { "artist", "artist" }, + { "album", "album" }, + { "duration", "duration" }, + { "trackNumber", "track" } + // { "http://www.semanticdesktop.org/ontologies/2010/04/30/ndo#copiedFrom", "copiedFrom" } + }; + + for (unsigned int i = 0; i < sizeof(propertyInfoList) / sizeof(PropertyInfo); ++i) { + m_roleForProperty.insert(propertyInfoList[i].property, propertyInfoList[i].role); + m_roles.insert(propertyInfoList[i].role); + } +} + +QString KBalooRolesProvider::tagsFromValues(const QStringList& values) const +{ + return values.join(", "); +} + +QString KBalooRolesProvider::orientationFromValue(int value) const +{ + QString string; + switch (value) { + case 1: string = i18nc("@item:intable Image orientation", "Unchanged"); break; + case 2: string = i18nc("@item:intable Image orientation", "Horizontally flipped"); break; + case 3: string = i18nc("@item:intable image orientation", "180° rotated"); break; + case 4: string = i18nc("@item:intable image orientation", "Vertically flipped"); break; + case 5: string = i18nc("@item:intable image orientation", "Transposed"); break; + case 6: string = i18nc("@item:intable image orientation", "90° rotated"); break; + case 7: string = i18nc("@item:intable image orientation", "Transversed"); break; + case 8: string = i18nc("@item:intable image orientation", "270° rotated"); break; + default: + break; + } + return string; +} + +QString KBalooRolesProvider::durationFromValue(int value) const +{ + QTime duration; + duration = duration.addSecs(value); + return duration.toString("hh:mm:ss"); +} + diff --git a/src/kitemviews/private/knepomukrolesprovider.h b/src/kitemviews/private/kbaloorolesprovider.h index 68a4027e1..f1ad5c740 100644 --- a/src/kitemviews/private/knepomukrolesprovider.h +++ b/src/kitemviews/private/kbaloorolesprovider.h @@ -1,5 +1,6 @@ /*************************************************************************** * Copyright (C) 2012 by Peter Penz <[email protected]> * + * Copyright (C) 2013 by Vishesh Handa <[email protected]> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * @@ -17,8 +18,8 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************/ -#ifndef KNEPOMUKROLESPROVIDER_H -#define KNEPOMUKROLESPROVIDER_H +#ifndef KBALOO_ROLESPROVIDER_H +#define KBALOO_ROLESPROVIDER_H #include <libdolphin_export.h> @@ -26,25 +27,24 @@ #include <QSet> #include <QUrl> -namespace Nepomuk2 -{ - class Resource; +namespace Baloo { + class File; } /** * @brief Allows accessing metadata of a file by providing KFileItemModel roles. * * Is a helper class for KFileItemModelRolesUpdater to retrieve roles that - * are only accessible with Nepomuk. + * are only accessible with Baloo. */ -class LIBDOLPHINPRIVATE_EXPORT KNepomukRolesProvider +class LIBDOLPHINPRIVATE_EXPORT KBalooRolesProvider { public: - static KNepomukRolesProvider& instance(); - virtual ~KNepomukRolesProvider(); + static KBalooRolesProvider& instance(); + virtual ~KBalooRolesProvider(); /** - * @return Roles that can be provided by KNepomukRolesProvider. + * @return Roles that can be provided by KBalooRolesProvider. */ QSet<QByteArray> roles() const; @@ -52,13 +52,13 @@ public: * @return Values for the roles \a roles that can be determined from the file * with the URL \a url. */ - QHash<QByteArray, QVariant> roleValues(const Nepomuk2::Resource& resource, + QHash<QByteArray, QVariant> roleValues(const Baloo::File& file, const QSet<QByteArray>& roles) const; - QByteArray roleForPropertyUri(const QUrl& uri) const; + QByteArray roleForProperty(const QString& property) const; protected: - KNepomukRolesProvider(); + KBalooRolesProvider(); private: /** @@ -81,9 +81,9 @@ private: private: QSet<QByteArray> m_roles; - QHash<QUrl, QByteArray> m_roleForUri; + QHash<QString, QByteArray> m_roleForProperty; - friend class KNepomukRolesProviderSingleton; + friend class KBalooRolesProviderSingleton; }; #endif diff --git a/src/kitemviews/private/kdirectorycontentscounter.cpp b/src/kitemviews/private/kdirectorycontentscounter.cpp index fd8479feb..65afb7c3e 100644 --- a/src/kitemviews/private/kdirectorycontentscounter.cpp +++ b/src/kitemviews/private/kdirectorycontentscounter.cpp @@ -30,7 +30,6 @@ KDirectoryContentsCounter::KDirectoryContentsCounter(KFileItemModel* model, QObj QObject(parent), m_model(model), m_queue(), - m_workerThread(0), m_worker(0), m_workerIsBusy(false), m_dirWatcher(0), @@ -39,25 +38,34 @@ KDirectoryContentsCounter::KDirectoryContentsCounter(KFileItemModel* model, QObj connect(m_model, SIGNAL(itemsRemoved(KItemRangeList)), this, SLOT(slotItemsRemoved())); - m_workerThread = new QThread(this); + if (!m_workerThread) { + m_workerThread = new QThread(); + m_workerThread->start(); + } + m_worker = new KDirectoryContentsCounterWorker(); m_worker->moveToThread(m_workerThread); + ++m_workersCount; connect(this, SIGNAL(requestDirectoryContentsCount(QString,KDirectoryContentsCounterWorker::Options)), m_worker, SLOT(countDirectoryContents(QString,KDirectoryContentsCounterWorker::Options))); connect(m_worker, SIGNAL(result(QString,int)), this, SLOT(slotResult(QString,int))); - m_workerThread->start(); - m_dirWatcher = new KDirWatch(this); connect(m_dirWatcher, SIGNAL(dirty(QString)), this, SLOT(slotDirWatchDirty(QString))); } KDirectoryContentsCounter::~KDirectoryContentsCounter() { - m_workerThread->quit(); - m_workerThread->wait(); + --m_workersCount; + + if (m_workersCount == 0) { + m_workerThread->quit(); + m_workerThread->wait(); + delete m_workerThread; + m_workerThread = 0; + } delete m_worker; } @@ -162,3 +170,6 @@ void KDirectoryContentsCounter::startWorker(const QString& path) m_workerIsBusy = true; } } + +QThread* KDirectoryContentsCounter::m_workerThread = 0; +int KDirectoryContentsCounter::m_workersCount = 0;
\ No newline at end of file diff --git a/src/kitemviews/private/kdirectorycontentscounter.h b/src/kitemviews/private/kdirectorycontentscounter.h index 425c3632a..c03d0249c 100644 --- a/src/kitemviews/private/kdirectorycontentscounter.h +++ b/src/kitemviews/private/kdirectorycontentscounter.h @@ -78,7 +78,9 @@ private: QQueue<QString> m_queue; - QThread* m_workerThread; + static QThread* m_workerThread; + static int m_workersCount; + KDirectoryContentsCounterWorker* m_worker; bool m_workerIsBusy; diff --git a/src/kitemviews/private/kitemlistheaderwidget.cpp b/src/kitemviews/private/kitemlistheaderwidget.cpp index b55ba1eb5..1f210ab5a 100644 --- a/src/kitemviews/private/kitemlistheaderwidget.cpp +++ b/src/kitemviews/private/kitemlistheaderwidget.cpp @@ -327,6 +327,22 @@ void KItemListHeaderWidget::mouseMoveEvent(QGraphicsSceneMouseEvent* event) } } +void KItemListHeaderWidget::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) +{ + QGraphicsItem::mouseDoubleClickEvent(event); + + const int roleIndex = roleIndexAt(event->pos()); + if (roleIndex >= 0 && isAboveRoleGrip(event->pos(), roleIndex)) { + const QByteArray role = m_columns.at(roleIndex); + + qreal previousWidth = columnWidth(role); + setColumnWidth(role, preferredColumnWidth(role)); + qreal currentWidth = columnWidth(role); + + emit columnWidthChanged(role, currentWidth, previousWidth); + } +} + void KItemListHeaderWidget::hoverEnterEvent(QGraphicsSceneHoverEvent* event) { QGraphicsWidget::hoverEnterEvent(event); diff --git a/src/kitemviews/private/kitemlistheaderwidget.h b/src/kitemviews/private/kitemlistheaderwidget.h index f8bba977b..b99f45f35 100644 --- a/src/kitemviews/private/kitemlistheaderwidget.h +++ b/src/kitemviews/private/kitemlistheaderwidget.h @@ -100,6 +100,7 @@ protected: virtual void mousePressEvent(QGraphicsSceneMouseEvent* event); virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent* event); virtual void mouseMoveEvent(QGraphicsSceneMouseEvent* event); + virtual void mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event); virtual void hoverEnterEvent(QGraphicsSceneHoverEvent* event); virtual void hoverLeaveEvent(QGraphicsSceneHoverEvent* event); virtual void hoverMoveEvent(QGraphicsSceneHoverEvent* event); diff --git a/src/kitemviews/private/kitemlistsizehintresolver.cpp b/src/kitemviews/private/kitemlistsizehintresolver.cpp index 0e2286b45..029beddf9 100644 --- a/src/kitemviews/private/kitemlistsizehintresolver.cpp +++ b/src/kitemviews/private/kitemlistsizehintresolver.cpp @@ -23,7 +23,8 @@ KItemListSizeHintResolver::KItemListSizeHintResolver(const KItemListView* itemListView) : m_itemListView(itemListView), - m_sizeHintCache() + m_sizeHintCache(), + m_needsResolving(false) { } @@ -31,14 +32,10 @@ KItemListSizeHintResolver::~KItemListSizeHintResolver() { } -QSizeF KItemListSizeHintResolver::sizeHint(int index) const +QSizeF KItemListSizeHintResolver::sizeHint(int index) { - QSizeF size = m_sizeHintCache.at(index); - if (size.isEmpty()) { - size = m_itemListView->itemSizeHint(index); - m_sizeHintCache[index] = size; - } - return size; + updateCache(); + return m_sizeHintCache.at(index); } void KItemListSizeHintResolver::itemsInserted(const KItemRangeList& itemRanges) @@ -77,6 +74,8 @@ void KItemListSizeHintResolver::itemsInserted(const KItemRangeList& itemRanges) } } + m_needsResolving = true; + Q_ASSERT(m_sizeHintCache.count() == m_itemListView->model()->count()); } @@ -135,9 +134,20 @@ void KItemListSizeHintResolver::itemsChanged(int index, int count, const QSet<QB ++index; --count; } + + m_needsResolving = true; } void KItemListSizeHintResolver::clearCache() { m_sizeHintCache.fill(QSizeF()); + m_needsResolving = true; +} + +void KItemListSizeHintResolver::updateCache() +{ + if (m_needsResolving) { + m_itemListView->calculateItemSizeHints(m_sizeHintCache); + m_needsResolving = false; + } } diff --git a/src/kitemviews/private/kitemlistsizehintresolver.h b/src/kitemviews/private/kitemlistsizehintresolver.h index 486f9b631..86580bf7b 100644 --- a/src/kitemviews/private/kitemlistsizehintresolver.h +++ b/src/kitemviews/private/kitemlistsizehintresolver.h @@ -36,7 +36,7 @@ class LIBDOLPHINPRIVATE_EXPORT KItemListSizeHintResolver public: KItemListSizeHintResolver(const KItemListView* itemListView); virtual ~KItemListSizeHintResolver(); - QSizeF sizeHint(int index) const; + QSizeF sizeHint(int index); void itemsInserted(const KItemRangeList& itemRanges); void itemsRemoved(const KItemRangeList& itemRanges); @@ -44,10 +44,12 @@ public: void itemsChanged(int index, int count, const QSet<QByteArray>& roles); void clearCache(); + void updateCache(); private: const KItemListView* m_itemListView; mutable QVector<QSizeF> m_sizeHintCache; + bool m_needsResolving; }; #endif diff --git a/src/kitemviews/private/kitemlistviewlayouter.cpp b/src/kitemviews/private/kitemlistviewlayouter.cpp index f5f63d5ab..9da5384d4 100644 --- a/src/kitemviews/private/kitemlistviewlayouter.cpp +++ b/src/kitemviews/private/kitemlistviewlayouter.cpp @@ -26,7 +26,7 @@ // #define KITEMLISTVIEWLAYOUTER_DEBUG -KItemListViewLayouter::KItemListViewLayouter(QObject* parent) : +KItemListViewLayouter::KItemListViewLayouter(KItemListSizeHintResolver* sizeHintResolver, QObject* parent) : QObject(parent), m_dirty(true), m_visibleIndexesDirty(true), @@ -36,7 +36,7 @@ KItemListViewLayouter::KItemListViewLayouter(QObject* parent) : m_itemMargin(), m_headerHeight(0), m_model(0), - m_sizeHintResolver(0), + m_sizeHintResolver(sizeHintResolver), m_scrollOffset(0), m_maximumScrollOffset(0), m_itemOffset(0), @@ -46,11 +46,14 @@ KItemListViewLayouter::KItemListViewLayouter(QObject* parent) : m_columnWidth(0), m_xPosInc(0), m_columnCount(0), + m_rowOffsets(), + m_columnOffsets(), m_groupItemIndexes(), m_groupHeaderHeight(0), m_groupHeaderMargin(0), m_itemInfos() { + Q_ASSERT(m_sizeHintResolver); } KItemListViewLayouter::~KItemListViewLayouter() @@ -207,19 +210,6 @@ const KItemModelBase* KItemListViewLayouter::model() const return m_model; } -void KItemListViewLayouter::setSizeHintResolver(const KItemListSizeHintResolver* sizeHintResolver) -{ - if (m_sizeHintResolver != sizeHintResolver) { - m_sizeHintResolver = sizeHintResolver; - m_dirty = true; - } -} - -const KItemListSizeHintResolver* KItemListViewLayouter::sizeHintResolver() const -{ - return m_sizeHintResolver; -} - int KItemListViewLayouter::firstVisibleIndex() const { const_cast<KItemListViewLayouter*>(this)->doLayout(); @@ -239,18 +229,15 @@ QRectF KItemListViewLayouter::itemRect(int index) const return QRectF(); } - QSizeF sizeHint; - if (m_sizeHintResolver) { - sizeHint = m_sizeHintResolver->sizeHint(index); - } else { - sizeHint = m_itemSize; - } + QSizeF sizeHint = m_sizeHintResolver->sizeHint(index); + + const qreal x = m_columnOffsets.at(m_itemInfos.at(index).column); + const qreal y = m_rowOffsets.at(m_itemInfos.at(index).row); if (m_scrollOrientation == Qt::Horizontal) { // Rotate the logical direction which is always vertical by 90° // to get the physical horizontal direction - const QPointF logicalPos = m_itemInfos[index].pos; - QPointF pos(logicalPos.y(), logicalPos.x()); + QPointF pos(y, x); pos.rx() -= m_scrollOffset; return QRectF(pos, sizeHint); } @@ -260,8 +247,7 @@ QRectF KItemListViewLayouter::itemRect(int index) const sizeHint.rwidth() = m_itemSize.width(); } - QPointF pos = m_itemInfos[index].pos; - pos -= QPointF(m_itemOffset, m_scrollOffset); + const QPointF pos(x - m_itemOffset, y - m_scrollOffset); return QRectF(pos, sizeHint); } @@ -284,25 +270,19 @@ QRectF KItemListViewLayouter::groupHeaderRect(int index) const pos.rx() -= m_itemMargin.width(); pos.ry() = 0; - // Determine the maximum width used in the - // current column. As the scroll-direction is - // Qt::Horizontal and m_itemRects is accessed directly, - // the logical height represents the visual width. + // Determine the maximum width used in the current column. As the + // scroll-direction is Qt::Horizontal and m_itemRects is accessed + // directly, the logical height represents the visual width, and + // the logical row represents the column. qreal headerWidth = minimumGroupHeaderWidth(); - const qreal y = m_itemInfos[index].pos.y(); + const int row = m_itemInfos[index].row; const int maxIndex = m_itemInfos.count() - 1; while (index <= maxIndex) { - const QPointF pos = m_itemInfos[index].pos; - if (pos.y() != y) { + if (m_itemInfos[index].row != row) { break; } - qreal itemWidth; - if (m_sizeHintResolver) { - itemWidth = m_sizeHintResolver->sizeHint(index).width(); - } else { - itemWidth = m_itemSize.width(); - } + const qreal itemWidth = m_sizeHintResolver->sizeHint(index).width(); if (itemWidth > headerWidth) { headerWidth = itemWidth; @@ -422,21 +402,40 @@ void KItemListViewLayouter::doLayout() m_itemInfos.resize(itemCount); + // Calculate the offset of each column, i.e., the x-coordinate where the column starts. + m_columnOffsets.resize(m_columnCount); + qreal currentOffset = m_xPosInc; + + if (grouped && horizontalScrolling) { + // All group headers will always be aligned on the top and not + // flipped like the other properties. + currentOffset += m_groupHeaderHeight; + } + + for (int column = 0; column < m_columnCount; ++column) { + m_columnOffsets[column] = currentOffset; + currentOffset += m_columnWidth; + } + + // Prepare the QVector which stores the y-coordinate for each new row. + int numberOfRows = (itemCount + m_columnCount - 1) / m_columnCount; + if (grouped && m_columnCount > 1) { + // In the worst case, a new row will be started for every group. + // We could calculate the exact number of rows now to prevent that we reserve + // too much memory, but the code required to do that might need much more + // memory than it would save in the average case. + numberOfRows += m_groupItemIndexes.count(); + } + m_rowOffsets.resize(numberOfRows); + qreal y = m_headerHeight + itemMargin.height(); int row = 0; int index = 0; while (index < itemCount) { - qreal x = m_xPosInc; qreal maxItemHeight = itemSize.height(); if (grouped) { - if (horizontalScrolling) { - // All group headers will always be aligned on the top and not - // flipped like the other properties - x += m_groupHeaderHeight; - } - if (m_groupItemIndexes.contains(index)) { // The item is the first item of a group. // Increase the y-position to provide space @@ -456,19 +455,18 @@ void KItemListViewLayouter::doLayout() } } + m_rowOffsets[row] = y; + int column = 0; while (index < itemCount && column < m_columnCount) { qreal requiredItemHeight = itemSize.height(); - if (m_sizeHintResolver) { - const QSizeF sizeHint = m_sizeHintResolver->sizeHint(index); - const qreal sizeHintHeight = horizontalScrolling ? sizeHint.width() : sizeHint.height(); - if (sizeHintHeight > requiredItemHeight) { - requiredItemHeight = sizeHintHeight; - } + const QSizeF sizeHint = m_sizeHintResolver->sizeHint(index); + const qreal sizeHintHeight = horizontalScrolling ? sizeHint.width() : sizeHint.height(); + if (sizeHintHeight > requiredItemHeight) { + requiredItemHeight = sizeHintHeight; } ItemInfo& itemInfo = m_itemInfos[index]; - itemInfo.pos = QPointF(x, y); itemInfo.column = column; itemInfo.row = row; @@ -492,7 +490,6 @@ void KItemListViewLayouter::doLayout() } maxItemHeight = qMax(maxItemHeight, requiredItemHeight); - x += m_columnWidth; ++index; ++column; @@ -547,7 +544,7 @@ void KItemListViewLayouter::updateVisibleIndexes() int mid = 0; do { mid = (min + max) / 2; - if (m_itemInfos[mid].pos.y() < m_scrollOffset) { + if (m_rowOffsets.at(m_itemInfos[mid].row) < m_scrollOffset) { min = mid + 1; } else { max = mid - 1; @@ -557,13 +554,13 @@ void KItemListViewLayouter::updateVisibleIndexes() if (mid > 0) { // Include the row before the first fully visible index, as it might // be partly visible - if (m_itemInfos[mid].pos.y() >= m_scrollOffset) { + if (m_rowOffsets.at(m_itemInfos[mid].row) >= m_scrollOffset) { --mid; - Q_ASSERT(m_itemInfos[mid].pos.y() < m_scrollOffset); + Q_ASSERT(m_rowOffsets.at(m_itemInfos[mid].row) < m_scrollOffset); } - const qreal rowTop = m_itemInfos[mid].pos.y(); - while (mid > 0 && m_itemInfos[mid - 1].pos.y() == rowTop) { + const int firstVisibleRow = m_itemInfos[mid].row; + while (mid > 0 && m_itemInfos[mid - 1].row == firstVisibleRow) { --mid; } } @@ -580,14 +577,14 @@ void KItemListViewLayouter::updateVisibleIndexes() max = maxIndex; do { mid = (min + max) / 2; - if (m_itemInfos[mid].pos.y() <= bottom) { + if (m_rowOffsets.at(m_itemInfos[mid].row) <= bottom) { min = mid + 1; } else { max = mid - 1; } } while (min <= max); - while (mid > 0 && m_itemInfos[mid].pos.y() > bottom) { + while (mid > 0 && m_rowOffsets.at(m_itemInfos[mid].row) > bottom) { --mid; } m_lastVisibleIndex = mid; diff --git a/src/kitemviews/private/kitemlistviewlayouter.h b/src/kitemviews/private/kitemlistviewlayouter.h index a3b0893a1..0efcab12b 100644 --- a/src/kitemviews/private/kitemlistviewlayouter.h +++ b/src/kitemviews/private/kitemlistviewlayouter.h @@ -50,7 +50,7 @@ class LIBDOLPHINPRIVATE_EXPORT KItemListViewLayouter : public QObject Q_OBJECT public: - KItemListViewLayouter(QObject* parent = 0); + KItemListViewLayouter(KItemListSizeHintResolver* sizeHintResolver, QObject* parent = 0); virtual ~KItemListViewLayouter(); void setScrollOrientation(Qt::Orientation orientation); @@ -103,9 +103,6 @@ public: void setModel(const KItemModelBase* model); const KItemModelBase* model() const; - void setSizeHintResolver(const KItemListSizeHintResolver* sizeHintResolver); - const KItemListSizeHintResolver* sizeHintResolver() const; - /** * @return The first (at least partly) visible index. -1 is returned * if the item count is 0. @@ -205,7 +202,7 @@ private: QSizeF m_itemMargin; qreal m_headerHeight; const KItemModelBase* m_model; - const KItemListSizeHintResolver* m_sizeHintResolver; + KItemListSizeHintResolver* m_sizeHintResolver; qreal m_scrollOffset; qreal m_maximumScrollOffset; @@ -220,6 +217,9 @@ private: qreal m_xPosInc; int m_columnCount; + QVector<qreal> m_rowOffsets; + QVector<qreal> m_columnOffsets; + // Stores all item indexes that are the first item of a group. // Assures fast access for KItemListViewLayouter::isFirstGroupItem(). QSet<int> m_groupItemIndexes; @@ -227,7 +227,6 @@ private: qreal m_groupHeaderMargin; struct ItemInfo { - QPointF pos; int column; int row; }; diff --git a/src/kitemviews/private/knepomukrolesprovider.cpp b/src/kitemviews/private/knepomukrolesprovider.cpp deleted file mode 100644 index e237f948f..000000000 --- a/src/kitemviews/private/knepomukrolesprovider.cpp +++ /dev/null @@ -1,201 +0,0 @@ -/*************************************************************************** - * Copyright (C) 2012 by Peter Penz <[email protected]> * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU General Public License for more details. * - * * - * You should have received a copy of the GNU General Public License * - * along with this program; if not, write to the * - * Free Software Foundation, Inc., * - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * - ***************************************************************************/ - -#include "knepomukrolesprovider.h" - -#include <KDebug> -#include <KGlobal> -#include <KLocale> - -#include <Nepomuk2/Resource> -#include <Nepomuk2/Tag> -#include <Nepomuk2/Types/Property> -#include <Nepomuk2/Variant> - -#include <QTime> - -struct KNepomukRolesProviderSingleton -{ - KNepomukRolesProvider instance; -}; -K_GLOBAL_STATIC(KNepomukRolesProviderSingleton, s_nepomukRolesProvider) - - -KNepomukRolesProvider& KNepomukRolesProvider::instance() -{ - return s_nepomukRolesProvider->instance; -} - -KNepomukRolesProvider::~KNepomukRolesProvider() -{ -} - -QSet<QByteArray> KNepomukRolesProvider::roles() const -{ - return m_roles; -} - -QHash<QByteArray, QVariant> KNepomukRolesProvider::roleValues(const Nepomuk2::Resource& resource, - const QSet<QByteArray>& roles) const -{ - if (!resource.isValid()) { - return QHash<QByteArray, QVariant>(); - } - - QHash<QByteArray, QVariant> values; - - int width = -1; - int height = -1; - - QHashIterator<QUrl, Nepomuk2::Variant> it(resource.properties()); - while (it.hasNext()) { - it.next(); - - const Nepomuk2::Types::Property property = it.key(); - const QByteArray role = roleForPropertyUri(property.uri()); - if (role.isEmpty() || !roles.contains(role)) { - continue; - } - - const Nepomuk2::Variant value = it.value(); - - if (role == "imageSize") { - // Merge the two Nepomuk properties for width and height - // as one string into the "imageSize" role - const QString uri = property.uri().toString(); - if (uri.endsWith(QLatin1String("#width"))) { - width = value.toInt(); - } else if (uri.endsWith(QLatin1String("#height"))) { - height = value.toInt(); - } - - if (width >= 0 && height >= 0) { - const QString widthAndHeight = QString::number(width) + - QLatin1String(" x ") + - QString::number(height); - values.insert(role, widthAndHeight); - } - } else if (role == "tags") { - const QString tags = tagsFromValues(value.toStringList()); - values.insert(role, tags); - } else if (role == "orientation") { - const QString orientation = orientationFromValue(value.toInt()); - values.insert(role, orientation); - } else if (role == "duration") { - const QString duration = durationFromValue(value.toInt()); - values.insert(role, duration); - } else if (value.isResource()) { - const Nepomuk2::Resource resource = value.toResource(); - values.insert(role, resource.genericLabel()); - } else if (value.isResourceList()) { - const QList<Nepomuk2::Resource> resList = value.toResourceList(); - QStringList strList; - foreach (const Nepomuk2::Resource& res, resList) { - strList << res.genericLabel(); - } - values.insert(role, strList.join(QLatin1String(", "))); - } else { - values.insert(role, value.toString()); - } - } - - return values; -} - -QByteArray KNepomukRolesProvider::roleForPropertyUri(const QUrl& uri) const -{ - return m_roleForUri.value(uri); -} - -KNepomukRolesProvider::KNepomukRolesProvider() : - m_roles(), - m_roleForUri() -{ - struct UriInfo - { - const char* const uri; - const char* const role; - }; - - // Mapping from the URIs to the KFileItemModel roles. Note that this must not be - // a 1:1 mapping: One role may contain several URI-values (e.g. the URIs for height and - // width of an image are mapped to the role "imageSize") - static const UriInfo uriInfoList[] = { - { "http://www.semanticdesktop.org/ontologies/2007/08/15/nao#numericRating", "rating" }, - { "http://www.semanticdesktop.org/ontologies/2007/08/15/nao#hasTag", "tags" }, - { "http://www.semanticdesktop.org/ontologies/2007/08/15/nao#description", "comment" }, - { "http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#wordCount", "wordCount" }, - { "http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#lineCount", "lineCount" }, - { "http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#width", "imageSize" }, - { "http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#height", "imageSize" }, - { "http://www.semanticdesktop.org/ontologies/2007/05/10/nexif#orientation", "orientation", }, - { "http://www.semanticdesktop.org/ontologies/2009/02/19/nmm#performer", "artist" }, - { "http://www.semanticdesktop.org/ontologies/2009/02/19/nmm#musicAlbum", "album" }, - { "http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#duration", "duration" }, - { "http://www.semanticdesktop.org/ontologies/2009/02/19/nmm#trackNumber", "track" }, - { "http://www.semanticdesktop.org/ontologies/2010/04/30/ndo#copiedFrom", "copiedFrom" } - }; - - for (unsigned int i = 0; i < sizeof(uriInfoList) / sizeof(UriInfo); ++i) { - m_roleForUri.insert(QUrl(uriInfoList[i].uri), uriInfoList[i].role); - m_roles.insert(uriInfoList[i].role); - } -} - -QString KNepomukRolesProvider::tagsFromValues(const QStringList& values) const -{ - QString tags; - - for (int i = 0; i < values.count(); ++i) { - if (i > 0) { - tags.append(QLatin1String(", ")); - } - - const Nepomuk2::Tag tag(values[i]); - tags += tag.genericLabel(); - } - - return tags; -} - -QString KNepomukRolesProvider::orientationFromValue(int value) const -{ - QString string; - switch (value) { - case 1: string = i18nc("@item:intable Image orientation", "Unchanged"); break; - case 2: string = i18nc("@item:intable Image orientation", "Horizontally flipped"); break; - case 3: string = i18nc("@item:intable image orientation", "180° rotated"); break; - case 4: string = i18nc("@item:intable image orientation", "Vertically flipped"); break; - case 5: string = i18nc("@item:intable image orientation", "Transposed"); break; - case 6: string = i18nc("@item:intable image orientation", "90° rotated"); break; - case 7: string = i18nc("@item:intable image orientation", "Transversed"); break; - case 8: string = i18nc("@item:intable image orientation", "270° rotated"); break; - default: - break; - } - return string; -} - -QString KNepomukRolesProvider::durationFromValue(int value) const -{ - QTime duration; - duration = duration.addSecs(value); - return duration.toString("hh:mm:ss"); -} - |
