]> cloud.milkyroute.net Git - dolphin.git/blobdiff - src/kitemviews/kfileitemmodel.h
Merge remote-tracking branch 'origin/KDE/4.12'
[dolphin.git] / src / kitemviews / kfileitemmodel.h
index 05834cd31befd03f7113c67c00fa5d60ccf57256..0224290238b6a2d77741b625c0d7212ba080baa9 100644 (file)
@@ -27,6 +27,7 @@
 #include <kitemviews/private/kfileitemmodelfilter.h>
 
 #include <QHash>
+#include <QSet>
 
 class KFileItemModelDirLister;
 class QTimer;
@@ -34,13 +35,11 @@ class QTimer;
 /**
  * @brief KItemModelBase implementation for KFileItems.
  *
- * KFileItemModel is connected with one KDirLister. Each time the KDirLister
- * emits new items, removes items or changes items the model gets synchronized.
+ * Allows to load items of a directory. Sorting and grouping of
+ * items are supported. Roles that are not part of KFileItem can
+ * be added with KFileItemModel::setData().
  *
- * KFileItemModel supports sorting and grouping of items. Additional roles that
- * are not part of KFileItem can be added with KFileItemModel::setData().
- *
- * Also the recursive expansion of sub-directories is supported by
+ * Recursive expansion of sub-directories is supported by
  * KFileItemModel::setExpanded().
  */
 class LIBDOLPHINPRIVATE_EXPORT KFileItemModel : public KItemModelBase
@@ -53,17 +52,17 @@ public:
 
     /**
      * Loads the directory specified by \a url. The signals
-     * dirLoadingStarted(), dirLoadingProgress() and dirLoadingCompleted()
+     * directoryLoadingStarted(), directoryLoadingProgress() and directoryLoadingCompleted()
      * indicate the current state of the loading process. The items
      * of the directory are added after the loading has been completed.
      */
-    void loadDir(const KUrl& url);
+    void loadDirectory(const KUrl& url);
 
     /**
      * Throws away all currently loaded items and refreshes the directory
      * by reloading all items again.
      */
-    void refreshDir(const KUrl& url);
+    void refreshDirectory(const KUrl& url);
 
     /**
      * @return Parent directory of the items that are shown. In case
@@ -71,30 +70,37 @@ public:
      *         the root-parent of all items.
      * @see rootItem()
      */
-    KUrl dir() const;
+    KUrl directory() const;
+
+    /**
+     * Cancels the loading of a directory which has been started by either
+     * loadDirectory() or refreshDirectory().
+     */
+    void cancelDirectoryLoading();
 
     virtual int count() const;
     virtual QHash<QByteArray, QVariant> data(int index) const;
     virtual bool setData(int index, const QHash<QByteArray, QVariant>& values);
 
     /**
-     * Sets a separate sorting with folders first (true) or a mixed sorting of files and folders (false).
+     * Sets a separate sorting with directories first (true) or a mixed
+     * sorting of files and directories (false).
      */
-    void setSortFoldersFirst(bool foldersFirst);
-    bool sortFoldersFirst() const;
+    void setSortDirectoriesFirst(bool dirsFirst);
+    bool sortDirectoriesFirst() const;
 
     void setShowHiddenFiles(bool show);
     bool showHiddenFiles() const;
 
     /**
-     * If set to true, only folders are shown as items of the model. Files
+     * If set to true, only directories are shown as items of the model. Files
      * are ignored.
      */
-    void setShowFoldersOnly(bool enabled);
-    bool showFoldersOnly() const;
+    void setShowDirectoriesOnly(bool enabled);
+    bool showDirectoriesOnly() const;
 
     /** @reimp */
-    virtual QMimeData* createMimeData(const QSet<int>& indexes) const;
+    virtual QMimeData* createMimeData(const KItemSet& indexes) const;
 
     /** @reimp */
     virtual int indexForKeyboardSearch(const QString& text, int startFromIndex = 0) const;
@@ -103,7 +109,7 @@ public:
     virtual bool supportsDropping(int index) const;
 
     /** @reimp */
