]> cloud.milkyroute.net Git - dolphin.git/blobdiff - src/kitemviews/kfileitemmodelrolesupdater.cpp
Merge remote-tracking branch 'origin/KDE/4.9'
[dolphin.git] / src / kitemviews / kfileitemmodelrolesupdater.cpp
index 942db2bbd9fe306d71795354cbc243b34f940bc4..ae935819272a4ea1925bbd40718fd26e2734665a 100644 (file)
 #include <KConfig>
 #include <KConfigGroup>
 #include <KDebug>
+#include <KDirWatch>
 #include <KFileItem>
 #include <KGlobal>
+#include <KIO/JobUiDelegate>
 #include <KIO/PreviewJob>
 
 #include "private/kpixmapmodifier.h"
 
+#include <QApplication>
 #include <QPainter>
 #include <QPixmap>
 #include <QElapsedTimer>
@@ -37,7 +40,7 @@
 
 #ifdef HAVE_NEPOMUK
     #include "private/knepomukrolesprovider.h"
-    #include "private/knepomukresourcewatcher.h"
+    #include <Nepomuk2/ResourceWatcher>
 #endif
 
 // Required includes for subItemsCount():
@@ -82,12 +85,13 @@ KFileItemModelRolesUpdater::KFileItemModelRolesUpdater(KFileItemModel* model, QO
     m_pendingInvisibleItems(),
     m_previewJobs(),
     m_changedItemsTimer(0),
-    m_changedItems()
+    m_changedItems(),
+    m_dirWatcher(0),
+    m_watchedDirs()
   #ifdef HAVE_NEPOMUK
   , m_nepomukResourceWatcher(0),
     m_nepomukUriItems()
   #endif
-
 {
     Q_ASSERT(model);
 
@@ -119,10 +123,16 @@ KFileItemModelRolesUpdater::KFileItemModelRolesUpdater(KFileItemModel* model, QO
 #ifdef HAVE_NEPOMUK
     m_resolvableRoles += KNepomukRolesProvider::instance().roles();
 #endif
+
+    // When folders are expandable or the item-count is shown for folders, it is necessary
+    // to watch the number of items of the sub-folder to be able to react on changes.
+    m_dirWatcher = new KDirWatch(this);
+    connect(m_dirWatcher, SIGNAL(dirty(QString)), this, SLOT(slotDirWatchDirty(QString)));
 }
 
 KFileItemModelRolesUpdater::~KFileItemModelRolesUpdater()
 {
+    resetPendingRoles();
 }
 
 void KFileItemModelRolesUpdater::setIconSize(const QSize& size)
@@ -204,7 +214,7 @@ bool KFileItemModelRolesUpdater::enlargeSmallPreviews() const
 
 void KFileItemModelRolesUpdater::setEnabledPlugins(const QStringList& list)
 {
-    if (m_enabledPlugins == list) {
+    if (m_enabledPlugins != list) {
         m_enabledPlugins = list;
         if (m_previewShown) {
             updateAllPreviews();
@@ -266,15 +276,15 @@ void KFileItemModelRolesUpdater::setRoles(const QSet<QByteArray>& roles)
         if (hasNepomukRole && !m_nepomukResourceWatcher) {
             Q_ASSERT(m_nepomukUriItems.isEmpty());
 
-            m_nepomukResourceWatcher = new Nepomuk::ResourceWatcher(this);
-            connect(m_nepomukResourceWatcher, SIGNAL(propertyChanged(Nepomuk::Resource,Nepomuk::Types::Property,QVariantList,QVariantList)),
-                    this, SLOT(applyChangedNepomukRoles(Nepomuk::Resource)));
-            connect(m_nepomukResourceWatcher, SIGNAL(propertyRemoved(Nepomuk::Resource,Nepomuk::Types::Property,QVariant)),
-                    this, SLOT(applyChangedNepomukRoles(Nepomuk::Resource)));
-            connect(m_nepomukResourceWatcher, SIGNAL(propertyAdded(Nepomuk::Resource,Nepomuk::Types::Property,QVariant)),
-                    this, SLOT(applyChangedNepomukRoles(Nepomuk::Resource)));
-            connect(m_nepomukResourceWatcher, SIGNAL(resourceCreated(Nepomuk::Resource,QList<QUrl>)),
-                    this, SLOT(applyChangedNepomukRoles(Nepomuk::Resource)));
+            m_nepomukResourceWatcher = new Nepomuk2::ResourceWatcher(this);
+            connect(m_nepomukResourceWatcher, SIGNAL(propertyChanged(Nepomuk2::Resource,Nepomuk2::Types::Property,QVariantList,QVariantList)),
+                    this, SLOT(applyChangedNepomukRoles(Nepomuk2::Resource)));
+            connect(m_nepomukResourceWatcher, SIGNAL(propertyRemoved(Nepomuk2::Resource,Nepomuk2::Types::Property,QVariant)),
+                    this, SLOT(applyChangedNepomukRoles(Nepomuk2::Resource)));
+            connect(m_nepomukResourceWatcher, SIGNAL(propertyAdded(Nepomuk2::Resource,Nepomuk2::Types::Property,QVariant)),
+                    this, SLOT(applyChangedNepomukRoles(Nepomuk2::Resource)));
+            connect(m_nepomukResourceWatcher, SIGNAL(resourceCreated(Nepomuk2::Resource,QList<QUrl>)),
+                    this, SLOT(applyChangedNepomukRoles(Nepomuk2::Resource)));
         } else if (!hasNepomukRole && m_nepomukResourceWatcher) {
             delete m_nepomukResourceWatcher;
             m_nepomukResourceWatcher = 0;
@@ -316,17 +326,39 @@ void KFileItemModelRolesUpdater::slotItemsRemoved(const KItemRangeList& itemRang
 {
     Q_UNUSED(itemRanges);
 
+    const bool allItemsRemoved = (m_model->count() == 0);
+
+    if (!m_watchedDirs.isEmpty()) {
+        // Don't let KDirWatch watch for removed items
+        if (allItemsRemoved) {
+            foreach (const QString& path, m_watchedDirs) {
+                m_dirWatcher->removeDir(path);
+            }
+            m_watchedDirs.clear();
+        } else {
+            QMutableSetIterator<QString> it(m_watchedDirs);
+            while (it.hasNext()) {
+                const QString& path = it.next();
+                if (m_model->index(KUrl(path)) < 0) {
+                    m_dirWatcher->removeDir(path);
+                    it.remove();
+                }
+            }
+        }
+    }
+
 #ifdef HAVE_NEPOMUK
     if (m_nepomukResourceWatcher) {
         // Don't let the ResourceWatcher watch for removed items
-        if (m_model->count() == 0) {
-            m_nepomukResourceWatcher->setResources(QList<Nepomuk::Resource>());
+        if (allItemsRemoved) {
+            m_nepomukResourceWatcher->setResources(QList<Nepomuk2::Resource>());
+            m_nepomukResourceWatcher->stop();
             m_nepomukUriItems.clear();
         } else {
-            QList<Nepomuk::Resource> newResources;
-            const QList<Nepomuk::Resource> oldResources = m_nepomukResourceWatcher->resources();
-            foreach (const Nepomuk::Resource& resource, oldResources) {
-                const QUrl uri = resource.resourceUri();
+            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);
                 if (m_model->index(itemUrl) >= 0) {
                     newResources.append(resource);
@@ -335,6 +367,10 @@ void KFileItemModelRolesUpdater::slotItemsRemoved(const KItemRangeList& itemRang
                 }
             }
             m_nepomukResourceWatcher->setResources(newResources);
+            if (newResources.isEmpty()) {
+                Q_ASSERT(m_nepomukUriItems.isEmpty());
+                m_nepomukResourceWatcher->stop();
+            }
         }
     }
 #endif
@@ -345,7 +381,7 @@ void KFileItemModelRolesUpdater::slotItemsRemoved(const KItemRangeList& itemRang
         return;
     }
 
-    if (m_model->count() == 0) {
+    if (allItemsRemoved) {
         // Most probably a directory change is done. Clear all pending items
         // and also kill all ongoing preview-jobs.
         resetPendingRoles();
@@ -505,11 +541,10 @@ void KFileItemModelRolesUpdater::resolveNextPendingRoles()
     bool changed = false;
     for (int i = 0; i <= 1; ++i) {
         QSet<KFileItem>& pendingItems = (i == 0) ? m_pendingVisibleItems : m_pendingInvisibleItems;
-        QSetIterator<KFileItem> it(pendingItems);
-        while (it.hasNext() && !changed && resolvedCount < MaxResolveItemsCount) {
-            const KFileItem item = it.next();
-            pendingItems.remove(item);
-            changed = applyResolvedRoles(item, ResolveAll);
+        QSet<KFileItem>::iterator it = pendingItems.begin();
+        while (it != pendingItems.end() && !changed && resolvedCount < MaxResolveItemsCount) {
+            changed = applyResolvedRoles(*it, ResolveAll);
+            it = pendingItems.erase(it);
             ++resolvedCount;
         }
     }
@@ -553,11 +588,18 @@ void KFileItemModelRolesUpdater::resolveChangedItems()
     startUpdating(itemRanges);
 }
 
-void KFileItemModelRolesUpdater::applyChangedNepomukRoles(const Nepomuk::Resource& resource)
+void KFileItemModelRolesUpdater::applyChangedNepomukRoles(const Nepomuk2::Resource& resource)
 {
 #ifdef HAVE_NEPOMUK
-    const KUrl itemUrl = m_nepomukUriItems.value(resource.resourceUri());
+    const KUrl itemUrl = m_nepomukUriItems.value(resource.uri());
     const KFileItem item = m_model->fileItem(itemUrl);
+
+    if (item.isNull()) {
+        // itemUrl is not in the model anymore, probably because
+        // the corresponding file has been deleted in the meantime.
+        return;
+    }
+
     QHash<QByteArray, QVariant> data = rolesData(item);
 
     const KNepomukRolesProvider& rolesProvider = KNepomukRolesProvider::instance();
@@ -574,8 +616,33 @@ void KFileItemModelRolesUpdater::applyChangedNepomukRoles(const Nepomuk::Resourc
     connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
             this,    SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
 #else
+#ifndef Q_CC_MSVC
     Q_UNUSED(resource);
 #endif
+#endif
+}
+
+void KFileItemModelRolesUpdater::slotDirWatchDirty(const QString& path)
+{
+    const bool getSizeRole = m_roles.contains("size");
+    const bool getIsExpandableRole = m_roles.contains("isExpandable");
+
+    if (getSizeRole || getIsExpandableRole) {
+        const int index = m_model->index(KUrl(path));
+        if (index >= 0) {
+            QHash<QByteArray, QVariant> data;
+
+            const int count = subItemsCount(path);
+            if (getSizeRole) {
+                data.insert("size", count);
+            }
+            if (getIsExpandableRole) {
+                data.insert("isExpandable", count > 0);
+            }
+
+            m_model->setData(index, data);
+        }
+    }
 }
 
 void KFileItemModelRolesUpdater::startUpdating(const KItemRangeList& itemRanges)
@@ -587,13 +654,15 @@ void KFileItemModelRolesUpdater::startUpdating(const KItemRangeList& itemRanges)
     if (hasValidIndexRange) {
         // Move all current pending visible items that are not visible anymore
         // to the pending invisible items.
-        QSetIterator<KFileItem> it(m_pendingVisibleItems);
-        while (it.hasNext()) {
-            const KFileItem item = it.next();
+        QSet<KFileItem>::iterator it = m_pendingVisibleItems.begin();
+        while (it != m_pendingVisibleItems.end()) {
+            const KFileItem item = *it;
             const int index = m_model->index(item);
             if (index < m_firstVisibleIndex || index > m_lastVisibleIndex) {
-                m_pendingVisibleItems.remove(item);
+                it = m_pendingVisibleItems.erase(it);
                 m_pendingInvisibleItems.insert(item);
+            } else {
+                ++it;
             }
         }
     }
@@ -640,11 +709,14 @@ void KFileItemModelRolesUpdater::startPreviewJob(const KFileItemList& items)
     // MIME-type in a fast way.
     QElapsedTimer timer;
     timer.start();
+
     KFileItemList itemSubSet;
-    for (int i = 0; i < items.count(); ++i) {
+    const int count = items.count();
+    itemSubSet.reserve(count);
+    for (int i = 0; i < count; ++i) {
         KFileItem item = items.at(i);
         item.determineMimeType();
-        itemSubSet.append(items.at(i));
+        itemSubSet.append(item);
         if (timer.elapsed() > MaxBlockTimeout) {
 #ifdef KFILEITEMMODELROLESUPDATER_DEBUG
             kDebug() << "Maximum time of" << MaxBlockTimeout << "ms exceeded, creating only previews for"
@@ -655,6 +727,9 @@ void KFileItemModelRolesUpdater::startPreviewJob(const KFileItemList& items)
     }
     KIO::PreviewJob* job = new KIO::PreviewJob(itemSubSet, cacheSize, &m_enabledPlugins);
     job->setIgnoreMaximumSize(items.first().isLocalFile());
+    if (job->ui()) {
+        job->ui()->setWindow(qApp->activeWindow());
+    }
 
     connect(job,  SIGNAL(gotPreview(KFileItem,QPixmap)),
             this, SLOT(slotGotPreview(KFileItem,QPixmap)));
@@ -696,13 +771,15 @@ void KFileItemModelRolesUpdater::resolvePendingRoles()
     timer.start();
 
     // Resolve the MIME type of all visible items
-    QSetIterator<KFileItem> visibleIt(m_pendingVisibleItems);
-    while (visibleIt.hasNext()) {
-        const KFileItem item = visibleIt.next();
+    QSet<KFileItem>::iterator visibleIt = m_pendingVisibleItems.begin();
+    while (visibleIt != m_pendingVisibleItems.end()) {
+        const KFileItem item = *visibleIt;
         if (!hasSlowRoles) {
             Q_ASSERT(!m_pendingInvisibleItems.contains(item));
             // All roles will be resolved by applyResolvedRoles()
-            m_pendingVisibleItems.remove(item);
+            visibleIt = m_pendingVisibleItems.erase(visibleIt);
+        } else {
+            ++visibleIt;
         }
         applyResolvedRoles(item, resolveHint);
         ++resolvedCount;
@@ -800,7 +877,8 @@ void KFileItemModelRolesUpdater::sortAndResolveAllRoles()
             m_pendingInvisibleItems.insert(item);
         }
     }
-    for (int i = m_lastVisibleIndex + 1; i < m_model->count(); ++i) {
+    const int count = m_model->count();
+    for (int i = m_lastVisibleIndex + 1; i < count; ++i) {
         const KFileItem item = m_model->fileItem(i);
         if (!item.isNull()) {
             m_pendingInvisibleItems.insert(item);
@@ -823,26 +901,42 @@ void KFileItemModelRolesUpdater::sortAndResolvePendingRoles()
 
     // Trigger a preview generation of all pending items. Assure that the visible
     // pending items get generated first.
-    QSet<KFileItem> pendingItems;
-    pendingItems += m_pendingVisibleItems;
-    pendingItems += m_pendingInvisibleItems;
 
-    resetPendingRoles();
-    Q_ASSERT(m_pendingVisibleItems.isEmpty());
-    Q_ASSERT(m_pendingInvisibleItems.isEmpty());
+    // Step 1: Check if any items in m_pendingVisibleItems are not visible any more
+    //         and move them to m_pendingInvisibleItems.
+    QSet<KFileItem>::iterator itVisible = m_pendingVisibleItems.begin();
+    while (itVisible != m_pendingVisibleItems.end()) {
+        const KFileItem item = *itVisible;
+        if (item.isNull()) {
+            itVisible = m_pendingVisibleItems.erase(itVisible);
+            continue;
+        }
 
-    QSetIterator<KFileItem> it(pendingItems);
-    while (it.hasNext()) {
-        const KFileItem item = it.next();
+        const int index = m_model->index(item);
+        if (!hasValidIndexRange || (index >= m_firstVisibleIndex && index <= m_lastVisibleIndex)) {
+            ++itVisible;
+        } else {
+            itVisible = m_pendingVisibleItems.erase(itVisible);
+            m_pendingInvisibleItems.insert(item);
+        }
+    }
+
+    // Step 2: Check if any items in m_pendingInvisibleItems have become visible
+    //         and move them to m_pendingVisibleItems.
+    QSet<KFileItem>::iterator itInvisible = m_pendingInvisibleItems.begin();
+    while (itInvisible != m_pendingInvisibleItems.end()) {
+        const KFileItem item = *itInvisible;
         if (item.isNull()) {
+            itInvisible = m_pendingInvisibleItems.erase(itInvisible);
             continue;
         }
 
         const int index = m_model->index(item);
         if (!hasValidIndexRange || (index >= m_firstVisibleIndex && index <= m_lastVisibleIndex)) {
+            itInvisible = m_pendingInvisibleItems.erase(itInvisible);
             m_pendingVisibleItems.insert(item);
         } else {
-            m_pendingInvisibleItems.insert(item);
+            ++itInvisible;
         }
     }
 
@@ -958,6 +1052,11 @@ QHash<QByteArray, QVariant> KFileItemModelRolesUpdater::rolesData(const KFileIte
             if (getIsExpandableRole) {
                 data.insert("isExpandable", count > 0);
             }
+
+            if (!m_dirWatcher->contains(path)) {
+                m_dirWatcher->addDir(path);
+                m_watchedDirs.insert(path);
+            }
         } else if (getSizeRole) {
             data.insert("size", -1); // -1 indicates an unknown number of items
         }
@@ -972,26 +1071,26 @@ QHash<QByteArray, QVariant> KFileItemModelRolesUpdater::rolesData(const KFileIte
 #ifdef HAVE_NEPOMUK
     if (m_nepomukResourceWatcher) {
         const KNepomukRolesProvider& rolesProvider = KNepomukRolesProvider::instance();
-        Nepomuk::Resource resource(item.url());
+        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.resourceUri();
+        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.resourceUri();
+            uri = resource.uri();
         }
         if (!uri.isEmpty() && !m_nepomukUriItems.contains(uri)) {
-            // TODO: Calling stop()/start() is a workaround until
-            // ResourceWatcher has been fixed.
-            m_nepomukResourceWatcher->stop();
             m_nepomukResourceWatcher->addResource(resource);
-            m_nepomukResourceWatcher->start();
+
+            if (m_nepomukUriItems.isEmpty()) {
+                m_nepomukResourceWatcher->start();
+            }
 
             m_nepomukUriItems.insert(uri, item.url());
         }
@@ -1060,10 +1159,10 @@ int KFileItemModelRolesUpdater::subItemsCount(const QString& path) const
 
     int count = -1;
     DIR* dir = ::opendir(QFile::encodeName(path));
-    if (dir) {
+    if (dir) {  // krazy:exclude=syscalls
         count = 0;
         struct dirent *dirEntry = 0;
-        while ((dirEntry = ::readdir(dir))) { // krazy:exclude=syscalls
+        while ((dirEntry = ::readdir(dir))) {
             if (dirEntry->d_name[0] == '.') {
                 if (dirEntry->d_name[1] == '\0' || !countHiddenFiles) {
                     // Skip "." or hidden files
@@ -1075,9 +1174,14 @@ int KFileItemModelRolesUpdater::subItemsCount(const QString& path) const
                 }
             }
 
-            // If only directories are counted, consider an unknown file type also
-            // as directory instead of trying to do an expensive stat() (see bug 292642).
-            if (!showFoldersOnly || dirEntry->d_type == DT_DIR || dirEntry->d_type == DT_UNKNOWN) {
+            // If only directories are counted, consider an unknown file type and links also
+            // as directory instead of trying to do an expensive stat()
+            // (see bugs 292642 and 299997).
+            const bool countEntry = !showFoldersOnly ||
+                                    dirEntry->d_type == DT_DIR ||
+                                    dirEntry->d_type == DT_LNK ||
+                                    dirEntry->d_type == DT_UNKNOWN;
+            if (countEntry) {
                 ++count;
             }
         }