]> cloud.milkyroute.net Git - dolphin.git/blobdiff - src/kitemviews/kfileitemmodelrolesupdater.cpp
[Details mode] Allow to fill the column size of directories with actual size
[dolphin.git] / src / kitemviews / kfileitemmodelrolesupdater.cpp
index bfb4e644eae0341691f64a5439dee05ea5f782bc..c28e240a5f97ba6b54dc1bd6e5c5453a769da363 100644 (file)
 #include "kfileitemmodelrolesupdater.h"
 
 #include "kfileitemmodel.h"
+#include "private/kdirectorycontentscounter.h"
+#include "private/kpixmapmodifier.h"
 
 #include <KConfig>
 #include <KConfigGroup>
-#include <KDebug>
-#include <KDirWatch>
-#include <KFileItem>
-#include <KGlobal>
 #include <KIO/JobUiDelegate>
 #include <KIO/PreviewJob>
-
-#include "private/kpixmapmodifier.h"
+#include <KIconLoader>
+#include <KJobWidgets>
+#include <KOverlayIconPlugin>
+#include <KPluginLoader>
+#include <KSharedConfig>
+
+#ifdef HAVE_BALOO
+#include "private/kbaloorolesprovider.h"
+#include <Baloo/File>
+#include <Baloo/FileMonitor>
+#endif
 
 #include <QApplication>
 #include <QPainter>
-#include <QPixmap>
 #include <QElapsedTimer>
 #include <QTimer>
 
