2 * SPDX-FileCopyrightText: 2011 Peter Penz <peter.penz19@gmail.com>
4 * SPDX-License-Identifier: GPL-2.0-or-later
7 #ifndef KFILEITEMMODEL_H
8 #define KFILEITEMMODEL_H
10 #include "dolphin_export.h"
11 #include "kitemviews/kitemmodelbase.h"
12 #include "kitemviews/private/kfileitemmodelfilter.h"
32 * @brief KItemModelBase implementation for KFileItems.
34 * Allows to load items of a directory. Sorting and grouping of
35 * items are supported. Roles that are not part of KFileItem can
36 * be added with KFileItemModel::setData().
38 * Recursive expansion of sub-directories is supported by
39 * KFileItemModel::setExpanded().
41 class DOLPHIN_EXPORT KFileItemModel
: public KItemModelBase
46 explicit KFileItemModel(QObject
* parent
= nullptr);
47 ~KFileItemModel() override
;
50 * Loads the directory specified by \a url. The signals
51 * directoryLoadingStarted(), directoryLoadingProgress() and directoryLoadingCompleted()
52 * indicate the current state of the loading process. The items
53 * of the directory are added after the loading has been completed.
55 void loadDirectory(const QUrl
& url
);
58 * Throws away all currently loaded items and refreshes the directory
59 * by reloading all items again.
61 void refreshDirectory(const QUrl
& url
);
64 * @return Parent directory of the items that are shown. In case
65 * if a directory tree is shown, KFileItemModel::dir() returns
66 * the root-parent of all items.
69 QUrl
directory() const override
;
72 * Cancels the loading of a directory which has been started by either
73 * loadDirectory() or refreshDirectory().
75 void cancelDirectoryLoading();
77 int count() const override
;
78 QHash
<QByteArray
, QVariant
> data(int index
) const override
;
79 bool setData(int index
, const QHash
<QByteArray
, QVariant
>& values
) override
;
82 * Sets a separate sorting with directories first (true) or a mixed
83 * sorting of files and directories (false).
85 void setSortDirectoriesFirst(bool dirsFirst
);
86 bool sortDirectoriesFirst() const;
89 * Sets a separate sorting with hidden files and folders last (true) or not (false).
91 void setSortHiddenLast(bool hiddenLast
);
92 bool sortHiddenLast() const;
94 void setShowHiddenFiles(bool show
);
95 bool showHiddenFiles() const;
98 * If set to true, only directories are shown as items of the model. Files
101 void setShowDirectoriesOnly(bool enabled
);
102 bool showDirectoriesOnly() const;
104 QMimeData
* createMimeData(const KItemSet
& indexes
) const override
;
106 int indexForKeyboardSearch(const QString
& text
, int startFromIndex
= 0) const override
;
108 bool supportsDropping(int index
) const override
;
110 QString
roleDescription(const QByteArray
& role
) const override
;
112 QList
<QPair
<int, QVariant
> > groups() const override
;
115 * @return The file-item for the index \a index. If the index is in a valid
116 * range it is assured that the file-item is not null. The runtime
117 * complexity of this call is O(1).
119 KFileItem
fileItem(int index
) const;
122 * @return The file-item for the url \a url. If no file-item with the given
123 * URL is found KFileItem::isNull() will be true for the returned
124 * file-item. The runtime complexity of this call is O(1).
126 KFileItem
fileItem(const QUrl
& url
) const;
129 * @return The index for the file-item \a item. -1 is returned if no file-item
130 * is found or if the file-item is null. The amortized runtime
131 * complexity of this call is O(1).
133 int index(const KFileItem
& item
) const;
136 * @return The index for the URL \a url. -1 is returned if no file-item
137 * is found. The amortized runtime complexity of this call is O(1).
139 int index(const QUrl
&url
) const;
142 * @return Root item of all items representing the item
143 * for KFileItemModel::dir().
145 KFileItem
rootItem() const;
148 * Clears all items of the model.
153 * Sets the roles that should be shown for each item.
155 void setRoles(const QSet
<QByteArray
>& roles
);
156 QSet
<QByteArray
> roles() const;
158 bool setExpanded(int index
, bool expanded
) override
;
159 bool isExpanded(int index
) const override
;
160 bool isExpandable(int index
) const override
;
161 int expandedParentsCount(int index
) const override
;
163 QSet
<QUrl
> expandedDirectories() const;
166 * Marks the URLs in \a urls as sub-directories which were expanded previously.
167 * After calling loadDirectory() or refreshDirectory() the marked sub-directories
168 * will be expanded step-by-step.
170 void restoreExpandedDirectories(const QSet
<QUrl
>& urls
);
173 * Expands all parent-directories of the item \a url.
175 void expandParentDirectories(const QUrl
& url
);
177 void setNameFilter(const QString
& nameFilter
);
178 QString
nameFilter() const;
180 void setMimeTypeFilters(const QStringList
& filters
);
181 QStringList
mimeTypeFilters() const;
188 bool requiresIndexer
;
192 * @return Provides static information for all available roles that
193 * are supported by KFileItemModel. Some roles can only be
194 * determined if Baloo is enabled and/or the Baloo
195 * indexing is enabled.
197 static QList
<RoleInfo
> rolesInformation();
201 * Is emitted if the loading of a directory has been started. It is
202 * assured that a signal directoryLoadingCompleted() will be send after
203 * the loading has been finished. For tracking the loading progress
204 * the signal directoryLoadingProgress() gets emitted in between.
206 void directoryLoadingStarted();
209 * Is emitted after the loading of a directory has been completed or new
210 * items have been inserted to an already loaded directory. Usually
211 * one or more itemsInserted() signals are emitted before loadingCompleted()
212 * (the only exception is loading an empty directory, where only a
213 * loadingCompleted() signal gets emitted).
215 void directoryLoadingCompleted();
218 * Is emitted after the loading of a directory has been canceled.
220 void directoryLoadingCanceled();
223 * Informs about the progress in percent when loading a directory. It is assured
224 * that the signal directoryLoadingStarted() has been emitted before.
226 void directoryLoadingProgress(int percent
);
229 * Is emitted if the sort-role gets resolved asynchronously and provides
230 * the progress-information of the sorting in percent. It is assured
231 * that the last sortProgress-signal contains 100 as value.
233 void directorySortingProgress(int percent
);
236 * Is emitted if an information message (e.g. "Connecting to host...")
239 void infoMessage(const QString
& message
);
242 * Is emitted if an error message (e.g. "Unknown location")
245 void errorMessage(const QString
& message
);
248 * Is emitted if a redirection from the current URL \a oldUrl
249 * to the new URL \a newUrl has been done.
251 void directoryRedirection(const QUrl
& oldUrl
, const QUrl
& newUrl
);
254 * Is emitted when the URL passed by KFileItemModel::setUrl() represents a file.
255 * In this case no signal errorMessage() will be emitted.
257 void urlIsFileError(const QUrl
& url
);
260 * It is emitted for files when they change and
261 * for dirs when files are added or removed.
263 void fileItemsChanged(const KFileItemList
&changedFileItems
);
266 void onGroupedSortingChanged(bool current
) override
;
267 void onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
, bool resortItems
= true) override
;
268 void onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
) override
;
272 * Resorts all items dependent on the set sortRole(), sortOrder()
273 * and foldersFirst() settings.
275 void resortAllItems();
277 void slotCompleted();
279 void slotItemsAdded(const QUrl
& directoryUrl
, const KFileItemList
& items
);
280 void slotItemsDeleted(const KFileItemList
& items
);
281 void slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
);
283 void slotSortingChoiceChanged();
284 void slotListerError(KIO::Job
*job
);
286 void dispatchPendingItemsToInsert();
290 // User visible roles:
291 NoRole
, NameRole
, SizeRole
, ModificationTimeRole
, CreationTimeRole
, AccessTimeRole
, PermissionsRole
, OwnerRole
,
292 GroupRole
, TypeRole
, DestinationRole
, PathRole
, DeletionTimeRole
,
293 // User visible roles available with Baloo:
294 CommentRole
, TagsRole
, RatingRole
, WidthRole
, HeightRole
, ImageDateTimeRole
, OrientationRole
,
295 WordCountRole
, TitleRole
, LineCountRole
, ArtistRole
, GenreRole
, AlbumRole
, DurationRole
, TrackRole
, ReleaseYearRole
,
296 BitrateRole
, OriginUrlRole
, AspectRatioRole
, FrameRateRole
,
297 // Non-visible roles:
298 IsDirRole
, IsLinkRole
, IsHiddenRole
, IsExpandedRole
, IsExpandableRole
, ExpandedParentsCountRole
,
299 // Mandatory last entry:
306 QHash
<QByteArray
, QVariant
> values
;
310 enum RemoveItemsBehavior
{
313 DeleteItemDataIfUnfiltered
316 void insertItems(QList
<ItemData
*>& items
);
317 void removeItems(const KItemRangeList
& itemRanges
, RemoveItemsBehavior behavior
);
320 * Helper method for insertItems() and removeItems(): Creates
321 * a list of ItemData elements based on the given items.
322 * Note that the ItemData instances are created dynamically and
323 * must be deleted by the caller.
325 QList
<ItemData
*> createItemDataList(const QUrl
& parentUrl
, const KFileItemList
& items
) const;
328 * Prepares the items for sorting. Normally, the hash 'values' in ItemData is filled
329 * lazily to save time and memory, but for some sort roles, it is expected that the
330 * sort role data is stored in 'values'.
332 void prepareItemsForSorting(QList
<ItemData
*>& itemDataList
);
334 static int expandedParentsCount(const ItemData
* data
);
336 void removeExpandedItems();
339 * This function is called by setData() and slotRefreshItems(). It emits
340 * the itemsChanged() signal, checks if the sort order is still correct,
341 * and starts m_resortAllItemsTimer if that is not the case.
343 void emitItemsChangedAndTriggerResorting(const KItemRangeList
& itemRanges
, const QSet
<QByteArray
>& changedRoles
);
346 * Resets all values from m_requestRole to false.
351 * @return Role-type for the given role.
352 * Runtime complexity is O(1).
354 RoleType
typeForRole(const QByteArray
& role
) const;
357 * @return Role-byte-array for the given role-type.
358 * Runtime complexity is O(1).
360 QByteArray
roleForType(RoleType roleType
) const;
362 QHash
<QByteArray
, QVariant
> retrieveData(const KFileItem
& item
, const ItemData
* parent
) const;
365 * @return True if role values benefit from natural or case insensitive sorting.
367 static bool isRoleValueNatural(const RoleType roleType
);
370 * @return True if \a a has a KFileItem whose text is 'less than' the one
371 * of \a b according to QString::operator<(const QString&).
373 static bool nameLessThan(const ItemData
* a
, const ItemData
* b
);
376 * @return True if the item-data \a a should be ordered before the item-data
377 * \b. The item-data may have different parent-items.
379 bool lessThan(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const;
382 * Sorts the items between \a begin and \a end using the comparison
383 * function lessThan().
385 void sort(const QList
<ItemData
*>::iterator
&begin
, const QList
<ItemData
*>::iterator
&end
) const;
388 * Helper method for lessThan() and expandedParentsCountCompare(): Compares
389 * the passed item-data using m_sortRole as criteria. Both items must
390 * have the same parent item, otherwise the comparison will be wrong.
392 int sortRoleCompare(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const;
394 int stringCompare(const QString
& a
, const QString
& b
, const QCollator
& collator
) const;
396 QList
<QPair
<int, QVariant
> > nameRoleGroups() const;
397 QList
<QPair
<int, QVariant
> > sizeRoleGroups() const;
398 QList
<QPair
<int, QVariant
> > timeRoleGroups(const std::function
<QDateTime(const ItemData
*)> &fileTimeCb
) const;
399 QList
<QPair
<int, QVariant
> > permissionRoleGroups() const;
400 QList
<QPair
<int, QVariant
> > ratingRoleGroups() const;
401 QList
<QPair
<int, QVariant
> > genericStringRoleGroups(const QByteArray
& typeForRole
) const;
404 * Helper method for all xxxRoleGroups() methods to check whether the
405 * item with the given index is a child-item. A child-item is defined
406 * as item having an expansion-level > 0. All xxxRoleGroups() methods
407 * should skip the grouping if the item is a child-item (although
408 * KItemListView would be capable to show sub-groups in groups this
409 * results in visual clutter for most usecases).
411 bool isChildItem(int index
) const;
414 * Is invoked by KFileItemModelRolesUpdater and results in emitting the
415 * sortProgress signal with a percent-value of the progress.
417 void emitSortProgress(int resolvedCount
);
420 * Applies the filters set through @ref setNameFilter and @ref setMimeTypeFilters.
425 * Removes filtered items whose expanded parents have been deleted
426 * or collapsed via setExpanded(parentIndex, false).
428 void removeFilteredChildren(const KItemRangeList
& parents
);
431 * Loads the selected choice of sorting method from Dolphin General Settings
433 void loadSortingSettings();
436 * Maps the QByteArray-roles to RoleTypes and provides translation- and
441 const char* const role
;
442 const RoleType roleType
;
443 const char* const roleTranslationContext
;
444 const char* const roleTranslation
;
445 const char* const groupTranslationContext
;
446 const char* const groupTranslation
;
447 const bool requiresBaloo
;
448 const bool requiresIndexer
;
452 * @return Map of user visible roles that are accessible by KFileItemModel::rolesInformation().
454 static const RoleInfoMap
* rolesInfoMap(int& count
);
457 * Determines the MIME-types of all items that can be done within
460 static void determineMimeTypes(const KFileItemList
& items
, int timeout
);
463 * @return Returns a copy of \a value that is implicitly shared
464 * with other users to save memory.
466 static QByteArray
sharedValue(const QByteArray
& value
);
469 * Checks if the model's internal data structures are consistent.
471 bool isConsistent() const;
474 * Filters out the expanded folders that don't pass the filter themselves and don't have any filter-passing children.
475 * Will update the removedItemRanges arguments to include the parents that have been filtered.
476 * @returns the number of parents that have been filtered.
477 * @param removedItemRanges The ranges of items being deleted/filtered, will get updated
478 * @param parentsToEnsureVisible Parents that must be visible no matter what due to being ancestors of newly visible items
480 int filterChildlessParents(KItemRangeList
&removedItemRanges
, const QSet
<ItemData
*> &parentsToEnsureVisible
= QSet
<ItemData
*>());
483 KDirLister
*m_dirLister
= nullptr;
485 QCollator m_collator
;
486 bool m_naturalSorting
;
487 bool m_sortDirsFirst
;
488 bool m_sortHiddenLast
;
491 int m_sortingProgressPercent
; // Value of directorySortingProgress() signal
492 QSet
<QByteArray
> m_roles
;
494 QList
<ItemData
*> m_itemData
;
496 // m_items is a cache for the method index(const QUrl&). If it contains N
497 // entries, it is guaranteed that these correspond to the first N items in
498 // the model, i.e., that (for every i between 0 and N - 1)
499 // m_items.value(fileItem(i).url()) == i
500 mutable QHash
<QUrl
, int> m_items
;
502 KFileItemModelFilter m_filter
;
503 QHash
<KFileItem
, ItemData
*> m_filteredItems
; // Items that got hidden by KFileItemModel::setNameFilter()
505 bool m_requestRole
[RolesCount
];
507 QTimer
* m_maximumUpdateIntervalTimer
;
508 QTimer
* m_resortAllItemsTimer
;
509 QList
<ItemData
*> m_pendingItemsToInsert
;
511 // Cache for KFileItemModel::groups()
512 mutable QList
<QPair
<int, QVariant
> > m_groups
;
514 // Stores the URLs (key: target url, value: url) of the expanded directories.
515 QHash
<QUrl
, QUrl
> m_expandedDirs
;
517 // URLs that must be expanded. The expanding is initially triggered in setExpanded()
518 // and done step after step in slotCompleted().
519 QSet
<QUrl
> m_urlsToExpand
;
521 friend class KFileItemModelRolesUpdater
; // Accesses emitSortProgress() method
522 friend class KFileItemModelTest
; // For unit testing
523 friend class KFileItemModelBenchmark
; // For unit testing
524 friend class KFileItemListViewTest
; // For unit testing
525 friend class DolphinPart
; // Accesses m_dirLister
528 inline bool KFileItemModel::isRoleValueNatural(RoleType roleType
)
530 return (roleType
== TypeRole
||
531 roleType
== TagsRole
||
532 roleType
== CommentRole
||
533 roleType
== TitleRole
||
534 roleType
== ArtistRole
||
535 roleType
== GenreRole
||
536 roleType
== AlbumRole
||
537 roleType
== PathRole
||
538 roleType
== DestinationRole
||
539 roleType
== OriginUrlRole
||
540 roleType
== OwnerRole
||
541 roleType
== GroupRole
);
544 inline bool KFileItemModel::nameLessThan(const ItemData
* a
, const ItemData
* b
)
546 return a
->item
.text() < b
->item
.text();
549 inline bool KFileItemModel::isChildItem(int index
) const
551 if (m_itemData
.at(index
)->parent
) {