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>
32 class KFileItemModelDirLister
;
36 * @brief KItemModelBase implementation for KFileItems.
38 * Allows to load items of a directory. Sorting and grouping of
39 * items are supported. Roles that are not part of KFileItem can
40 * be added with KFileItemModel::setData().
42 * Recursive expansion of sub-directories is supported by
43 * KFileItemModel::setExpanded().
45 class LIBDOLPHINPRIVATE_EXPORT KFileItemModel
: public KItemModelBase
50 explicit KFileItemModel(QObject
* parent
= 0);
51 virtual ~KFileItemModel();
54 * Loads the directory specified by \a url. The signals
55 * directoryLoadingStarted(), directoryLoadingProgress() and directoryLoadingCompleted()
56 * indicate the current state of the loading process. The items
57 * of the directory are added after the loading has been completed.
59 void loadDirectory(const KUrl
& url
);
62 * Throws away all currently loaded items and refreshes the directory
63 * by reloading all items again.
65 void refreshDirectory(const KUrl
& url
);
68 * @return Parent directory of the items that are shown. In case
69 * if a directory tree is shown, KFileItemModel::dir() returns
70 * the root-parent of all items.
73 KUrl
directory() const;
76 * Cancels the loading of a directory which has been started by either
77 * loadDirectory() or refreshDirectory().
79 void cancelDirectoryLoading();
81 virtual int count() const;
82 virtual QHash
<QByteArray
, QVariant
> data(int index
) const;
83 virtual bool setData(int index
, const QHash
<QByteArray
, QVariant
>& values
);
86 * Sets a separate sorting with directories first (true) or a mixed
87 * sorting of files and directories (false).
89 void setSortDirectoriesFirst(bool dirsFirst
);
90 bool sortDirectoriesFirst() const;
92 void setShowHiddenFiles(bool show
);
93 bool showHiddenFiles() const;
96 * If set to true, only directories are shown as items of the model. Files
99 void setShowDirectoriesOnly(bool enabled
);
100 bool showDirectoriesOnly() const;
103 virtual QMimeData
* createMimeData(const KItemSet
& indexes
) const;
106 virtual int indexForKeyboardSearch(const QString
& text
, int startFromIndex
= 0) const;
109 virtual bool supportsDropping(int index
) const;
112 virtual QString
roleDescription(const QByteArray
& role
) const;
115 virtual QList
<QPair
<int, QVariant
> > groups() const;
118 * @return The file-item for the index \a index. If the index is in a valid
119 * range it is assured that the file-item is not null. The runtime
120 * complexity of this call is O(1).
122 KFileItem
fileItem(int index
) const;
125 * @return The file-item for the url \a url. If no file-item with the given
126 * URL is found KFileItem::isNull() will be true for the returned
127 * file-item. The runtime complexity of this call is O(1).
129 KFileItem
fileItem(const KUrl
& url
) const;
132 * @return The index for the file-item \a item. -1 is returned if no file-item
133 * is found or if the file-item is null. The amortized runtime
134 * complexity of this call is O(1).
136 int index(const KFileItem
& item
) const;
139 * @return The index for the URL \a url. -1 is returned if no file-item
140 * is found. The amortized runtime complexity of this call is O(1).
142 int index(const KUrl
& url
) const;
145 * @return Root item of all items representing the item
146 * for KFileItemModel::dir().
148 KFileItem
rootItem() const;
151 * Clears all items of the model.
156 * Sets the roles that should be shown for each item.
158 void setRoles(const QSet
<QByteArray
>& roles
);
159 QSet
<QByteArray
> roles() const;
161 virtual bool setExpanded(int index
, bool expanded
);
162 virtual bool isExpanded(int index
) const;
163 virtual bool isExpandable(int index
) const;
164 virtual int expandedParentsCount(int index
) const;
166 QSet
<KUrl
> expandedDirectories() const;
169 * Marks the URLs in \a urls as sub-directories which were expanded previously.
170 * After calling loadDirectory() or refreshDirectory() the marked sub-directories
171 * will be expanded step-by-step.
173 void restoreExpandedDirectories(const QSet
<KUrl
>& urls
);
176 * Expands all parent-directories of the item \a url.
178 void expandParentDirectories(const KUrl
& url
);
180 void setNameFilter(const QString
& nameFilter
);
181 QString
nameFilter() const;
183 void setMimeTypeFilters(const QStringList
& filters
);
184 QStringList
mimeTypeFilters() const;
191 bool requiresIndexer
;
195 * @return Provides static information for all available roles that
196 * are supported by KFileItemModel. Some roles can only be
197 * determined if Baloo is enabled and/or the Baloo
198 * indexing is enabled.
200 static QList
<RoleInfo
> rolesInformation();
204 * Is emitted if the loading of a directory has been started. It is
205 * assured that a signal directoryLoadingCompleted() will be send after
206 * the loading has been finished. For tracking the loading progress
207 * the signal directoryLoadingProgress() gets emitted in between.
209 void directoryLoadingStarted();
212 * Is emitted after the loading of a directory has been completed or new
213 * items have been inserted to an already loaded directory. Usually
214 * one or more itemsInserted() signals are emitted before loadingCompleted()
215 * (the only exception is loading an empty directory, where only a
216 * loadingCompleted() signal gets emitted).
218 void directoryLoadingCompleted();
221 * Is emitted after the loading of a directory has been canceled.
223 void directoryLoadingCanceled();
226 * Informs about the progress in percent when loading a directory. It is assured
227 * that the signal directoryLoadingStarted() has been emitted before.
229 void directoryLoadingProgress(int percent
);
232 * Is emitted if the sort-role gets resolved asynchronously and provides
233 * the progress-information of the sorting in percent. It is assured
234 * that the last sortProgress-signal contains 100 as value.
236 void directorySortingProgress(int percent
);
239 * Is emitted if an information message (e.g. "Connecting to host...")
242 void infoMessage(const QString
& message
);
245 * Is emitted if an error message (e.g. "Unknown location")
248 void errorMessage(const QString
& message
);
251 * Is emitted if a redirection from the current URL \a oldUrl
252 * to the new URL \a newUrl has been done.
254 void directoryRedirection(const KUrl
& oldUrl
, const KUrl
& newUrl
);
257 * Is emitted when the URL passed by KFileItemModel::setUrl() represents a file.
258 * In this case no signal errorMessage() will be emitted.
260 void urlIsFileError(const KUrl
& url
);
263 virtual void onGroupedSortingChanged(bool current
);
264 virtual void onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
);
265 virtual void onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
);
269 * Resorts all items dependent on the set sortRole(), sortOrder()
270 * and foldersFirst() settings.
272 void resortAllItems();
274 void slotCompleted();
276 void slotItemsAdded(const KUrl
& directoryUrl
, const KFileItemList
& items
);
277 void slotItemsDeleted(const KFileItemList
& items
);
278 void slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
);
280 void slotNaturalSortingChanged();
282 void dispatchPendingItemsToInsert();
286 // User visible roles:
287 NoRole
, NameRole
, SizeRole
, DateRole
, PermissionsRole
, OwnerRole
,
288 GroupRole
, TypeRole
, DestinationRole
, PathRole
,
289 // User visible roles available with Baloo:
290 CommentRole
, TagsRole
, RatingRole
, ImageSizeRole
, OrientationRole
,
291 WordCountRole
, LineCountRole
, ArtistRole
, AlbumRole
, DurationRole
, TrackRole
,
293 // Non-visible roles:
294 IsDirRole
, IsLinkRole
, IsExpandedRole
, IsExpandableRole
, ExpandedParentsCountRole
,
295 // Mandatory last entry:
302 QHash
<QByteArray
, QVariant
> values
;
306 enum RemoveItemsBehavior
{
311 void insertItems(QList
<ItemData
*>& items
);
312 void removeItems(const KItemRangeList
& itemRanges
, RemoveItemsBehavior behavior
);
315 * Helper method for insertItems() and removeItems(): Creates
316 * a list of ItemData elements based on the given items.
317 * Note that the ItemData instances are created dynamically and
318 * must be deleted by the caller.
320 QList
<ItemData
*> createItemDataList(const KUrl
& parentUrl
, const KFileItemList
& items
) const;
323 * Prepares the items for sorting. Normally, the hash 'values' in ItemData is filled
324 * lazily to save time and memory, but for some sort roles, it is expected that the
325 * sort role data is stored in 'values'.
327 void prepareItemsForSorting(QList
<ItemData
*>& itemDataList
);
329 static int expandedParentsCount(const ItemData
* data
);
331 void removeExpandedItems();
334 * This function is called by setData() and slotRefreshItems(). It emits
335 * the itemsChanged() signal, checks if the sort order is still correct,
336 * and starts m_resortAllItemsTimer if that is not the case.
338 void emitItemsChangedAndTriggerResorting(const KItemRangeList
& itemRanges
, const QSet
<QByteArray
>& changedRoles
);
341 * Resets all values from m_requestRole to false.
346 * @return Role-type for the given role.
347 * Runtime complexity is O(1).
349 RoleType
typeForRole(const QByteArray
& role
) const;
352 * @return Role-byte-array for the given role-type.
353 * Runtime complexity is O(1).
355 QByteArray
roleForType(RoleType roleType
) const;
357 QHash
<QByteArray
, QVariant
> retrieveData(const KFileItem
& item
, const ItemData
* parent
) const;
360 * @return True if \a a has a KFileItem whose text is 'less than' the one
361 * of \a b according to QString::operator<(const QString&).
363 static bool nameLessThan(const ItemData
* a
, const ItemData
* b
);
366 * @return True if the item-data \a a should be ordered before the item-data
367 * \b. The item-data may have different parent-items.
369 bool lessThan(const ItemData
* a
, const ItemData
* b
) const;
372 * Sorts the items between \a begin and \a end using the comparison
373 * function lessThan().
375 void sort(QList
<ItemData
*>::iterator begin
, QList
<ItemData
*>::iterator end
) const;
378 * Helper method for lessThan() and expandedParentsCountCompare(): Compares
379 * the passed item-data using m_sortRole as criteria. Both items must
380 * have the same parent item, otherwise the comparison will be wrong.
382 int sortRoleCompare(const ItemData
* a
, const ItemData
* b
) const;
384 int stringCompare(const QString
& a
, const QString
& b
) const;
386 bool useMaximumUpdateInterval() const;
388 QList
<QPair
<int, QVariant
> > nameRoleGroups() const;
389 QList
<QPair
<int, QVariant
> > sizeRoleGroups() const;
390 QList
<QPair
<int, QVariant
> > dateRoleGroups() const;
391 QList
<QPair
<int, QVariant
> > permissionRoleGroups() const;
392 QList
<QPair
<int, QVariant
> > ratingRoleGroups() const;
393 QList
<QPair
<int, QVariant
> > genericStringRoleGroups(const QByteArray
& typeForRole
) const;
396 * Helper method for all xxxRoleGroups() methods to check whether the
397 * item with the given index is a child-item. A child-item is defined
398 * as item having an expansion-level > 0. All xxxRoleGroups() methods
399 * should skip the grouping if the item is a child-item (although
400 * KItemListView would be capable to show sub-groups in groups this
401 * results in visual clutter for most usecases).
403 bool isChildItem(int index
) const;
406 * Is invoked by KFileItemModelRolesUpdater and results in emitting the
407 * sortProgress signal with a percent-value of the progress.
409 void emitSortProgress(int resolvedCount
);
412 * Applies the filters set through @ref setNameFilter and @ref setMimeTypeFilters.
417 * Removes filtered items whose expanded parents have been deleted
418 * or collapsed via setExpanded(parentIndex, false).
420 void removeFilteredChildren(const KItemRangeList
& parents
);
423 * Maps the QByteArray-roles to RoleTypes and provides translation- and
428 const char* const role
;
429 const RoleType roleType
;
430 const char* const roleTranslationContext
;
431 const char* const roleTranslation
;
432 const char* const groupTranslationContext
;
433 const char* const groupTranslation
;
434 const bool requiresBaloo
;
435 const bool requiresIndexer
;
439 * @return Map of user visible roles that are accessible by KFileItemModel::rolesInformation().
441 static const RoleInfoMap
* rolesInfoMap(int& count
);
444 * Determines the MIME-types of all items that can be done within
447 static void determineMimeTypes(const KFileItemList
& items
, int timeout
);
450 * @return Returns a copy of \a value that is implicitly shared
451 * with other users to save memory.
453 static QByteArray
sharedValue(const QByteArray
& value
);
456 * Checks if the model's internal data structures are consistent.
458 bool isConsistent() const;
461 KFileItemModelDirLister
* m_dirLister
;
463 bool m_naturalSorting
;
464 bool m_sortDirsFirst
;
467 int m_sortingProgressPercent
; // Value of directorySortingProgress() signal
468 QSet
<QByteArray
> m_roles
;
469 Qt::CaseSensitivity m_caseSensitivity
;
471 QList
<ItemData
*> m_itemData
;
473 // m_items is a cache for the method index(const KUrl&). If it contains N
474 // entries, it is guaranteed that these correspond to the first N items in
475 // the model, i.e., that (for every i between 0 and N - 1)
476 // m_items.value(fileItem(i).url()) == i
477 mutable QHash
<KUrl
, int> m_items
;
479 KFileItemModelFilter m_filter
;
480 QHash
<KFileItem
, ItemData
*> m_filteredItems
; // Items that got hidden by KFileItemModel::setNameFilter()
482 bool m_requestRole
[RolesCount
];
484 QTimer
* m_maximumUpdateIntervalTimer
;
485 QTimer
* m_resortAllItemsTimer
;
486 QList
<ItemData
*> m_pendingItemsToInsert
;
488 // Cache for KFileItemModel::groups()
489 mutable QList
<QPair
<int, QVariant
> > m_groups
;
491 // Stores the URLs (key: target url, value: url) of the expanded directories.
492 QHash
<KUrl
, KUrl
> m_expandedDirs
;
494 // URLs that must be expanded. The expanding is initially triggered in setExpanded()
495 // and done step after step in slotCompleted().
496 QSet
<KUrl
> m_urlsToExpand
;
498 friend class KFileItemModelLessThan
; // Accesses lessThan() method
499 friend class KFileItemModelRolesUpdater
; // Accesses emitSortProgress() method
500 friend class KFileItemModelTest
; // For unit testing
501 friend class KFileItemModelBenchmark
; // For unit testing
502 friend class KFileItemListViewTest
; // For unit testing
503 friend class DolphinPart
; // Accesses m_dirLister
506 inline bool KFileItemModel::nameLessThan(const ItemData
* a
, const ItemData
* b
)
508 return a
->item
.text() < b
->item
.text();
512 inline bool KFileItemModel::isChildItem(int index
) const
514 if (m_itemData
.at(index
)->parent
) {