-#include <algorithm>
-
-#ifdef HAVE_NEPOMUK
-    #include "private/knepomukrolesprovider.h"
-    #include <Nepomuk2/ResourceWatcher>
-#endif
-
-// Required includes for subItemsCount():
-#ifdef Q_WS_WIN
-    #include <QDir>
-#else
-    #include <dirent.h>
-    #include <QFile>
-#endif
-
 // #define KFILEITEMMODELROLESUPDATER_DEBUG
 
 namespace {
@@ -88,58 +79,62 @@ KFileItemModelRolesUpdater::KFileItemModelRolesUpdater(KFileItemModel* model, QO
     m_resolvableRoles(),
     m_enabledPlugins(),
     m_pendingSortRoleItems(),
-    m_hasUnknownIcons(false),
-    m_firstIndexWithoutIcon(0),
     m_pendingIndexes(),
     m_pendingPreviewItems(),
     m_previewJob(),
-    m_recentlyChangedItemsTimer(0),
+    m_recentlyChangedItemsTimer(nullptr),
     m_recentlyChangedItems(),
     m_changedItems(),
-    m_dirWatcher(0),
-    m_watchedDirs()
-  #ifdef HAVE_NEPOMUK
-  , m_nepomukResourceWatcher(0),
-    m_nepomukUriItems()
+    m_directoryContentsCounter(nullptr)
+  #ifdef HAVE_BALOO
+  , m_balooFileMonitor(nullptr)
   #endif
 {
     Q_ASSERT(model);
 
-    const KConfigGroup globalConfig(KGlobal::config(), "PreviewSettings");
-    m_enabledPlugins = globalConfig.readEntry("Plugins", QStringList()
-                                                         << "directorythumbnail"
-                                                         << "imagethumbnail"
-                                                         << "jpegthumbnail");
-
-    connect(m_model, SIGNAL(itemsInserted(KItemRangeList)),
-            this,    SLOT(slotItemsInserted(KItemRangeList)));
-    connect(m_model, SIGNAL(itemsRemoved(KItemRangeList)),
-            this,    SLOT(slotItemsRemoved(KItemRangeList)));
-    connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
-            this,    SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
-    connect(m_model, SIGNAL(itemsMoved(KItemRange,QList<int>)),
-            this,    SLOT(slotItemsMoved(KItemRange,QList<int>)));
-    connect(m_model, SIGNAL(sortRoleChanged(QByteArray,QByteArray)),
-            this,    SLOT(slotSortRoleChanged(QByteArray,QByteArray)));
+    const KConfigGroup globalConfig(KSharedConfig::openConfig(), "PreviewSettings");
+    m_enabledPlugins = globalConfig.readEntry("Plugins", KIO::PreviewJob::defaultPlugins());
+
+    connect(m_model, &KFileItemModel::itemsInserted,
+            this,    &KFileItemModelRolesUpdater::slotItemsInserted);
+    connect(m_model, &KFileItemModel::itemsRemoved,
+            this,    &KFileItemModelRolesUpdater::slotItemsRemoved);
+    connect(m_model, &KFileItemModel::itemsChanged,
+            this,    &KFileItemModelRolesUpdater::slotItemsChanged);
+    connect(m_model, &KFileItemModel::itemsMoved,
+            this,    &KFileItemModelRolesUpdater::slotItemsMoved);
+    connect(m_model, &KFileItemModel::sortRoleChanged,
+            this,    &KFileItemModelRolesUpdater::slotSortRoleChanged);
 
     // 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.
+    // resolving of the roles. Postpone the resolving until no update has been done for 100 ms.
     m_recentlyChangedItemsTimer = new QTimer(this);
-    m_recentlyChangedItemsTimer->setInterval(1000);
+    m_recentlyChangedItemsTimer->setInterval(100);
     m_recentlyChangedItemsTimer->setSingleShot(true);
-    connect(m_recentlyChangedItemsTimer, SIGNAL(timeout()), this, SLOT(resolveRecentlyChangedItems()));
+    connect(m_recentlyChangedItemsTimer, &QTimer::timeout, this, &KFileItemModelRolesUpdater::resolveRecentlyChangedItems);
 
     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
 
-    // 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)));
+    m_directoryContentsCounter = new KDirectoryContentsCounter(m_model, this);
+    connect(m_directoryContentsCounter, &KDirectoryContentsCounter::result,
+            this,                       &KFileItemModelRolesUpdater::slotDirectoryContentsCountReceived);
+
+    auto plugins = KPluginLoader::instantiatePlugins(QStringLiteral("kf5/overlayicon"), nullptr, qApp);
+    foreach (QObject *it, plugins) {
+        auto plugin = qobject_cast<KOverlayIconPlugin*>(it);
+        if (plugin) {
+            m_overlayIconsPlugin.append(plugin);
+            connect(plugin, &KOverlayIconPlugin::overlaysChanged, this, &KFileItemModelRolesUpdater::slotOverlaysChanged);
+        } else {
+            // not our/valid plugin, so delete the created object
+            it->deleteLater();
+        }
+    }
 }
 
 KFileItemModelRolesUpdater::~KFileItemModelRolesUpdater()
@@ -273,32 +268,29 @@ void KFileItemModelRolesUpdater::setRoles(const QSet<QByteArray>& roles)
     if (m_roles != roles) {
         m_roles = roles;
 
-#ifdef HAVE_NEPOMUK
+#ifdef HAVE_BALOO
         // 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)
+        // 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 KNepomukRolesProvider& rolesProvider = KNepomukRolesProvider::instance();
-        bool hasNepomukRole = false;
+        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)) {
-                hasNepomukRole = true;
+                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)));
-        } else if (!hasNepomukRole && m_nepomukResourceWatcher) {
-            delete m_nepomukResourceWatcher;
-            m_nepomukResourceWatcher = 0;
-            m_nepomukUriItems.clear();
+        if (hasBalooRole && m_balooConfig.fileIndexingEnabled() && !m_balooFileMonitor) {
+            m_balooFileMonitor = new Baloo::FileMonitor(this);
+            connect(m_balooFileMonitor, &Baloo::FileMonitor::fileMetaDataChanged,
+                    this, &KFileItemModelRolesUpdater::applyChangedBalooRoles);
+        } else if (!hasBalooRole && m_balooFileMonitor) {
+            delete m_balooFileMonitor;
+            m_balooFileMonitor = nullptr;
         }
 #endif
 
@@ -330,10 +322,6 @@ void KFileItemModelRolesUpdater::slotItemsInserted(const KItemRangeList& itemRan
     QElapsedTimer timer;
     timer.start();
 
-    const int firstInsertedIndex = itemRanges.first().index;
-    m_firstIndexWithoutIcon = qMin(m_firstIndexWithoutIcon, firstInsertedIndex);
-    m_hasUnknownIcons = true;
-
     // Determine the sort role synchronously for as many items as possible.
     if (m_resolvableRoles.contains(m_model->sortRole())) {
         int insertedCount = 0;
@@ -366,58 +354,23 @@ void KFileItemModelRolesUpdater::slotItemsInserted(const KItemRangeList& itemRan
 
 void KFileItemModelRolesUpdater::slotItemsRemoved(const KItemRangeList& itemRanges)
 {
-    Q_UNUSED(itemRanges);
+    Q_UNUSED(itemRanges)
 
     const bool allItemsRemoved = (m_model->count() == 0);
 
-    if (m_hasUnknownIcons) {
-        const int firstRemovedIndex = itemRanges.first().index;
-        m_firstIndexWithoutIcon = qMin(m_firstIndexWithoutIcon, firstRemovedIndex);
-    }
-
-    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
+#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);
-                if (m_model->index(itemUrl) >= 0) {
-                    newResources.append(resource);
-                } else {
-                    m_nepomukUriItems.remove(uri);
+            QStringList newFileList;
+            foreach (const QString& file, m_balooFileMonitor->files()) {
+                if (m_model->index(QUrl::fromLocalFile(file)) >= 0) {
+                    newFileList.append(file);
                 }
             }
-            m_nepomukResourceWatcher->setResources(newResources);
-            if (newResources.isEmpty()) {
-                Q_ASSERT(m_nepomukUriItems.isEmpty());
-                m_nepomukResourceWatcher->stop();
-            }
+            m_balooFileMonitor->setFiles(newFileList);
         }
     }
 #endif
@@ -451,15 +404,10 @@ void KFileItemModelRolesUpdater::slotItemsRemoved(const KItemRangeList& itemRang
     }
 }
 
-void KFileItemModelRolesUpdater::slotItemsMoved(const KItemRange& itemRange, QList<int> movedToIndexes)
+void KFileItemModelRolesUpdater::slotItemsMoved(const KItemRange& itemRange, const QList<int> &movedToIndexes)
 {
-    Q_UNUSED(itemRange);
-    Q_UNUSED(movedToIndexes);
-
-    if (m_hasUnknownIcons) {
-        const int firstMovedIndex = itemRange.index;
-        m_firstIndexWithoutIcon = qMin(m_firstIndexWithoutIcon, firstMovedIndex);
-    }
+    Q_UNUSED(itemRange)
+    Q_UNUSED(movedToIndexes)
 
     // The visible items might have changed.
     startUpdating();
@@ -468,7 +416,7 @@ void KFileItemModelRolesUpdater::slotItemsMoved(const KItemRange& itemRange, QLi
 void KFileItemModelRolesUpdater::slotItemsChanged(const KItemRangeList& itemRanges,
                                                   const QSet<QByteArray>& roles)
 {
-    Q_UNUSED(roles);
+    Q_UNUSED(roles)
 
     // Find out if slotItemsChanged() has been done recently. If that is the
     // case, resolving the roles is postponed until a timer has exceeded
@@ -496,8 +444,8 @@ void KFileItemModelRolesUpdater::slotItemsChanged(const KItemRangeList& itemRang
 void KFileItemModelRolesUpdater::slotSortRoleChanged(const QByteArray& current,
                                                      const QByteArray& previous)
 {
-    Q_UNUSED(current);
-    Q_UNUSED(previous);
+    Q_UNUSED(current)
+    Q_UNUSED(previous)
 
     if (m_resolvableRoles.contains(current)) {
         m_pendingSortRoleItems.clear();
@@ -546,10 +494,9 @@ void KFileItemModelRolesUpdater::slotGotPreview(const KFileItem& item, const QPi
 
     QPixmap scaledPixmap = pixmap;
 
-    const QString mimeType = item.mimetype();
-    const int slashIndex = mimeType.indexOf(QLatin1Char('/'));
-    const QString mimeTypeGroup = mimeType.left(slashIndex);
-    if (mimeTypeGroup == QLatin1String("image")) {
+    if (!pixmap.hasAlpha()
+        && m_iconSize.width()  > KIconLoader::SizeSmallMedium
+        && m_iconSize.height() > KIconLoader::SizeSmallMedium) {
         if (m_enlargeSmallPreviews) {
             KPixmapModifier::applyFrame(scaledPixmap, m_iconSize);
         } else {
@@ -559,7 +506,7 @@ void KFileItemModelRolesUpdater::slotGotPreview(const KFileItem& item, const QPi
             const bool enlargingRequired = scaledPixmap.width()  < contentSize.width() &&
                                            scaledPixmap.height() < contentSize.height();
             if (enlargingRequired) {
-                QSize frameSize = scaledPixmap.size();
+                QSize frameSize = scaledPixmap.size() / scaledPixmap.devicePixelRatio();
                 frameSize.scale(m_iconSize, Qt::KeepAspectRatio);
 
                 QPixmap largeFrame(frameSize);
@@ -568,28 +515,45 @@ void KFileItemModelRolesUpdater::slotGotPreview(const KFileItem& item, const QPi
                 KPixmapModifier::applyFrame(largeFrame, frameSize);
 
                 QPainter painter(&largeFrame);
-                painter.drawPixmap((largeFrame.width()  - scaledPixmap.width()) / 2,
-                                   (largeFrame.height() - scaledPixmap.height()) / 2,
+                painter.drawPixmap((largeFrame.width()  - scaledPixmap.width() / scaledPixmap.devicePixelRatio()) / 2,
+                                   (largeFrame.height() - scaledPixmap.height() / scaledPixmap.devicePixelRatio()) / 2,
                                    scaledPixmap);
                 scaledPixmap = largeFrame;
             } else {
-                // The image must be shrinked as it is too large to fit into
+                // The image must be shrunk as it is too large to fit into
                 // the available icon size
                 KPixmapModifier::applyFrame(scaledPixmap, m_iconSize);
             }
         }
     } else {
-        KPixmapModifier::scale(scaledPixmap, m_iconSize);
+        KPixmapModifier::scale(scaledPixmap, m_iconSize * qApp->devicePixelRatio());
+        scaledPixmap.setDevicePixelRatio(qApp->devicePixelRatio());
     }
 
     QHash<QByteArray, QVariant> data = rolesData(item);
+
+    const QStringList overlays = data["iconOverlays"].toStringList();
+    // Strangely KFileItem::overlays() returns empty string-values, so
+    // we need to check first whether an overlay must be drawn at all.
+    // It is more efficient to do it here, as KIconLoader::drawOverlays()
+    // assumes that an overlay will be drawn and has some additional
+    // setup time.
+    foreach (const QString& overlay, overlays) {
+        if (!overlay.isEmpty()) {
+            // There is at least one overlay, draw all overlays above m_pixmap
+            // and cancel the check
+            KIconLoader::global()->drawOverlays(overlays, scaledPixmap, KIconLoader::Desktop);
+            break;
+        }
+    }
+
     data.insert("iconPixmap", scaledPixmap);
 
-    disconnect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
-               this,    SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
+    disconnect(m_model, &KFileItemModel::itemsChanged,
+               this,    &KFileItemModelRolesUpdater::slotItemsChanged);
     m_model->setData(index, data);
-    connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
-            this,    SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
+    connect(m_model, &KFileItemModel::itemsChanged,
+            this,    &KFileItemModelRolesUpdater::slotItemsChanged);
 
     m_finishedItems.insert(item);
 }
@@ -607,20 +571,20 @@ void KFileItemModelRolesUpdater::slotPreviewFailed(const KFileItem& item)
         QHash<QByteArray, QVariant> data;
         data.insert("iconPixmap", QPixmap());
 
-        disconnect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
-                   this,    SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
+        disconnect(m_model, &KFileItemModel::itemsChanged,
+                   this,    &KFileItemModelRolesUpdater::slotItemsChanged);
         m_model->setData(index, data);
-        connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
-                this,    SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
+        connect(m_model, &KFileItemModel::itemsChanged,
+                this,    &KFileItemModelRolesUpdater::slotItemsChanged);
 
-        applyResolvedRoles(item, ResolveAll);
+        applyResolvedRoles(index, ResolveAll);
         m_finishedItems.insert(item);
     }
 }
 
 void KFileItemModelRolesUpdater::slotPreviewJobFinished()
 {
-    m_previewJob = 0;
+    m_previewJob = nullptr;
 
     if (m_state != PreviewJobRunning) {
         return;
@@ -662,23 +626,23 @@ void KFileItemModelRolesUpdater::resolveNextSortRole()
 
     if (!m_pendingSortRoleItems.isEmpty()) {
         applySortProgressToModel();
-        QTimer::singleShot(0, this, SLOT(resolveNextSortRole()));
+        QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextSortRole);
     } else {
         m_state = Idle;
 
         // Prevent that we try to update the items twice.
-        disconnect(m_model, SIGNAL(itemsMoved(KItemRange,QList<int>)),
-                   this,    SLOT(slotItemsMoved(KItemRange,QList<int>)));
+        disconnect(m_model, &KFileItemModel::itemsMoved,
+                   this,    &KFileItemModelRolesUpdater::slotItemsMoved);
         applySortProgressToModel();
-        connect(m_model, SIGNAL(itemsMoved(KItemRange,QList<int>)),
-                this,    SLOT(slotItemsMoved(KItemRange,QList<int>)));
+        connect(m_model, &KFileItemModel::itemsMoved,
+                this,    &KFileItemModelRolesUpdater::slotItemsMoved);
         startUpdating();
     }
 }
 
 void KFileItemModelRolesUpdater::resolveNextPendingRoles()
 {
-    if (m_state != ResolvingAllRoles && m_state != PreviewJobRunning) {
+    if (m_state != ResolvingAllRoles) {
         return;
     }
 
@@ -690,21 +654,15 @@ void KFileItemModelRolesUpdater::resolveNextPendingRoles()
             continue;
         }
 
-        if (m_previewShown) {
-            // Only determine the icon. The other roles are resolved when the preview is received.
-            applyResolvedRoles(item, ResolveFast);
-        } else {
-            applyResolvedRoles(item, ResolveAll);
-            m_finishedItems.insert(item);
-            m_changedItems.remove(item);
-        }
-
+        applyResolvedRoles(index, ResolveAll);
+        m_finishedItems.insert(item);
+        m_changedItems.remove(item);
         break;
     }
 
     if (!m_pendingIndexes.isEmpty()) {
-        QTimer::singleShot(0, this, SLOT(resolveNextPendingRoles()));
-    } else if (m_state != PreviewJobRunning) {
+        QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextPendingRoles);
+    } else {
         m_state = Idle;
 
         if (m_clearPreviews) {
@@ -713,15 +671,15 @@ void KFileItemModelRolesUpdater::resolveNextPendingRoles()
                 QHash<QByteArray, QVariant> data;
                 data.insert("iconPixmap", QPixmap());
 
-                disconnect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
-                           this,    SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
+                disconnect(m_model, &KFileItemModel::itemsChanged,
+                           this,    &KFileItemModelRolesUpdater::slotItemsChanged);
                 for (int index = 0; index <= m_model->count(); ++index) {
                     if (m_model->data(index).contains("iconPixmap")) {
                         m_model->setData(index, data);
                     }
                 }
-                connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
-                        this,    SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
+                connect(m_model, &KFileItemModel::itemsChanged,
+                        this,    &KFileItemModelRolesUpdater::slotItemsChanged);
 
             }
             m_clearPreviews = false;
@@ -740,67 +698,77 @@ void KFileItemModelRolesUpdater::resolveRecentlyChangedItems()
     updateChangedItems();
 }
 
-void KFileItemModelRolesUpdater::applyChangedNepomukRoles(const Nepomuk2::Resource& resource)
+void KFileItemModelRolesUpdater::applyChangedBalooRoles(const QString& file)
 {
-#ifdef HAVE_NEPOMUK
-    const KUrl itemUrl = m_nepomukUriItems.value(resource.uri());
-    const KFileItem item = m_model->fileItem(itemUrl);
+#ifdef HAVE_BALOO
+    const KFileItem item = m_model->fileItem(QUrl::fromLocalFile(file));
 
     if (item.isNull()) {
         // itemUrl is not in the model anymore, probably because
         // the corresponding file has been deleted in the meantime.
         return;
     }
+    applyChangedBalooRolesForItem(item);
+#else
+    Q_UNUSED(file)
+#endif
+}
 
-    QHash<QByteArray, QVariant> data = rolesData(item);
+void KFileItemModelRolesUpdater::applyChangedBalooRolesForItem(const KFileItem &item)
+{
+#ifdef HAVE_BALOO
+    Baloo::File file(item.localPath());
+    file.load();
 
-    const KNepomukRolesProvider& rolesProvider = KNepomukRolesProvider::instance();
-    QHashIterator<QByteArray, QVariant> it(rolesProvider.roleValues(resource, m_roles));
+    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(file, m_roles));
     while (it.hasNext()) {
         it.next();
         data.insert(it.key(), it.value());
     }
 
-    disconnect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
-               this,    SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
+    disconnect(m_model, &KFileItemModel::itemsChanged,
+               this,    &KFileItemModelRolesUpdater::slotItemsChanged);
     const int index = m_model->index(item);
     m_model->setData(index, data);
-    connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
-            this,    SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
+    connect(m_model, &KFileItemModel::itemsChanged,
+            this,    &KFileItemModelRolesUpdater::slotItemsChanged);
 #else
 #ifndef Q_CC_MSVC
-    Q_UNUSED(resource);
+    Q_UNUSED(item)
 #endif
 #endif
 }
 
-void KFileItemModelRolesUpdater::slotDirWatchDirty(const QString& path)
+void KFileItemModelRolesUpdater::slotDirectoryContentsCountReceived(const QString& path, int count, long size)
 {
     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));
+        const int index = m_model->index(QUrl::fromLocalFile(path));
         if (index >= 0) {
-            if (!m_model->fileItem(index).isDir()) {
-                // If INotify is used, KDirWatch issues the dirty() signal
-                // also for changed files inside the directory, even if we
-                // don't enable this behavior explicitly (see bug 309740).
-                return;
-            }
-
             QHash<QByteArray, QVariant> data;
 
-            const int count = subItemsCount(path);
             if (getSizeRole) {
-                data.insert("size", count);
+                data.insert("count", count);
+                if (size != -1) {
+                    data.insert("size", QVariant::fromValue(size));
+                }
             }
             if (getIsExpandableRole) {
                 data.insert("isExpandable", count > 0);
             }
 
-            // Note that we do not block the itemsChanged signal here.
-            // This ensures that a new preview will be generated.
             m_model->setData(index, data);
         }
     }
@@ -828,13 +796,6 @@ void KFileItemModelRolesUpdater::startUpdating()
     // Determine the icons for the visible items synchronously.
     updateVisibleIcons();
 
-    // Try to do at least a fast icon loading (without determining the
-    // mime type) for all items, to reduce the risk that the user sees
-    // "unknown" icons when scrolling.
-    if (m_hasUnknownIcons) {
-        updateAllIconsFast(MaxBlockTimeout - timer.elapsed());
-    }
-
     // A detailed update of the items in and near the visible area
     // only makes sense if sorting is finished.
     if (m_state == ResolvingSortRole) {
@@ -860,7 +821,7 @@ void KFileItemModelRolesUpdater::startUpdating()
         m_pendingIndexes = indexes;
         // Trigger the asynchronous resolving of all roles.
         m_state = ResolvingAllRoles;
-        QTimer::singleShot(0, this, SLOT(resolveNextPendingRoles()));
+        QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextPendingRoles);
     }
 }
 
@@ -882,62 +843,12 @@ 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);
-    }
-
-    if (index > lastVisibleIndex) {
-        return;
-    }
-
-    // If this didn't work before MaxBlockTimeout was reached, at least
-    // prevent that the user sees 'unknown' icons.
-    disconnect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
-               this,    SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
-
-    while (index <= lastVisibleIndex) {
-        if (!m_model->data(index).contains("iconName")) {
-            const KFileItem item = m_model->fileItem(index);
-            QHash<QByteArray, QVariant> data;
-            data.insert("iconName", item.iconName());
-            m_model->setData(index, data);
-        }
-        ++index;
-    }
-
-    connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
-            this,    SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
-}
-
-void KFileItemModelRolesUpdater::updateAllIconsFast(int timeout)
-{
-    if (timeout <= 0) {
-        return;
-    }
-
-    QElapsedTimer timer;
-    timer.start();
-
-    disconnect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
-               this,    SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
-
-    const int count = m_model->count();
-    while (m_firstIndexWithoutIcon < count && timer.elapsed() < timeout) {
-        if (!m_model->data(m_firstIndexWithoutIcon).contains("iconName")) {
-            const KFileItem item = m_model->fileItem(m_firstIndexWithoutIcon);
-            QHash<QByteArray, QVariant> data;
-            data.insert("iconName", item.iconName());
-            m_model->setData(m_firstIndexWithoutIcon, data);
-        }
-        ++m_firstIndexWithoutIcon;
-    }
-
-    if (m_firstIndexWithoutIcon == count) {
-        m_hasUnknownIcons = false;
+        applyResolvedRoles(index, ResolveFast);
     }
 
-    connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
-            this,    SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
+    // KFileItemListView::initializeItemListWidget(KItemListWidget*) will load
+    // preliminary icons (i.e., without mime type determination) for the
+    // remaining items.
 }
 
 void KFileItemModelRolesUpdater::startPreviewJob()
@@ -945,7 +856,7 @@ void KFileItemModelRolesUpdater::startPreviewJob()
     m_state = PreviewJobRunning;
 
     if (m_pendingPreviewItems.isEmpty()) {
-        QTimer::singleShot(0, this, SLOT(slotPreviewJobFinished()));
+        QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::slotPreviewJobFinished);
         return;
     }
 
@@ -988,16 +899,16 @@ void KFileItemModelRolesUpdater::startPreviewJob()
     KIO::PreviewJob* job = new KIO::PreviewJob(itemSubSet, cacheSize, &m_enabledPlugins);
 
     job->setIgnoreMaximumSize(itemSubSet.first().isLocalFile());
-    if (job->ui()) {
-        job->ui()->setWindow(qApp->activeWindow());
+    if (job->uiDelegate()) {
+        KJobWidgets::setWindow(job, qApp->activeWindow());
     }
 
-    connect(job,  SIGNAL(gotPreview(KFileItem,QPixmap)),
-            this, SLOT(slotGotPreview(KFileItem,QPixmap)));
-    connect(job,  SIGNAL(failed(KFileItem)),
-            this, SLOT(slotPreviewFailed(KFileItem)));
-    connect(job,  SIGNAL(finished(KJob*)),
-            this, SLOT(slotPreviewJobFinished()));
+    connect(job,  &KIO::PreviewJob::gotPreview,
+            this, &KFileItemModelRolesUpdater::slotGotPreview);
+    connect(job,  &KIO::PreviewJob::failed,
+            this, &KFileItemModelRolesUpdater::slotPreviewFailed);
+    connect(job,  &KIO::PreviewJob::finished,
+            this, &KFileItemModelRolesUpdater::slotPreviewJobFinished);
 
     m_previewJob = job;
 }
@@ -1022,7 +933,7 @@ void KFileItemModelRolesUpdater::updateChangedItems()
             // asynchronous determination of the sort role.
             killPreviewJob();
             m_state = ResolvingSortRole;
-            QTimer::singleShot(0, this, SLOT(resolveNextSortRole()));
+            QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextSortRole);
         }
 
         return;