-    virtual QString roleDescription(const QByteArray& typeForRole) const;
+    virtual QString roleDescription(const QByteArray& role) const;
 
     /** @reimp */
     virtual QList<QPair<int, QVariant> > groups() const;
@@ -146,7 +152,9 @@ public:
      */
     void clear();
 
-    // TODO: "name" + "isDir" is default in ctor
+    /**
+     * Sets the roles that should be shown for each item.
+     */
     void setRoles(const QSet<QByteArray>& roles);
     QSet<QByteArray> roles() const;
 
@@ -155,24 +163,25 @@ public:
     virtual bool isExpandable(int index) const;
     virtual int expandedParentsCount(int index) const;
 
-    QSet<KUrl> expandedUrls() const;
+    QSet<KUrl> expandedDirectories() const;
 
     /**
-     * Marks the URLs in \a urls as subfolders which were expanded previously.
-     * They are re-expanded one by one each time the KDirLister's completed() signal is received.
-     * Note that a manual triggering of the KDirLister is required.
+     * 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 restoreExpandedUrls(const QSet<KUrl>& urls);
+    void restoreExpandedDirectories(const QSet<KUrl>& urls);
 
     /**
-     * Expands all parent-items of \a url.
+     * Expands all parent-directories of the item \a url.
      */
-    void expandParentItems(const KUrl& url);
+    void expandParentDirectories(const KUrl& url);
 
     void setNameFilter(const QString& nameFilter);
     QString nameFilter() const;
 
-    void cancelDirLoading();
+    void setMimeTypeFilters(const QStringList& filters);
+    QStringList mimeTypeFilters() const;
 
     struct RoleInfo
     {   QByteArray role;
@@ -193,11 +202,11 @@ public:
 signals:
     /**
      * Is emitted if the loading of a directory has been started. It is
-     * assured that a signal dirLoadingCompleted() will be send after
+     * assured that a signal directoryLoadingCompleted() will be send after
      * the loading has been finished. For tracking the loading progress
-     * the signal dirLoadingProgress() gets emitted in between.
+     * the signal directoryLoadingProgress() gets emitted in between.
      */
-    void dirLoadingStarted();
+    void directoryLoadingStarted();
 
     /**
      * Is emitted after the loading of a directory has been completed or new
@@ -206,20 +215,25 @@ signals:
      * (the only exception is loading an empty directory, where only a
      * loadingCompleted() signal gets emitted).
      */
-    void dirLoadingCompleted();
+    void directoryLoadingCompleted();
+
+    /**
+     * Is emitted after the loading of a directory has been canceled.
+     */
+    void directoryLoadingCanceled();
 
     /**
      * Informs about the progress in percent when loading a directory. It is assured
-     * that the signal dirLoadingStarted() has been emitted before.
+     * that the signal directoryLoadingStarted() has been emitted before.
      */
-    void dirLoadingProgress(int percent);
+    void directoryLoadingProgress(int percent);
 
     /**
      * Is emitted if the sort-role gets resolved asynchronously and provides
      * the progress-information of the sorting in percent. It is assured
      * that the last sortProgress-signal contains 100 as value.
      */
-    void dirSortingProgress(int percent);
+    void directorySortingProgress(int percent);
 
     /**
      * Is emitted if an information message (e.g. "Connecting to host...")
@@ -237,7 +251,13 @@ signals:
      * Is emitted if a redirection from the current URL \a oldUrl
      * to the new URL \a newUrl has been done.
      */
-    void redirection(const KUrl& oldUrl, const KUrl& newUrl);
+    void directoryRedirection(const KUrl& oldUrl, const KUrl& 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);
 
 protected:
     virtual void onGroupedSortingChanged(bool current);
@@ -253,7 +273,7 @@ private slots:
 
     void slotCompleted();
     void slotCanceled();
-    void slotNewItems(const KFileItemList& items);
+    void slotItemsAdded(const KUrl& directoryUrl, const KFileItemList& items);
     void slotItemsDeleted(const KFileItemList& items);
     void slotRefreshItems(const QList<QPair<KFileItem, KFileItem> >& items);
     void slotClear();
@@ -272,7 +292,7 @@ private:
         WordCountRole, LineCountRole, ArtistRole, AlbumRole, DurationRole, TrackRole,
         CopiedFromRole,
         // Non-visible roles:
-        IsDirRole, IsExpandedRole, IsExpandableRole, ExpandedParentsCountRole,
+        IsDirRole, IsLinkRole, IsExpandedRole, IsExpandableRole, ExpandedParentsCountRole,
         // Mandatory last entry:
         RolesCount
     };
