]> cloud.milkyroute.net Git - dolphin.git/blobdiff - src/kitemviews/kfileitemmodel.h
Merge branch 'release/21.08'
[dolphin.git] / src / kitemviews / kfileitemmodel.h
index c57329fc85051b153f0430e327bc2cdc1dccfded..3602c16c12227f6a250561d60d67ca29e0d64744 100644 (file)
@@ -1,37 +1,33 @@
-/***************************************************************************
- *   Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com>             *
- *                                                                         *
- *   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            *
- ***************************************************************************/
+/*
+ * SPDX-FileCopyrightText: 2011 Peter Penz <peter.penz19@gmail.com>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
 
 #ifndef KFILEITEMMODEL_H
 #define KFILEITEMMODEL_H
 
-#include <libdolphin_export.h>
-#include <KFileItemList>
-#include <KUrl>
-#include <kitemviews/kitemmodelbase.h>
-#include <kitemviews/private/kfileitemmodelfilter.h>
+#include "dolphin_export.h"
+#include "kitemviews/kitemmodelbase.h"
+#include "kitemviews/private/kfileitemmodelfilter.h"
 
+#include <KFileItem>
+
+#include <QCollator>
 #include <QHash>
 #include <QSet>
+#include <QUrl>
+
+#include <functional>
+
+class KDirLister;
 
-class KFileItemModelDirLister;
 class QTimer;
 
+namespace KIO {
+    class Job;
+}
+
 /**
  * @brief KItemModelBase implementation for KFileItems.
  *
@@ -42,13 +38,13 @@ class QTimer;
  * Recursive expansion of sub-directories is supported by
  * KFileItemModel::setExpanded().
  */