@@ -1066,7 +977,7 @@ void KFileItemModelRolesUpdater::updateChangedItems()
         if (!resolvingInProgress) {
             // Trigger the asynchronous resolving of the changed roles.
             m_state = ResolvingAllRoles;
-            QTimer::singleShot(0, this, SLOT(resolveNextPendingRoles()));
+            QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextPendingRoles);
         }
     }
 }
@@ -1084,17 +995,17 @@ void KFileItemModelRolesUpdater::applySortRole(int index)
         data.insert("type", item.mimeComment());
     } else if (m_model->sortRole() == "size" && item.isLocalFile() && item.isDir()) {
         const QString path = item.localPath();
-        data.insert("size", subItemsCount(path));
+        m_directoryContentsCounter->scanDirectory(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);
     }
 
-    disconnect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
-               this,    SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
+    disconnect(m_model, &KFileItemModel::itemsChanged,
+               this,    &KFileItemModelRolesUpdater::slotItemsChanged);
     m_model->setData(index, data);
-    connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
-            this,    SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
+    connect(m_model, &KFileItemModel::itemsChanged,
+            this,    &KFileItemModelRolesUpdater::slotItemsChanged);
 }
 
 void KFileItemModelRolesUpdater::applySortProgressToModel()
@@ -1105,29 +1016,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 if (m_state == ResolvingSortRole || m_state == PreviewJobRunning) {
-        // We are currently performing a fast determination of all icons
-        // in the visible area.
-        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;
         }
