1 /***************************************************************************
2 * Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
4 * This program is free software; you can redistribute it and/or modify *
5 * it under the terms of the GNU General Public License as published by *
6 * the Free Software Foundation; either version 2 of the License, or *
7 * (at your option) any later version. *
9 * This program is distributed in the hope that it will be useful, *
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
12 * GNU General Public License for more details. *
14 * You should have received a copy of the GNU General Public License *
15 * along with this program; if not, write to the *
16 * Free Software Foundation, Inc., *
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
18 ***************************************************************************/
20 #ifndef KFILEITEMMODEL_H
21 #define KFILEITEMMODEL_H
23 #include <libdolphin_export.h>
24 #include <KFileItemList>
26 #include <kitemviews/kitemmodelbase.h>
27 #include <kitemviews/private/kfileitemmodelfilter.h>
31 class KFileItemModelDirLister
;
35 * @brief KItemModelBase implementation for KFileItems.
37 * Allows to load items of a directory. Sorting and grouping of
38 * items are supported. Roles that are not part of KFileItem can
39 * be added with KFileItemModel::setData().
41 * Recursive expansion of sub-directories is supported by
42 * KFileItemModel::setExpanded().
44 class LIBDOLPHINPRIVATE_EXPORT KFileItemModel
: public KItemModelBase
49 explicit KFileItemModel(QObject
* parent
= 0);
50 virtual ~KFileItemModel();
53 * Loads the directory specified by \a url. The signals
54 * directoryLoadingStarted(), directoryLoadingProgress() and directoryLoadingCompleted()
55 * indicate the current state of the loading process. The items
56 * of the directory are added after the loading has been completed.
58 void loadDirectory(const KUrl
& url
);
61 * Throws away all currently loaded items and refreshes the directory
62 * by reloading all items again.
64 void refreshDirectory(const KUrl
& url
);
67 * @return Parent directory of the items that are shown. In case
68 * if a directory tree is shown, KFileItemModel::dir() returns
69 * the root-parent of all items.
72 KUrl
directory() const;
75 * Cancels the loading of a directory which has been started by either
76 * loadDirectory() or refreshDirectory().
78 void cancelDirectoryLoading();
80 virtual int count() const;
81 virtual QHash
<QByteArray
, QVariant
> data(int index
) const;
82 virtual bool setData(int index
, const QHash
<QByteArray
, QVariant
>& values
);
85 * Sets a separate sorting with directories first (true) or a mixed
86 * sorting of files and directories (false).
88 void setSortDirectoriesFirst(bool dirsFirst
);
89 bool sortDirectoriesFirst() const;
91 void setShowHiddenFiles(bool show
);
92 bool showHiddenFiles() const;
95 * If set to true, only directories are shown as items of the model. Files
98 void setShowDirectoriesOnly(bool enabled
);
99 bool showDirectoriesOnly() const;
102 virtual QMimeData
* createMimeData(const QSet
<int>& indexes
) const;
105 virtual int indexForKeyboardSearch(const QString
& text
, int startFromIndex
= 0) const;
108 virtual bool supportsDropping(int index
) const;
111 virtual QString
roleDescription(const QByteArray
& typeForRole
) const;
114 virtual QList
<QPair
<int, QVariant
> > groups() const;
117 * @return The file-item for the index \a index. If the index is in a valid
118 * range it is assured that the file-item is not null. The runtime
119 * complexity of this call is O(1).
121 KFileItem
fileItem(int index
) const;
124 * @return The file-item for the url \a url. If no file-item with the given
125 * URL is found KFileItem::isNull() will be true for the returned
126 * file-item. The runtime complexity of this call is O(1).
128 KFileItem
fileItem(const KUrl
& url
) const;
131 * @return The index for the file-item \a item. -1 is returned if no file-item
132 * is found or if the file-item is null. The runtime
133 * complexity of this call is O(1).
135 int index(const KFileItem
& item
) const;
138 * @return The index for the URL \a url. -1 is returned if no file-item
139 * is found. The runtime complexity of this call is O(1).
141 int index(const KUrl
& url
) const;
144 * @return Root item of all items representing the item
145 * for KFileItemModel::dir().
147 KFileItem
rootItem() const;
150 * Clears all items of the model.
155 * Sets the roles that should be shown for each item.
157 void setRoles(const QSet
<QByteArray
>& roles
);
158 QSet
<QByteArray
> roles() const;
160 virtual bool setExpanded(int index
, bool expanded
);
161 virtual bool isExpanded(int index
) const;
162 virtual bool isExpandable(int index
) const;
163 virtual int expandedParentsCount(int index
) const;
165 QSet
<KUrl
> expandedDirectories() const;
168 * Marks the URLs in \a urls as sub-directories which were expanded previously.
169 * After calling loadDirectory() or refreshDirectory() the marked sub-directories
170 * will be expanded step-by-step.
172 void restoreExpandedDirectories(const QSet
<KUrl
>& urls
);
175 * Expands all parent-directories of the item \a url.
177 void expandParentDirectories(const KUrl
& url
);
179 void setNameFilter(const QString
& nameFilter
);
180 QString
nameFilter() const;
186 bool requiresNepomuk
;
187 bool requiresIndexer
;
191 * @return Provides static information for all available roles that
192 * are supported by KFileItemModel. Some roles can only be
193 * determined if Nepomuk is enabled and/or the Nepomuk
194 * indexing is enabled.
196 static QList
<RoleInfo
> rolesInformation();
200 * Is emitted if the loading of a directory has been started. It is
201 * assured that a signal directoryLoadingCompleted() will be send after
202 * the loading has been finished. For tracking the loading progress
203 * the signal directoryLoadingProgress() gets emitted in between.
205 void directoryLoadingStarted();
208 * Is emitted after the loading of a directory has been completed or new
209 * items have been inserted to an already loaded directory. Usually
210 * one or more itemsInserted() signals are emitted before loadingCompleted()
211 * (the only exception is loading an empty directory, where only a
212 * loadingCompleted() signal gets emitted).
214 void directoryLoadingCompleted();
217 * Informs about the progress in percent when loading a directory. It is assured
218 * that the signal directoryLoadingStarted() has been emitted before.
220 void directoryLoadingProgress(int percent
);
223 * Is emitted if the sort-role gets resolved asynchronously and provides
224 * the progress-information of the sorting in percent. It is assured
225 * that the last sortProgress-signal contains 100 as value.
227 void directorySortingProgress(int percent
);
230 * Is emitted if an information message (e.g. "Connecting to host...")
233 void infoMessage(const QString
& message
);
236 * Is emitted if an error message (e.g. "Unknown location")
239 void errorMessage(const QString
& message
);
242 * Is emitted if a redirection from the current URL \a oldUrl
243 * to the new URL \a newUrl has been done.
245 void directoryRedirection(const KUrl
& oldUrl
, const KUrl
& newUrl
);
248 virtual void onGroupedSortingChanged(bool current
);
249 virtual void onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
);
250 virtual void onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
);
254 * Resorts all items dependent on the set sortRole(), sortOrder()
255 * and foldersFirst() settings.
257 void resortAllItems();
259 void slotCompleted();
261 void slotNewItems(const KFileItemList
& items
);
262 void slotItemsDeleted(const KFileItemList
& items
);
263 void slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
);
265 void slotClear(const KUrl
& url
);
266 void slotNaturalSortingChanged();
268 void dispatchPendingItemsToInsert();
272 // User visible roles:
273 NoRole
, NameRole
, SizeRole
, DateRole
, PermissionsRole
, OwnerRole
,
274 GroupRole
, TypeRole
, DestinationRole
, PathRole
,
275 // User visible roles available with Nepomuk:
276 CommentRole
, TagsRole
, RatingRole
, ImageSizeRole
, OrientationRole
,
277 WordCountRole
, LineCountRole
, ArtistRole
, AlbumRole
, DurationRole
, TrackRole
,
279 // Non-visible roles:
280 IsDirRole
, IsExpandedRole
, IsExpandableRole
, ExpandedParentsCountRole
,
281 // Mandatory last entry:
288 QHash
<QByteArray
, QVariant
> values
;
292 void insertItems(const KFileItemList
& items
);
293 void removeItems(const KFileItemList
& items
);
296 * Helper method for insertItems() and removeItems(): Creates
297 * a list of ItemData elements based on the given items.
298 * Note that the ItemData instances are created dynamically and
299 * must be deleted by the caller.
301 QList
<ItemData
*> createItemDataList(const KFileItemList
& items
) const;
303 void removeExpandedItems();
306 * Resets all values from m_requestRole to false.
311 * @return Role-type for the given role.
312 * Runtime complexity is O(1).
314 RoleType
typeForRole(const QByteArray
& role
) const;
317 * @return Role-byte-array for the given role-type.
318 * Runtime complexity is O(1).
320 QByteArray
roleForType(RoleType roleType
) const;
322 QHash
<QByteArray
, QVariant
> retrieveData(const KFileItem
& item
) const;
325 * @return True if the item-data \a a should be ordered before the item-data
326 * \b. The item-data may have different parent-items.
328 bool lessThan(const ItemData
* a
, const ItemData
* b
) const;
331 * Helper method for lessThan() and expandedParentsCountCompare(): Compares
332 * the passed item-data using m_sortRole as criteria. Both items must
333 * have the same parent item, otherwise the comparison will be wrong.
335 int sortRoleCompare(const ItemData
* a
, const ItemData
* b
) const;
337 int stringCompare(const QString
& a
, const QString
& b
) const;
340 * Compares the expansion level of both items. The "expansion level" is defined
341 * by the number of parent directories. However simply comparing just the numbers
342 * is not sufficient, it is also important to check the hierarchy for having
343 * a correct order like shown in a tree.
345 int expandedParentsCountCompare(const ItemData
* a
, const ItemData
* b
) const;
348 * Helper method for expandedParentsCountCompare().
350 QString
subPath(const KFileItem
& item
,
351 const QString
& itemPath
,
355 bool useMaximumUpdateInterval() const;
357 QList
<QPair
<int, QVariant
> > nameRoleGroups() const;
358 QList
<QPair
<int, QVariant
> > sizeRoleGroups() const;
359 QList
<QPair
<int, QVariant
> > dateRoleGroups() const;
360 QList
<QPair
<int, QVariant
> > permissionRoleGroups() const;
361 QList
<QPair
<int, QVariant
> > ratingRoleGroups() const;
362 QList
<QPair
<int, QVariant
> > genericStringRoleGroups(const QByteArray
& typeForRole
) const;
365 * Helper method for all xxxRoleGroups() methods to check whether the
366 * item with the given index is a child-item. A child-item is defined
367 * as item having an expansion-level > 0. All xxxRoleGroups() methods
368 * should skip the grouping if the item is a child-item (although
369 * KItemListView would be capable to show sub-groups in groups this
370 * results in visual clutter for most usecases).
372 bool isChildItem(int index
) const;
375 * @return Recursive list of child items that have \a item as upper most parent.
377 KFileItemList
childItems(const KFileItem
& item
) const;
380 * Is invoked by KFileItemModelRolesUpdater and results in emitting the
381 * sortProgress signal with a percent-value of the progress.
383 void emitSortProgress(int resolvedCount
);
386 * Maps the QByteArray-roles to RoleTypes and provides translation- and
391 const char* const role
;
392 const RoleType roleType
;
393 const char* const roleTranslationContext
;
394 const char* const roleTranslation
;
395 const char* const groupTranslationContext
;
396 const char* const groupTranslation
;
397 const bool requiresNepomuk
;
398 const bool requiresIndexer
;
402 * @return Map of user visible roles that are accessible by KFileItemModel::rolesInformation().
404 static const RoleInfoMap
* rolesInfoMap(int& count
);
407 * Determines the MIME-types of all items that can be done within
410 static void determineMimeTypes(const KFileItemList
& items
, int timeout
);
413 KFileItemModelDirLister
* m_dirLister
;
415 bool m_naturalSorting
;
416 bool m_sortDirsFirst
;
419 int m_sortingProgressPercent
; // Value of directorySortingProgress() signal
420 QSet
<QByteArray
> m_roles
;
421 Qt::CaseSensitivity m_caseSensitivity
;
423 QList
<ItemData
*> m_itemData
;
424 QHash
<KUrl
, int> m_items
; // Allows O(1) access for KFileItemModel::index(const KFileItem& item)
426 KFileItemModelFilter m_filter
;
427 QSet
<KFileItem
> m_filteredItems
; // Items that got hidden by KFileItemModel::setNameFilter()
429 bool m_requestRole
[RolesCount
];
431 QTimer
* m_maximumUpdateIntervalTimer
;
432 QTimer
* m_resortAllItemsTimer
;
433 KFileItemList m_pendingItemsToInsert
;
435 // Cache for KFileItemModel::groups()
436 mutable QList
<QPair
<int, QVariant
> > m_groups
;
438 // Stores the smallest expansion level of the root-URL. Is required to calculate
439 // the "expandedParentsCount" role in an efficient way. A value < 0 indicates a
441 enum ExpandedParentsCountRootTypes
443 // m_expandedParentsCountRoot is uninitialized and must be determined by checking
444 // the root URL from the KDirLister.
445 UninitializedExpandedParentsCountRoot
= -1,
446 // All items should be forced to get an expanded parents count of 0 even if they
447 // represent child items. This is useful for slaves that provide no parent items
448 // for child items like e.g. the search IO slaves.
449 ForceExpandedParentsCountRoot
= -2
451 mutable int m_expandedParentsCountRoot
;
453 // Stores the URLs of the expanded directories.
454 QSet
<KUrl
> m_expandedDirs
;
456 // URLs that must be expanded. The expanding is initially triggered in setExpanded()
457 // and done step after step in slotCompleted().
458 QSet
<KUrl
> m_urlsToExpand
;
460 friend class KFileItemModelSortAlgorithm
; // Accesses lessThan() method
461 friend class KFileItemModelRolesUpdater
; // Accesses emitSortProgress() method
462 friend class KFileItemModelTest
; // For unit testing
465 inline bool KFileItemModel::isChildItem(int index
) const
467 return m_requestRole
[ExpandedParentsCountRole
] && m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt() > 0;