-class LIBDOLPHINPRIVATE_EXPORT KFileItemModel : public KItemModelBase
+class DOLPHIN_EXPORT KFileItemModel : public KItemModelBase
 {
     Q_OBJECT
 
 public:
-    explicit KFileItemModel(QObject* parent = 0);
-    virtual ~KFileItemModel();
+    explicit KFileItemModel(QObject* parent = nullptr);
+    ~KFileItemModel() override;
 
     /**
      * Loads the directory specified by \a url. The signals
@@ -56,13 +52,13 @@ public:
      * indicate the current state of the loading process. The items
      * of the directory are added after the loading has been completed.
      */
-    void loadDirectory(const KUrl& url);
+    void loadDirectory(const QUrl& url);
 
     /**
      * Throws away all currently loaded items and refreshes the directory
      * by reloading all items again.
      */
-    void refreshDirectory(const KUrl& url);
+    void refreshDirectory(const QUrl& url);
 
     /**
      * @return Parent directory of the items that are shown. In case
@@ -70,7 +66,7 @@ public:
      *         the root-parent of all items.
      * @see rootItem()
      */
-    KUrl directory() const;
+    QUrl directory() const override;
 
     /**
      * Cancels the loading of a directory which has been started by either
@@ -78,9 +74,9 @@ public:
      */
     void cancelDirectoryLoading();
 
-    virtual int count() const;
-    virtual QHash<QByteArray, QVariant> data(int index) const;
-    virtual bool setData(int index, const QHash<QByteArray, QVariant>& values);
+    int count() const override;
+    QHash<QByteArray, QVariant> data(int index) const override;
+    bool setData(int index, const QHash<QByteArray, QVariant>& values) override;
 
     /**
      * Sets a separate sorting with directories first (true) or a mixed
@@ -99,20 +95,15 @@ public:
     void setShowDirectoriesOnly(bool enabled);
     bool showDirectoriesOnly() const;
 
-    /** @reimp */
-    virtual QMimeData* createMimeData(const KItemSet& indexes) const;
+    QMimeData* createMimeData(const KItemSet& indexes) const override;
 
-    /** @reimp */
-    virtual int indexForKeyboardSearch(const QString& text, int startFromIndex = 0) const;
+    int indexForKeyboardSearch(const QString& text, int startFromIndex = 0) const override;
 
-    /** @reimp */
-    virtual bool supportsDropping(int index) const;
+    bool supportsDropping(int index) const override;
 
-    /** @reimp */
-    virtual QString roleDescription(const QByteArray& role) const;
+    QString roleDescription(const QByteArray& role) const override;
 
-    /** @reimp */
-    virtual QList<QPair<int, QVariant> > groups() const;
+    QList<QPair<int, QVariant> > groups() const override;
 
     /**
      * @return The file-item for the index \a index. If the index is in a valid
@@ -126,20 +117,20 @@ public:
      *         URL is found KFileItem::isNull() will be true for the returned
      *         file-item. The runtime complexity of this call is O(1).
      */
-    KFileItem fileItem(const KUrl& url) const;
+    KFileItem fileItem(const QUrl& url) const;
 
     /**
      * @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;
+    int index(const QUrl &url) const;
 
     /**
      * @return Root item of all items representing the item
@@ -158,24 +149,24 @@ public:
     void setRoles(const QSet<QByteArray>& roles);
     QSet<QByteArray> roles() const;
 
-    virtual bool setExpanded(int index, bool expanded);
-    virtual bool isExpanded(int index) const;
-    virtual bool isExpandable(int index) const;
-    virtual int expandedParentsCount(int index) const;
+    bool setExpanded(int index, bool expanded) override;
+    bool isExpanded(int index) const override;
+    bool isExpandable(int index) const override;
+    int expandedParentsCount(int index) const override;
 
-    QSet<KUrl> expandedDirectories() const;
+    QSet<QUrl> expandedDirectories() const;
 
     /**
      * Marks the URLs in \a urls as sub-directories which were expanded previously.
      * After calling loadDirectory() or refreshDirectory() the marked sub-directories
      * will be expanded step-by-step.
      */
-    void restoreExpandedDirectories(const QSet<KUrl>& urls);
+    void restoreExpandedDirectories(const QSet<QUrl>& urls);
 
     /**
      * Expands all parent-directories of the item \a url.
      */
-    void expandParentDirectories(const KUrl& url);
+    void expandParentDirectories(const QUrl& url);
 
     void setNameFilter(const QString& nameFilter);
     QString nameFilter() const;
@@ -187,19 +178,19 @@ 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();
 
-signals:
+Q_SIGNALS:
     /**
      * Is emitted if the loading of a directory has been started. It is
      * assured that a signal directoryLoadingCompleted() will be send after
@@ -251,20 +242,26 @@ signals:
      * Is emitted if a redirection from the current URL \a oldUrl
      * to the new URL \a newUrl has been done.
      */
-    void directoryRedirection(const KUrl& oldUrl, const KUrl& newUrl);
+    void directoryRedirection(const QUrl& oldUrl, const QUrl& newUrl);
 
     /**
      * Is emitted when the URL passed by KFileItemModel::setUrl() represents a file.
      * In this case no signal errorMessage() will be emitted.
      */
-    void urlIsFileError(const KUrl& url);
+    void urlIsFileError(const QUrl& url);
+
+    /**
+     * It is emitted for files when they change and
+     * for dirs when files are added or removed.
+     */
+    void fileItemsChanged(const KFileItemList &changedFileItems);
 
 protected:
-    virtual void onGroupedSortingChanged(bool current);
-    virtual void onSortRoleChanged(const QByteArray& current, const QByteArray& previous);
-    virtual void onSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous);
+    void onGroupedSortingChanged(bool current) override;
+    void onSortRoleChanged(const QByteArray& current, const QByteArray& previous, bool resortItems = true) override;
+    void onSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous) override;
 