@@ -1143,18 +1045,18 @@ bool KFileItemModelRolesUpdater::applyResolvedRoles(const KFileItem& item, Resol
             data.insert("iconPixmap", QPixmap());
         }
 
-        disconnect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
-                   this,    SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
+        disconnect(m_model, &KFileItemModel::itemsChanged,
+                   this,    &KFileItemModelRolesUpdater::slotItemsChanged);
         m_model->setData(index, data);
-        connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
-                this,    SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
+        connect(m_model, &KFileItemModel::itemsChanged,
+                this,    &KFileItemModelRolesUpdater::slotItemsChanged);
         return true;
     }
 
     return false;
 }
 
-QHash<QByteArray, QVariant> KFileItemModelRolesUpdater::rolesData(const KFileItem& item) const
+QHash<QByteArray, QVariant> KFileItemModelRolesUpdater::rolesData(const KFileItem& item)
 {
     QHash<QByteArray, QVariant> data;
 
@@ -1163,19 +1065,10 @@ QHash<QByteArray, QVariant> KFileItemModelRolesUpdater::rolesData(const KFileIte
 
     if ((getSizeRole || getIsExpandableRole) && item.isDir()) {
         if (item.isLocalFile()) {
+            // Tell m_directoryContentsCounter that we want to count the items
+            // inside the directory. The result will be received in slotDirectoryContentsCountReceived.
             const QString path = item.localPath();
-            const int count = subItemsCount(path);
-            if (getSizeRole) {
-                data.insert("size", count);
-            }
-            if (getIsExpandableRole) {
-                data.insert("isExpandable", count > 0);
-            }
-
-            if (!m_dirWatcher->contains(path)) {
-                m_dirWatcher->addDir(path);
-                m_watchedDirs.insert(path);
-            }
+            m_directoryContentsCounter->scanDirectory(path);
         } else if (getSizeRole) {
             data.insert("size", -1); // -1 indicates an unknown number of items
         }
@@ -1185,93 +1078,35 @@ QHash<QByteArray, QVariant> KFileItemModelRolesUpdater::rolesData(const KFileIte
         data.insert("type", item.mimeComment());
     }
 
-    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();
-            }
+    QStringList overlays = item.overlays();
+    foreach(KOverlayIconPlugin *it, m_overlayIconsPlugin) {
+        overlays.append(it->getOverlays(item.url()));
+    }
+    data.insert("iconOverlays", overlays);
 
-            m_nepomukUriItems.insert(uri, item.url());
-        }
+#ifdef HAVE_BALOO
+    if (m_balooFileMonitor) {
+        m_balooFileMonitor->addFile(item.localPath());
+        applyChangedBalooRolesForItem(item);
     }
 #endif
-
     return data;
 }
 
