]> cloud.milkyroute.net Git - dolphin.git/blobdiff - src/kitemviews/kfileitemmodelrolesupdater.cpp
Adding license header in kitemlistviewaccessible
[dolphin.git] / src / kitemviews / kfileitemmodelrolesupdater.cpp
index 34165843ff2915301cd12a86563cb41936c4b0df..6dba2245dd69a6bab353892e46600de9a14e715b 100644 (file)
 #include "kfileitemmodelrolesupdater.h"
 
 #include "kfileitemmodel.h"
-#include "kpixmapmodifier_p.h"
 
 #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>
 #include <QTimer>
 
 #ifdef HAVE_NEPOMUK
-    #include "knepomukrolesprovider_p.h"
-    #include "knepomukresourcewatcher_p.h"
+    #include "private/knepomukrolesprovider.h"
+    #include "private/nepomuk/resourcewatcher.h"
 #endif
 
 // Required includes for subItemsCount():
@@ -69,6 +74,7 @@ KFileItemModelRolesUpdater::KFileItemModelRolesUpdater(KFileItemModel* model, QO
     m_previewShown(false),
     m_enlargeSmallPreviews(true),
     m_clearPreviews(false),
+    m_sortingProgress(-1),
     m_model(model),
     m_iconSize(),
     m_firstVisibleIndex(0),
@@ -79,7 +85,9 @@ 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()
@@ -100,6 +108,8 @@ KFileItemModelRolesUpdater::KFileItemModelRolesUpdater(KFileItemModel* model, QO
             this,    SLOT(slotItemsRemoved(KItemRangeList)));
     connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
             this,    SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
+    connect(m_model, SIGNAL(sortRoleChanged(QByteArray,QByteArray)),
+            this,    SLOT(slotSortRoleChanged(QByteArray,QByteArray)));
 
     // Use a timer to prevent that each call of slotItemsChanged() results in a synchronous
     // resolving of the roles. Postpone the resolving until no update has been done for 1 second.
@@ -107,10 +117,23 @@ KFileItemModelRolesUpdater::KFileItemModelRolesUpdater(KFileItemModel* model, QO
     m_changedItemsTimer->setInterval(1000);
     m_changedItemsTimer->setSingleShot(true);
     connect(m_changedItemsTimer, SIGNAL(timeout()), this, SLOT(resolveChangedItems()));
+
+    m_resolvableRoles.insert("size");
+    m_resolvableRoles.insert("type");
+    m_resolvableRoles.insert("isExpandable");
+#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)
@@ -245,7 +268,7 @@ void KFileItemModelRolesUpdater::setRoles(const QSet<QByteArray>& roles)
         QSetIterator<QByteArray> it(roles);
         while (it.hasNext()) {
             const QByteArray& role = it.next();
-            if (rolesProvider.isNepomukRole(role)) {
+            if (rolesProvider.roles().contains(role)) {
                 hasNepomukRole = true;
                 break;
             }
@@ -270,6 +293,8 @@ void KFileItemModelRolesUpdater::setRoles(const QSet<QByteArray>& roles)
         }
 #endif
 
+        updateSortProgress();
+
         if (m_paused) {
             m_rolesChangedDuringPausing = true;
         } else {
@@ -302,11 +327,33 @@ 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) {
+        if (allItemsRemoved) {
             m_nepomukResourceWatcher->setResources(QList<Nepomuk::Resource>());
+            m_nepomukResourceWatcher->stop();
             m_nepomukUriItems.clear();
         } else {
             QList<Nepomuk::Resource> newResources;
@@ -321,6 +368,10 @@ void KFileItemModelRolesUpdater::slotItemsRemoved(const KItemRangeList& itemRang
                 }
             }
             m_nepomukResourceWatcher->setResources(newResources);
+            if (newResources.isEmpty()) {
+                Q_ASSERT(m_nepomukUriItems.isEmpty());
+                m_nepomukResourceWatcher->stop();
+            }
         }
     }
 #endif
@@ -331,7 +382,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();
@@ -378,6 +429,14 @@ void KFileItemModelRolesUpdater::slotItemsChanged(const KItemRangeList& itemRang
     m_changedItemsTimer->start();
 }
 
+void KFileItemModelRolesUpdater::slotSortRoleChanged(const QByteArray& current,
+                                                     const QByteArray& previous)
+{
+    Q_UNUSED(current);
+    Q_UNUSED(previous);
+    updateSortProgress();
+}
+
 void KFileItemModelRolesUpdater::slotGotPreview(const KFileItem& item, const QPixmap& pixmap)
 {
     m_pendingVisibleItems.remove(item);
@@ -434,6 +493,8 @@ void KFileItemModelRolesUpdater::slotGotPreview(const KFileItem& item, const QPi
     m_model->setData(index, data);
     connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
             this,    SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
+
+    applySortProgressToModel();
 }
 
 void KFileItemModelRolesUpdater::slotPreviewFailed(const KFileItem& item)
@@ -445,6 +506,8 @@ void KFileItemModelRolesUpdater::slotPreviewFailed(const KFileItem& item)
     m_clearPreviews = true;
     applyResolvedRoles(item, ResolveAll);
     m_clearPreviews = clearPreviews;
+
+    applySortProgressToModel();
 }
 
 void KFileItemModelRolesUpdater::slotPreviewJobFinished(KJob* job)
@@ -494,6 +557,8 @@ void KFileItemModelRolesUpdater::resolveNextPendingRoles()
         m_clearPreviews = false;
     }
 
+    applySortProgressToModel();
+
 #ifdef KFILEITEMMODELROLESUPDATER_DEBUG
     static int callCount = 0;
     ++callCount;
@@ -546,8 +611,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)
@@ -627,6 +717,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)));
@@ -648,10 +741,17 @@ void KFileItemModelRolesUpdater::resolvePendingRoles()
 {
     int resolvedCount = 0;
 
-    const bool hasSlowRoles = m_previewShown
-                              || m_roles.contains("size")
-                              || m_roles.contains("type")
-                              || m_roles.contains("isExpandable");
+    bool hasSlowRoles = m_previewShown;
+    if (!hasSlowRoles) {
+        QSetIterator<QByteArray> it(m_roles);
+        while (it.hasNext()) {
+            if (m_resolvableRoles.contains(it.next())) {
+                hasSlowRoles = true;
+                break;
+            }
+        }
+    }
+
     const ResolveHint resolveHint = hasSlowRoles ? ResolveFast : ResolveAll;
 
     // Resolving the MIME type can be expensive. Assure that not more than MaxBlockTimeout ms are
@@ -664,12 +764,12 @@ void KFileItemModelRolesUpdater::resolvePendingRoles()
     QSetIterator<KFileItem> visibleIt(m_pendingVisibleItems);
     while (visibleIt.hasNext()) {
         const KFileItem item = visibleIt.next();
-        applyResolvedRoles(item, resolveHint);
         if (!hasSlowRoles) {
             Q_ASSERT(!m_pendingInvisibleItems.contains(item));
-            // All roles have been resolved already by applyResolvedRoles()
+            // All roles will be resolved by applyResolvedRoles()
             m_pendingVisibleItems.remove(item);
         }
+        applyResolvedRoles(item, resolveHint);
         ++resolvedCount;
 
         if (timer.elapsed() > MaxBlockTimeout) {
@@ -720,6 +820,8 @@ void KFileItemModelRolesUpdater::resolvePendingRoles()
     }
     kDebug() << "[TIME] Resolved pending roles:" << timer.elapsed();
 #endif
+
+    applySortProgressToModel();
 }
 
 void KFileItemModelRolesUpdater::resetPendingRoles()
@@ -812,6 +914,56 @@ void KFileItemModelRolesUpdater::sortAndResolvePendingRoles()
     resolvePendingRoles();
 }
 