-private slots:
+private Q_SLOTS:
     /**
      * Resorts all items dependent on the set sortRole(), sortOrder()
      * and foldersFirst() settings.
@@ -273,26 +270,26 @@ private slots:
 
     void slotCompleted();
     void slotCanceled();
-    void slotItemsAdded(const KUrl& directoryUrl, const KFileItemList& items);
+    void slotItemsAdded(const QUrl& directoryUrl, const KFileItemList& items);
     void slotItemsDeleted(const KFileItemList& items);
     void slotRefreshItems(const QList<QPair<KFileItem, KFileItem> >& items);
     void slotClear();
-    void slotClear(const KUrl& url);
-    void slotNaturalSortingChanged();
+    void slotSortingChoiceChanged();
+    void slotListerError(KIO::Job *job);
 
     void dispatchPendingItemsToInsert();
 
 private:
     enum RoleType {
         // User visible roles:
-        NoRole, NameRole, SizeRole, DateRole, PermissionsRole, OwnerRole,
-        GroupRole, TypeRole, DestinationRole, PathRole,
-        // User visible roles available with Nepomuk:
-        CommentRole, TagsRole, RatingRole, ImageSizeRole, OrientationRole,
-        WordCountRole, LineCountRole, ArtistRole, AlbumRole, DurationRole, TrackRole,
-        CopiedFromRole,
+        NoRole, NameRole, SizeRole, ModificationTimeRole, CreationTimeRole, AccessTimeRole, PermissionsRole, OwnerRole,
+        GroupRole, TypeRole, DestinationRole, PathRole, DeletionTimeRole,
+        // User visible roles available with Baloo:
+        CommentRole, TagsRole, RatingRole, WidthRole, HeightRole, ImageDateTimeRole, OrientationRole,
+        WordCountRole, TitleRole, LineCountRole, ArtistRole, GenreRole, AlbumRole, DurationRole, TrackRole, ReleaseYearRole,
+        BitrateRole, OriginUrlRole, AspectRatioRole, FrameRateRole,
         // Non-visible roles:
-        IsDirRole, IsLinkRole, IsExpandedRole, IsExpandableRole, ExpandedParentsCountRole,
+        IsDirRole, IsLinkRole, IsHiddenRole, IsExpandedRole, IsExpandableRole, ExpandedParentsCountRole,
         // Mandatory last entry:
         RolesCount
     };
@@ -318,7 +315,14 @@ private:
      * Note that the ItemData instances are created dynamically and
      * must be deleted by the caller.
      */
-    QList<ItemData*> createItemDataList(const KUrl& parentUrl, const KFileItemList& items) const;
+    QList<ItemData*> createItemDataList(const QUrl& parentUrl, const KFileItemList& items) const;
+
+    /**
+     * Prepares the items for sorting. Normally, the hash 'values' in ItemData is filled
+     * lazily to save time and memory, but for some sort roles, it is expected that the
+     * sort role data is stored in 'values'.
+     */
+    void prepareItemsForSorting(QList<ItemData*>& itemDataList);
 
     static int expandedParentsCount(const ItemData* data);
 
@@ -350,6 +354,11 @@ private:
 
     QHash<QByteArray, QVariant> retrieveData(const KFileItem& item, const ItemData* parent) const;
 
+    /**
+     * @return True if role values benefit from natural or case insensitive sorting.
+     */
+    static bool isRoleValueNatural(const RoleType roleType);
+
     /**
      * @return True if \a a has a KFileItem whose text is 'less than' the one
      *         of \a b according to QString::operator<(const QString&).
@@ -360,28 +369,26 @@ private:
      * @return True if the item-data \a a should be ordered before the item-data
      *         \b. The item-data may have different parent-items.
      */
-    bool lessThan(const ItemData* a, const ItemData* b) const;
+    bool lessThan(const ItemData* a, const ItemData* b, const QCollator& collator) const;
 
     /**
      * Sorts the items between \a begin and \a end using the comparison
      * function lessThan().
      */
-    void sort(QList<ItemData*>::iterator begin, QList<ItemData*>::iterator end) const;
+    void sort(const QList<ItemData*>::iterator &begin, const QList<ItemData*>::iterator &end) const;
 
     /**
      * Helper method for lessThan() and expandedParentsCountCompare(): Compares
      * the passed item-data using m_sortRole as criteria. Both items must
      * have the same parent item, otherwise the comparison will be wrong.
      */