-int KFileItemModelRolesUpdater::subItemsCount(const QString& path) const
+void KFileItemModelRolesUpdater::slotOverlaysChanged(const QUrl& url, const QStringList &)
 {
-    const bool countHiddenFiles = m_model->showHiddenFiles();
-    const bool showFoldersOnly  = m_model->showDirectoriesOnly();
-
-#ifdef Q_WS_WIN
-    QDir dir(path);
-    QDir::Filters filters = QDir::NoDotAndDotDot | QDir::System;
-    if (countHiddenFiles) {
-        filters |= QDir::Hidden;
-    }
-    if (showFoldersOnly) {
-        filters |= QDir::Dirs;
-    } else {
-        filters |= QDir::AllEntries;
+    const KFileItem item = m_model->fileItem(url);
+    if (item.isNull()) {
+        return;
     }
-    return dir.entryList(filters).count();
-#else
-    // Taken from kdelibs/kio/kio/kdirmodel.cpp
-    // Copyright (C) 2006 David Faure <faure@kde.org>
-
-    int count = -1;
-    DIR* dir = ::opendir(QFile::encodeName(path));
-    if (dir) {  // krazy:exclude=syscalls
-        count = 0;
-        struct dirent *dirEntry = 0;
-        while ((dirEntry = ::readdir(dir))) {
-            if (dirEntry->d_name[0] == '.') {
-                if (dirEntry->d_name[1] == '\0' || !countHiddenFiles) {
-                    // Skip "." or hidden files
-                    continue;
-                }
-                if (dirEntry->d_name[1] == '.' && dirEntry->d_name[2] == '\0') {
-                    // Skip ".."
-                    continue;
-                }
-            }
-
-            // 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;
-            }
-        }
-        ::closedir(dir);
+    const int index = m_model->index(item);
+    QHash<QByteArray, QVariant> data =  m_model->data(index);
+    QStringList overlays = item.overlays();
+    foreach (KOverlayIconPlugin *it, m_overlayIconsPlugin) {
+        overlays.append(it->getOverlays(url));
     }
-    return count;
-#endif
+    data.insert("iconOverlays", overlays);
+    m_model->setData(index, data);
 }
 
 void KFileItemModelRolesUpdater::updateAllPreviews()
@@ -1287,14 +1122,14 @@ void KFileItemModelRolesUpdater::updateAllPreviews()
 void KFileItemModelRolesUpdater::killPreviewJob()
 {
     if (m_previewJob) {
-        disconnect(m_previewJob,  SIGNAL(gotPreview(KFileItem,QPixmap)),
-                   this, SLOT(slotGotPreview(KFileItem,QPixmap)));
-        disconnect(m_previewJob,  SIGNAL(failed(KFileItem)),
-                   this, SLOT(slotPreviewFailed(KFileItem)));
-        disconnect(m_previewJob,  SIGNAL(finished(KJob*)),
-                   this, SLOT(slotPreviewJobFinished()));
+        disconnect(m_previewJob,  &KIO::PreviewJob::gotPreview,
+                   this, &KFileItemModelRolesUpdater::slotGotPreview);
+        disconnect(m_previewJob,  &KIO::PreviewJob::failed,
+                   this, &KFileItemModelRolesUpdater::slotPreviewFailed);
+        disconnect(m_previewJob,  &KIO::PreviewJob::finished,
+                   this, &KFileItemModelRolesUpdater::slotPreviewJobFinished);
         m_previewJob->kill();
-        m_previewJob = 0;
+        m_previewJob = nullptr;
         m_pendingPreviewItems.clear();
     }
 }
@@ -1313,7 +1148,7 @@ QList<int> KFileItemModelRolesUpdater::indexesToResolve() const
 
     // We need a reasonable upper limit for number of items to resolve after
     // and before the visible range. m_maximumVisibleItems can be quite large
-    // when using Compace View.
+    // when using Compact View.
     const int readAheadItems = qMin(ReadAheadPages * m_maximumVisibleItems, ResolveAllItemsLimit / 2);
 
     // Add items after the visible range.
@@ -1356,4 +1191,3 @@ QList<int> KFileItemModelRolesUpdater::indexesToResolve() const
     return result;
 }
 
-#include "kfileitemmodelrolesupdater.moc"