@@ -284,8 +304,13 @@ private:
         ItemData* parent;
     };
 
-    void insertItems(const KFileItemList& items);
-    void removeItems(const KFileItemList& items);
+    enum RemoveItemsBehavior {
+        KeepItemData,
+        DeleteItemData
+    };
+
+    void insertItems(QList<ItemData*>& items);
+    void removeItems(const KItemRangeList& itemRanges, RemoveItemsBehavior behavior);
 
     /**
      * Helper method for insertItems() and removeItems(): Creates
@@ -293,10 +318,26 @@ private:
      * Note that the ItemData instances are created dynamically and
      * must be deleted by the caller.
      */
-    QList<ItemData*> createItemDataList(const KFileItemList& items) const;
+    QList<ItemData*> createItemDataList(const KUrl& 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);
 
     void removeExpandedItems();
 
+    /**
+     * This function is called by setData() and slotRefreshItems(). It emits
+     * the itemsChanged() signal, checks if the sort order is still correct,
+     * and starts m_resortAllItemsTimer if that is not the case.
+     */
+    void emitItemsChangedAndTriggerResorting(const KItemRangeList& itemRanges, const QSet<QByteArray>& changedRoles);
+
     /**
      * Resets all values from m_requestRole to false.
      */
@@ -314,7 +355,13 @@ private:
      */
     QByteArray roleForType(RoleType roleType) const;
 
-    QHash<QByteArray, QVariant> retrieveData(const KFileItem& item) const;
+    QHash<QByteArray, QVariant> retrieveData(const KFileItem& item, const ItemData* parent) const;
+
+    /**
+     * @return True if \a a has a KFileItem whose text is 'less than' the one
+     *         of \a b according to QString::operator<(const QString&).
+     */
+    static bool nameLessThan(const ItemData* a, const ItemData* b);
 
     /**
      * @return True if the item-data \a a should be ordered before the item-data
@@ -322,6 +369,12 @@ private:
      */
     bool lessThan(const ItemData* a, const ItemData* b) 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;
+
     /**
      * Helper method for lessThan() and expandedParentsCountCompare(): Compares
      * the passed item-data using m_sortRole as criteria. Both items must
@@ -331,22 +384,6 @@ private:
 
     int stringCompare(const QString& a, const QString& b) const;
 
-    /**
-     * Compares the expansion level of both items. The "expansion level" is defined
-     * by the number of parent directories. However simply comparing just the numbers
-     * is not sufficient, it is also important to check the hierarchy for having
-     * a correct order like shown in a tree.
-     */
-    int expandedParentsCountCompare(const ItemData* a, const ItemData* b) const;
-
-    /**
-     * Helper method for expandedParentsCountCompare().
-     */
-    QString subPath(const KFileItem& item,
-                    const QString& itemPath,
-                    int start,
-                    bool* isDir) const;
-
     bool useMaximumUpdateInterval() const;
 
     QList<QPair<int, QVariant> > nameRoleGroups() const;
@@ -366,17 +403,23 @@ private:
      */
     bool isChildItem(int index) const;
 
-    /**
-     * @return Recursive list of child items that have \a item as upper most parent.
-     */
-    KFileItemList childItems(const KFileItem& item) const;
-
     /**
      * Is invoked by KFileItemModelRolesUpdater and results in emitting the
      * sortProgress signal with a percent-value of the progress.
      */
     void emitSortProgress(int resolvedCount);
 