+void KFileItemModelRolesUpdater::applySortProgressToModel()
+{
+    if (m_sortingProgress < 0) {
+        return;
+    }
+
+    // Inform the model about the progress of the resolved items,
+    // so that it can give an indication when the sorting has been finished.
+    const int resolvedCount = m_model->count()
+                              - m_pendingVisibleItems.count()
+                              - m_pendingInvisibleItems.count();
+    if (resolvedCount > 0) {
+        m_model->emitSortProgress(resolvedCount);
+        if (resolvedCount == m_model->count()) {
+            m_sortingProgress = -1;
+        }
+    }
+}
+
+void KFileItemModelRolesUpdater::updateSortProgress()
+{
+    const QByteArray sortRole = m_model->sortRole();
+
+    // Optimization if the sorting is done by type: In case if all MIME-types
+    // are known, the types have been resolved already by KFileItemModel and
+    // no sort-progress feedback is required.
+    const bool showProgress = (sortRole == "type")
+                              ? hasUnknownMimeTypes()
+                              : m_resolvableRoles.contains(sortRole);
+
+    if (m_sortingProgress >= 0) {
+        // Mark the current sorting as finished
+        m_model->emitSortProgress(m_model->count());
+    }
+    m_sortingProgress = showProgress ? 0 : -1;
+}
+
+bool KFileItemModelRolesUpdater::hasUnknownMimeTypes() const
+{
+    const int count = m_model->count();
+    for (int i = 0; i < count; ++i) {
+        const KFileItem item = m_model->fileItem(i);
+        if (!item.isMimeTypeKnown()) {
+            return true;
+        }
+    }
+
+    return false;
+}
+
 bool KFileItemModelRolesUpdater::applyResolvedRoles(const KFileItem& item, ResolveHint hint)
 {
     if (item.isNull()) {
@@ -871,6 +1023,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
         }
@@ -885,7 +1042,7 @@ QHash<QByteArray, QVariant> KFileItemModelRolesUpdater::rolesData(const KFileIte
 #ifdef HAVE_NEPOMUK
     if (m_nepomukResourceWatcher) {
         const KNepomukRolesProvider& rolesProvider = KNepomukRolesProvider::instance();
-        Nepomuk::Resource resource(item.url());
+        Nepomuk::Resource resource(item.nepomukUri());
         QHashIterator<QByteArray, QVariant> it(rolesProvider.roleValues(resource, m_roles));
         while (it.hasNext()) {
             it.next();
@@ -900,11 +1057,11 @@ QHash<QByteArray, QVariant> KFileItemModelRolesUpdater::rolesData(const KFileIte
             uri = resource.resourceUri();
         }
         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());
         }
@@ -953,7 +1110,7 @@ KFileItemList KFileItemModelRolesUpdater::sortedItems(const QSet<KFileItem>& ite
 int KFileItemModelRolesUpdater::subItemsCount(const QString& path) const
 {
     const bool countHiddenFiles = m_model->showHiddenFiles();
-    const bool showFoldersOnly  = m_model->showFoldersOnly();
+    const bool showFoldersOnly  = m_model->showDirectoriesOnly();
 
 #ifdef Q_WS_WIN
     QDir dir(path);
@@ -973,10 +1130,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
@@ -988,9 +1145,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;
             }
         }