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"
15 #include <KLazyLocalizedString>
33 * @brief KItemModelBase implementation for KFileItems.
35 * Allows to load items of a directory. Sorting and grouping of
36 * items are supported. Roles that are not part of KFileItem can
37 * be added with KFileItemModel::setData().
39 * Recursive expansion of sub-directories is supported by
40 * KFileItemModel::setExpanded().
42 class DOLPHIN_EXPORT KFileItemModel
: public KItemModelBase
47 explicit KFileItemModel(QObject
* parent
= nullptr);
48 ~KFileItemModel() override
;
51 * Loads the directory specified by \a url. The signals
52 * directoryLoadingStarted(), directoryLoadingProgress() and directoryLoadingCompleted()
53 * indicate the current state of the loading process. The items
54 * of the directory are added after the loading has been completed.
56 void loadDirectory(const QUrl
& url
);
59 * Throws away all currently loaded items and refreshes the directory
60 * by reloading all items again.
62 void refreshDirectory(const QUrl
& url
);
65 * @return Parent directory of the items that are shown. In case
66 * if a directory tree is shown, KFileItemModel::dir() returns
67 * the root-parent of all items.
70 QUrl
directory() const override
;
73 * Cancels the loading of a directory which has been started by either
74 * loadDirectory() or refreshDirectory().
76 void cancelDirectoryLoading();
78 int count() const override
;
79 QHash
<QByteArray
, QVariant
> data(int index
) const override
;
80 bool setData(int index
, const QHash
<QByteArray
, QVariant
>& values
) override
;
83 * Sets a separate sorting with directories first (true) or a mixed
84 * sorting of files and directories (false).
86 void setSortDirectoriesFirst(bool dirsFirst
);
87 bool sortDirectoriesFirst() const;
90 * Sets a separate sorting with hidden files and folders last (true) or not (false).
92 void setSortHiddenLast(bool hiddenLast
);
93 bool sortHiddenLast() const;
95 void setShowHiddenFiles(bool show
);
96 bool showHiddenFiles() const;
99 * If set to true, only directories are shown as items of the model. Files
102 void setShowDirectoriesOnly(bool enabled
);
103 bool showDirectoriesOnly() const;
105 QMimeData
* createMimeData(const KItemSet
& indexes
) const override
;
107 int indexForKeyboardSearch(const QString
& text
, int startFromIndex
= 0) const override
;
109 bool supportsDropping(int index
) const override
;
111 QString
roleDescription(const QByteArray
& role
) const override
;
113 QList
<QPair
<int, QVariant
> > groups() const override
;
116 * @return The file-item for the index \a index. If the index is in a valid
117 * range it is assured that the file-item is not null. The runtime
118 * complexity of this call is O(1).
120 KFileItem
fileItem(int index
) const;
123 * @return The file-item for the url \a url. If no file-item with the given
124 * URL is found KFileItem::isNull() will be true for the returned
125 * file-item. The runtime complexity of this call is O(1).
127 KFileItem
fileItem(const QUrl
& url
) const;
130 * @return The index for the file-item \a item. -1 is returned if no file-item
131 * is found or if the file-item is null. The amortized runtime
132 * complexity of this call is O(1).
134 int index(const KFileItem
& item
) const;
137 * @return The index for the URL \a url. -1 is returned if no file-item
138 * is found. The amortized runtime complexity of this call is O(1).
140 int index(const QUrl
&url
) const;
143 * @return Root item of all items representing the item
144 * for KFileItemModel::dir().
146 KFileItem
rootItem() const;
149 * Clears all items of the model.
154 * Sets the roles that should be shown for each item.
156 void setRoles(const QSet
<QByteArray
>& roles
);
157 QSet
<QByteArray
> roles() const;
159 bool setExpanded(int index
, bool expanded
) override
;
160 bool isExpanded(int index
) const override
;
161 bool isExpandable(int index
) const override
;
162 int expandedParentsCount(int index
) const override
;
164 QSet
<QUrl
> expandedDirectories() const;
167 * Marks the URLs in \a urls as sub-directories which were expanded previously.
168 * After calling loadDirectory() or refreshDirectory() the marked sub-directories
169 * will be expanded step-by-step.
171 void restoreExpandedDirectories(const QSet
<QUrl
>& urls
);
174 * Expands all parent-directories of the item \a url.
176 void expandParentDirectories(const QUrl
& url
);
178 void setNameFilter(const QString
& nameFilter
);
179 QString
nameFilter() const;
181 void setMimeTypeFilters(const QStringList
& filters
);
182 QStringList
mimeTypeFilters() const;
189 bool requiresIndexer
;
193 * @return Provides static information for all available roles that
194 * are supported by KFileItemModel. Some roles can only be
195 * determined if Baloo is enabled and/or the Baloo
196 * indexing is enabled.
198 static QList
<RoleInfo
> rolesInformation();
202 * Is emitted if the loading of a directory has been started. It is
203 * assured that a signal directoryLoadingCompleted() will be send after
204 * the loading has been finished. For tracking the loading progress
205 * the signal directoryLoadingProgress() gets emitted in between.
207 void directoryLoadingStarted();
210 * Is emitted after the loading of a directory has been completed or new
211 * items have been inserted to an already loaded directory. Usually
212 * one or more itemsInserted() signals are emitted before loadingCompleted()
213 * (the only exception is loading an empty directory, where only a
214 * loadingCompleted() signal gets emitted).
216 void directoryLoadingCompleted();
219 * Is emitted after the loading of a directory has been canceled.
221 void directoryLoadingCanceled();
224 * Informs about the progress in percent when loading a directory. It is assured
225 * that the signal directoryLoadingStarted() has been emitted before.
227 void directoryLoadingProgress(int percent
);
230 * Is emitted if the sort-role gets resolved asynchronously and provides
231 * the progress-information of the sorting in percent. It is assured
232 * that the last sortProgress-signal contains 100 as value.
234 void directorySortingProgress(int percent
);
237 * Is emitted if an information message (e.g. "Connecting to host...")
240 void infoMessage(const QString
& message
);
243 * Is emitted if an error message (e.g. "Unknown location")
246 void errorMessage(const QString
& message
);
249 * Is emitted if a redirection from the current URL \a oldUrl
250 * to the new URL \a newUrl has been done.
252 void directoryRedirection(const QUrl
& oldUrl
, const QUrl
& newUrl
);
255 * Is emitted when the URL passed by KFileItemModel::setUrl() represents a file.
256 * In this case no signal errorMessage() will be emitted.
258 void urlIsFileError(const QUrl
& url
);
261 * It is emitted for files when they change and
262 * for dirs when files are added or removed.
264 void fileItemsChanged(const KFileItemList
&changedFileItems
);
267 * It is emitted when the parent directory was removed.
269 void currentDirectoryRemoved();
272 void onGroupedSortingChanged(bool current
) override
;
273 void onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
, bool resortItems
= true) override
;
274 void onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
) override
;
278 * Resorts all items dependent on the set sortRole(), sortOrder()
279 * and foldersFirst() settings.
281 void resortAllItems();
283 void slotCompleted();
285 void slotItemsAdded(const QUrl
& directoryUrl
, const KFileItemList
& items
);
286 void slotItemsDeleted(const KFileItemList
& items
);
287 void slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
);
289 void slotSortingChoiceChanged();
290 void slotListerError(KIO::Job
*job
);
292 void dispatchPendingItemsToInsert();
296 // User visible roles:
297 NoRole
, NameRole
, SizeRole
, ModificationTimeRole
, CreationTimeRole
, AccessTimeRole
, PermissionsRole
, OwnerRole
,
298 GroupRole
, TypeRole
, ExtensionRole
, DestinationRole
, PathRole
, DeletionTimeRole
,
299 // User visible roles available with Baloo:
300 CommentRole
, TagsRole
, RatingRole
, DimensionsRole
, WidthRole
, HeightRole
, ImageDateTimeRole
, OrientationRole
,
301 WordCountRole
, TitleRole
, AuthorRole
, LineCountRole
, ArtistRole
, GenreRole
, AlbumRole
, DurationRole
, TrackRole
, ReleaseYearRole
,
302 BitrateRole
, OriginUrlRole
, AspectRatioRole
, FrameRateRole
,
303 // Non-visible roles:
304 IsDirRole
, IsLinkRole
, IsHiddenRole
, IsExpandedRole
, IsExpandableRole
, ExpandedParentsCountRole
,
305 // Mandatory last entry:
312 QHash
<QByteArray
, QVariant
> values
;
316 enum RemoveItemsBehavior
{
319 DeleteItemDataIfUnfiltered
322 void insertItems(QList
<ItemData
*>& items
);
323 void removeItems(const KItemRangeList
& itemRanges
, RemoveItemsBehavior behavior
);
326 * Helper method for insertItems() and removeItems(): Creates
327 * a list of ItemData elements based on the given items.
328 * Note that the ItemData instances are created dynamically and
329 * must be deleted by the caller.
331 QList
<ItemData
*> createItemDataList(const QUrl
& parentUrl
, const KFileItemList
& items
) const;
334 * Prepares the items for sorting. Normally, the hash 'values' in ItemData is filled
335 * lazily to save time and memory, but for some sort roles, it is expected that the
336 * sort role data is stored in 'values'.
338 void prepareItemsForSorting(QList
<ItemData
*>& itemDataList
);
340 static int expandedParentsCount(const ItemData
* data
);
342 void removeExpandedItems();
345 * This function is called by setData() and slotRefreshItems(). It emits
346 * the itemsChanged() signal, checks if the sort order is still correct,
347 * and starts m_resortAllItemsTimer if that is not the case.
349 void emitItemsChangedAndTriggerResorting(const KItemRangeList
& itemRanges
, const QSet
<QByteArray
>& changedRoles
);
352 * Resets all values from m_requestRole to false.
357 * @return Role-type for the given role.
358 * Runtime complexity is O(1).
360 RoleType
typeForRole(const QByteArray
& role
) const;
363 * @return Role-byte-array for the given role-type.
364 * Runtime complexity is O(1).
366 QByteArray
roleForType(RoleType roleType
) const;
368 QHash
<QByteArray
, QVariant
> retrieveData(const KFileItem
& item
, const ItemData
* parent
) const;
371 * @return True if role values benefit from natural or case insensitive sorting.
373 static bool isRoleValueNatural(const RoleType roleType
);
376 * @return True if \a a has a KFileItem whose text is 'less than' the one
377 * of \a b according to QString::operator<(const QString&).
379 static bool nameLessThan(const ItemData
* a
, const ItemData
* b
);
382 * @return True if the item-data \a a should be ordered before the item-data
383 * \b. The item-data may have different parent-items.
385 bool lessThan(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const;
388 * Sorts the items between \a begin and \a end using the comparison
389 * function lessThan().
391 void sort(const QList
<ItemData
*>::iterator
&begin
, const QList
<ItemData
*>::iterator
&end
) const;
394 * Helper method for lessThan() and expandedParentsCountCompare(): Compares
395 * the passed item-data using m_sortRole as criteria. Both items must
396 * have the same parent item, otherwise the comparison will be wrong.
398 int sortRoleCompare(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const;
400 int stringCompare(const QString
& a
, const QString
& b
, const QCollator
& collator
) const;
402 QList
<QPair
<int, QVariant
> > nameRoleGroups() const;
403 QList
<QPair
<int, QVariant
> > sizeRoleGroups() const;
404 QList
<QPair
<int, QVariant
> > timeRoleGroups(const std::function
<QDateTime(const ItemData
*)> &fileTimeCb
) const;
405 QList
<QPair
<int, QVariant
> > permissionRoleGroups() const;
406 QList
<QPair
<int, QVariant
> > ratingRoleGroups() const;
407 QList
<QPair
<int, QVariant
> > genericStringRoleGroups(const QByteArray
& typeForRole
) const;
410 * Helper method for all xxxRoleGroups() methods to check whether the
411 * item with the given index is a child-item. A child-item is defined
412 * as item having an expansion-level > 0. All xxxRoleGroups() methods
413 * should skip the grouping if the item is a child-item (although
414 * KItemListView would be capable to show sub-groups in groups this
415 * results in visual clutter for most usecases).
417 bool isChildItem(int index
) const;
420 * Is invoked by KFileItemModelRolesUpdater and results in emitting the
421 * sortProgress signal with a percent-value of the progress.
423 void emitSortProgress(int resolvedCount
);
426 * Applies the filters set through @ref setNameFilter and @ref setMimeTypeFilters.
431 * Removes filtered items whose expanded parents have been deleted
432 * or collapsed via setExpanded(parentIndex, false).
434 void removeFilteredChildren(const KItemRangeList
& parents
);
437 * Loads the selected choice of sorting method from Dolphin General Settings
439 void loadSortingSettings();
442 * Maps the QByteArray-roles to RoleTypes and provides translation- and
447 const char* const role
;
448 const RoleType roleType
;
449 const KLazyLocalizedString roleTranslation
;
450 const KLazyLocalizedString groupTranslation
;
451 const bool requiresBaloo
;
452 const bool requiresIndexer
;
456 * @return Map of user visible roles that are accessible by KFileItemModel::rolesInformation().
458 static const RoleInfoMap
* rolesInfoMap(int& count
);
461 * Determines the MIME-types of all items that can be done within
464 static void determineMimeTypes(const KFileItemList
& items
, int timeout
);
467 * @return Returns a copy of \a value that is implicitly shared
468 * with other users to save memory.
470 static QByteArray
sharedValue(const QByteArray
& value
);
473 * Checks if the model's internal data structures are consistent.
475 bool isConsistent() const;
478 * Filters out the expanded folders that don't pass the filter themselves and don't have any filter-passing children.
479 * Will update the removedItemRanges arguments to include the parents that have been filtered.
480 * @returns the number of parents that have been filtered.
481 * @param removedItemRanges The ranges of items being deleted/filtered, will get updated
482 * @param parentsToEnsureVisible Parents that must be visible no matter what due to being ancestors of newly visible items
484 int filterChildlessParents(KItemRangeList
&removedItemRanges
, const QSet
<ItemData
*> &parentsToEnsureVisible
= QSet
<ItemData
*>());
487 KDirLister
*m_dirLister
= nullptr;
489 QCollator m_collator
;
490 bool m_naturalSorting
;
491 bool m_sortDirsFirst
;
492 bool m_sortHiddenLast
;
495 int m_sortingProgressPercent
; // Value of directorySortingProgress() signal
496 QSet
<QByteArray
> m_roles
;
498 QList
<ItemData
*> m_itemData
;
500 // m_items is a cache for the method index(const QUrl&). If it contains N
501 // entries, it is guaranteed that these correspond to the first N items in
502 // the model, i.e., that (for every i between 0 and N - 1)
503 // m_items.value(fileItem(i).url()) == i
504 mutable QHash
<QUrl
, int> m_items
;
506 KFileItemModelFilter m_filter
;
507 QHash
<KFileItem
, ItemData
*> m_filteredItems
; // Items that got hidden by KFileItemModel::setNameFilter()
509 bool m_requestRole
[RolesCount
];
511 QTimer
* m_maximumUpdateIntervalTimer
;
512 QTimer
* m_resortAllItemsTimer
;
513 QList
<ItemData
*> m_pendingItemsToInsert
;
515 // Cache for KFileItemModel::groups()
516 mutable QList
<QPair
<int, QVariant
> > m_groups
;
518 // Stores the URLs (key: target url, value: url) of the expanded directories.
519 QHash
<QUrl
, QUrl
> m_expandedDirs
;
521 // URLs that must be expanded. The expanding is initially triggered in setExpanded()
522 // and done step after step in slotCompleted().
523 QSet
<QUrl
> m_urlsToExpand
;
525 friend class KFileItemModelRolesUpdater
; // Accesses emitSortProgress() method
526 friend class KFileItemModelTest
; // For unit testing
527 friend class KFileItemModelBenchmark
; // For unit testing
528 friend class KFileItemListViewTest
; // For unit testing
529 friend class DolphinPart
; // Accesses m_dirLister
532 inline bool KFileItemModel::isRoleValueNatural(RoleType roleType
)
534 return (roleType
== TypeRole
||
535 roleType
== ExtensionRole
||
536 roleType
== TagsRole
||
537 roleType
== CommentRole
||
538 roleType
== TitleRole
||
539 roleType
== ArtistRole
||
540 roleType
== GenreRole
||
541 roleType
== AlbumRole
||
542 roleType
== PathRole
||
543 roleType
== DestinationRole
||
544 roleType
== OriginUrlRole
||
545 roleType
== OwnerRole
||
546 roleType
== GroupRole
);
549 inline bool KFileItemModel::nameLessThan(const ItemData
* a
, const ItemData
* b
)
551 return a
->item
.text() < b
->item
.text();
554 inline bool KFileItemModel::isChildItem(int index
) const
556 if (m_itemData
.at(index
)->parent
) {