+    /**
+     * Applies the filters set through @ref setNameFilter and @ref setMimeTypeFilters.
+     */
+    void applyFilters();
+
+    /**
+     * Removes filtered items whose expanded parents have been deleted
+     * or collapsed via setExpanded(parentIndex, false).
+     */
+    void removeFilteredChildren(const KItemRangeList& parents);
+
     /**
      * Maps the QByteArray-roles to RoleTypes and provides translation- and
      * group-contexts.
@@ -404,14 +447,25 @@ private:
      */
     static void determineMimeTypes(const KFileItemList& items, int timeout);
 
+    /**
+     * @return Returns a copy of \a value that is implicitly shared
+     * with other users to save memory.
+     */
+    static QByteArray sharedValue(const QByteArray& value);
+
+    /**
+     * Checks if the model's internal data structures are consistent.
+     */
+    bool isConsistent() const;
+
 private:
     KFileItemModelDirLister* m_dirLister;
 
     bool m_naturalSorting;
-    bool m_sortFoldersFirst;
+    bool m_sortDirsFirst;
 
     RoleType m_sortRole;
-    int m_sortingProgressPercent; // Value of dirSortingProgress() signal
+    int m_sortingProgressPercent; // Value of directorySortingProgress() signal
     QSet<QByteArray> m_roles;
     Qt::CaseSensitivity m_caseSensitivity;
 
@@ -419,47 +473,45 @@ private:
     QHash<KUrl, int> m_items; // Allows O(1) access for KFileItemModel::index(const KFileItem& item)
 
     KFileItemModelFilter m_filter;
-    QSet<KFileItem> m_filteredItems; // Items that got hidden by KFileItemModel::setNameFilter()
+    QHash<KFileItem, ItemData*> m_filteredItems; // Items that got hidden by KFileItemModel::setNameFilter()
 
     bool m_requestRole[RolesCount];
 
     QTimer* m_maximumUpdateIntervalTimer;
     QTimer* m_resortAllItemsTimer;
-    KFileItemList m_pendingItemsToInsert;
+    QList<ItemData*> m_pendingItemsToInsert;
 
     // Cache for KFileItemModel::groups()
     mutable QList<QPair<int, QVariant> > m_groups;
 
-    // Stores the smallest expansion level of the root-URL. Is required to calculate
-    // the "expandedParentsCount" role in an efficient way. A value < 0 indicates a
-    // special meaning:
-    enum ExpandedParentsCountRootTypes
-    {
-        // m_expandedParentsCountRoot is uninitialized and must be determined by checking
-        // the root URL from the KDirLister.
-        UninitializedExpandedParentsCountRoot = -1,
-        // All items should be forced to get an expanded parents count of 0 even if they
-        // represent child items. This is useful for slaves that provide no parent items
-        // for child items like e.g. the search IO slaves.
-        ForceExpandedParentsCountRoot = -2
-    };
-    mutable int m_expandedParentsCountRoot;
-
-    // Stores the URLs of the expanded folders.
-    QSet<KUrl> m_expandedUrls;
+    // Stores the URLs (key: target url, value: url) of the expanded directories.
+    QHash<KUrl, KUrl> 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;
 
-    friend class KFileItemModelSortAlgorithm;  // Accesses lessThan() method
+    friend class KFileItemModelLessThan;       // Accesses lessThan() method
     friend class KFileItemModelRolesUpdater;   // Accesses emitSortProgress() method
     friend class KFileItemModelTest;           // For unit testing
+    friend class KFileItemModelBenchmark;      // For unit testing
+    friend class KFileItemListViewTest;        // For unit testing
+    friend class DolphinPart;                  // Accesses m_dirLister
 };
 
+inline bool KFileItemModel::nameLessThan(const ItemData* a, const ItemData* b)
+{
+    return a->item.text() < b->item.text();
+}
+
+
 inline bool KFileItemModel::isChildItem(int index) const
 {
-    return m_requestRole[ExpandedParentsCountRole] && m_itemData.at(index)->values.value("expandedParentsCount").toInt() > 0;
+    if (m_itemData.at(index)->parent) {
+        return true;
+    } else {
+        return false;
+    }
 }
 
 #endif