-    int sortRoleCompare(const ItemData* a, const ItemData* b) const;
+    int sortRoleCompare(const ItemData* a, const ItemData* b, const QCollator& collator) const;
 
-    int stringCompare(const QString& a, const QString& b) const;
-
-    bool useMaximumUpdateInterval() const;
+    int stringCompare(const QString& a, const QString& b, const QCollator& collator) const;
 
     QList<QPair<int, QVariant> > nameRoleGroups() const;
     QList<QPair<int, QVariant> > sizeRoleGroups() const;
-    QList<QPair<int, QVariant> > dateRoleGroups() const;
+    QList<QPair<int, QVariant> > timeRoleGroups(const std::function<QDateTime(const ItemData *)> &fileTimeCb) const;
     QList<QPair<int, QVariant> > permissionRoleGroups() const;
     QList<QPair<int, QVariant> > ratingRoleGroups() const;
     QList<QPair<int, QVariant> > genericStringRoleGroups(const QByteArray& typeForRole) const;
@@ -413,6 +420,11 @@ private:
      */
     void removeFilteredChildren(const KItemRangeList& parents);
 
+    /**
+     * Loads the selected choice of sorting method from Dolphin General Settings
+     */
+    void loadSortingSettings();
+
     /**
      * Maps the QByteArray-roles to RoleTypes and provides translation- and
      * group-contexts.
@@ -425,7 +437,7 @@ private:
         const char* const roleTranslation;
         const char* const groupTranslationContext;
         const char* const groupTranslation;
-        const bool requiresNepomuk;
+        const bool requiresBaloo;
         const bool requiresIndexer;
     };
 
@@ -452,18 +464,23 @@ private:
     bool isConsistent() const;
 
 private:
-    KFileItemModelDirLister* m_dirLister;
+    KDirLister *m_dirLister = nullptr;
 
+    QCollator m_collator;
     bool m_naturalSorting;
     bool m_sortDirsFirst;
 
     RoleType m_sortRole;
     int m_sortingProgressPercent; // Value of directorySortingProgress() signal
     QSet<QByteArray> m_roles;
-    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 QUrl&). 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<QUrl, int> m_items;
 
     KFileItemModelFilter m_filter;
     QHash<KFileItem, ItemData*> m_filteredItems; // Items that got hidden by KFileItemModel::setNameFilter()
@@ -478,13 +495,12 @@ private:
     mutable QList<QPair<int, QVariant> > m_groups;
 
     // Stores the URLs (key: target url, value: url) of the expanded directories.
-    QHash<KUrl, KUrl> m_expandedDirs;
+    QHash<QUrl, QUrl> m_expandedDirs;
 
     // URLs that must be expanded. The expanding is initially triggered in setExpanded()
     // and done step after step in slotCompleted().
-    QSet<KUrl> m_urlsToExpand;
+    QSet<QUrl> m_urlsToExpand;
 
-    friend class KFileItemModelLessThan;       // Accesses lessThan() method
     friend class KFileItemModelRolesUpdater;   // Accesses emitSortProgress() method
     friend class KFileItemModelTest;           // For unit testing
     friend class KFileItemModelBenchmark;      // For unit testing
@@ -492,12 +508,27 @@ private:
     friend class DolphinPart;                  // Accesses m_dirLister
 };
 
+inline bool KFileItemModel::isRoleValueNatural(RoleType roleType)
+{
+    return (roleType == TypeRole ||
+            roleType == TagsRole ||
+            roleType == CommentRole ||
+            roleType == TitleRole ||
+            roleType == ArtistRole ||
+            roleType == GenreRole ||
+            roleType == AlbumRole ||
+            roleType == PathRole ||
+            roleType == DestinationRole ||
+            roleType == OriginUrlRole ||
+            roleType == OwnerRole ||
+            roleType == GroupRole);
+}
+
 inline bool KFileItemModel::nameLessThan(const ItemData* a, const ItemData* b)
 {
     return a->item.text() < b->item.text();
 }
 
-
 inline bool KFileItemModel::isChildItem(int index) const
 {
     if (m_itemData.at(index)->parent) {