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>
34 * @brief KItemModelBase implementation for KFileItems.
36 * Allows to load items of a directory. Sorting and grouping of
37 * items are supported. Roles that are not part of KFileItem can
38 * be added with KFileItemModel::setData().
40 * Recursive expansion of sub-directories is supported by
41 * KFileItemModel::setExpanded().
43 class DOLPHIN_EXPORT KFileItemModel
: public KItemModelBase
48 explicit KFileItemModel(QObject
*parent
= nullptr);
49 ~KFileItemModel() override
;
52 * Loads the directory specified by \a url. The signals
53 * directoryLoadingStarted(), directoryLoadingProgress() and directoryLoadingCompleted()
54 * indicate the current state of the loading process. The items
55 * of the directory are added after the loading has been completed.
57 void loadDirectory(const QUrl
&url
);
60 * Throws away all currently loaded items and refreshes the directory
61 * by reloading all items again.
63 void refreshDirectory(const QUrl
&url
);
66 * @return Parent directory of the items that are shown. In case
67 * if a directory tree is shown, KFileItemModel::dir() returns
68 * the root-parent of all items.
71 QUrl
directory() const override
;
74 * Cancels the loading of a directory which has been started by either
75 * loadDirectory() or refreshDirectory().
77 void cancelDirectoryLoading();
79 int count() const override
;
80 QHash
<QByteArray
, QVariant
> data(int index
) const override
;
81 bool setData(int index
, const QHash
<QByteArray
, QVariant
> &values
) override
;
84 * Sets a separate sorting with directories first (true) or a mixed
85 * sorting of files and directories (false).
87 void setSortDirectoriesFirst(bool dirsFirst
);
88 bool sortDirectoriesFirst() const;
91 * Sets a separate sorting with hidden files and folders last (true) or not (false).
93 void setSortHiddenLast(bool hiddenLast
);
94 bool sortHiddenLast() const;
96 void setShowHiddenFiles(bool show
);
97 bool showHiddenFiles() const;
100 * If set to true, only directories are shown as items of the model. Files
103 void setShowDirectoriesOnly(bool enabled
);
104 bool showDirectoriesOnly() const;
106 QMimeData
*createMimeData(const KItemSet
&indexes
) const override
;
108 int indexForKeyboardSearch(const QString
&text
, int startFromIndex
= 0) const override
;
110 bool supportsDropping(int index
) const override
;
112 bool canEnterOnHover(int index
) const override
;
114 QString
roleDescription(const QByteArray
&role
) const override
;
116 QList
<QPair
<int, QVariant
>> groups() const override
;
119 * @return The file-item for the index \a index. If the index is in a valid
120 * range it is assured that the file-item is not null. The runtime
121 * complexity of this call is O(1).
123 KFileItem
fileItem(int index
) const;
126 * @return The file-item for the url \a url. If no file-item with the given
127 * URL is found KFileItem::isNull() will be true for the returned
128 * file-item. The runtime complexity of this call is O(1).
130 KFileItem
fileItem(const QUrl
&url
) const;
133 * @return The index for the file-item \a item. -1 is returned if no file-item
134 * is found or if the file-item is null. The amortized runtime
135 * complexity of this call is O(1).
137 int index(const KFileItem
&item
) const;
140 * @return The index for the URL \a url. -1 is returned if no file-item
141 * is found. The amortized runtime complexity of this call is O(1).
143 int index(const QUrl
&url
) const;
146 * @return Root item of all items representing the item
147 * for KFileItemModel::dir().
149 KFileItem
rootItem() const;
152 * Clears all items of the model.
157 * Sets the roles that should be shown for each item.
159 void setRoles(const QSet
<QByteArray
> &roles
);
160 QSet
<QByteArray
> roles() const;
162 bool setExpanded(int index
, bool expanded
) override
;
163 bool isExpanded(int index
) const override
;
164 bool isExpandable(int index
) const override
;
165 int expandedParentsCount(int index
) const override
;
167 QSet
<QUrl
> expandedDirectories() const;
170 * Marks the URLs in \a urls as sub-directories which were expanded previously.
171 * After calling loadDirectory() or refreshDirectory() the marked sub-directories
172 * will be expanded step-by-step.
174 void restoreExpandedDirectories(const QSet
<QUrl
> &urls
);
177 * Expands all parent-directories of the item \a url.
179 void expandParentDirectories(const QUrl
&url
);
181 void setNameFilter(const QString
&nameFilter
);
182 QString
nameFilter() const;
184 void setMimeTypeFilters(const QStringList
&filters
);
185 QStringList
mimeTypeFilters() const;
187 void setExcludeMimeTypeFilter(const QStringList
&filters
);
188 QStringList
excludeMimeTypeFilter() const;
196 bool requiresIndexer
;
200 * @return Provides static information for a role that is supported
201 * by KFileItemModel. Some roles can only be determined if
202 * Baloo is enabled and/or the Baloo indexing is enabled.
204 static RoleInfo
roleInformation(const QByteArray
&role
);
207 * @return Provides static information for all available roles that
208 * are supported by KFileItemModel. Some roles can only be
209 * determined if Baloo is enabled and/or the Baloo
210 * indexing is enabled.
212 static QList
<RoleInfo
> rolesInformation();
214 /** set to true to hide application/x-trash files */
215 void setShowTrashMime(bool show
);
219 * Is emitted if the loading of a directory has been started. It is
220 * assured that a signal directoryLoadingCompleted() will be send after
221 * the loading has been finished. For tracking the loading progress
222 * the signal directoryLoadingProgress() gets emitted in between.
224 void directoryLoadingStarted();
227 * Is emitted after the loading of a directory has been completed or new
228 * items have been inserted to an already loaded directory. Usually
229 * one or more itemsInserted() signals are emitted before loadingCompleted()
230 * (the only exception is loading an empty directory, where only a
231 * loadingCompleted() signal gets emitted).
233 void directoryLoadingCompleted();
236 * Is emitted when the model is being refreshed (F5 key press)
238 void directoryRefreshing();
241 * Is emitted after the loading of a directory has been canceled.
243 void directoryLoadingCanceled();
246 * Informs about the progress in percent when loading a directory. It is assured
247 * that the signal directoryLoadingStarted() has been emitted before.
249 void directoryLoadingProgress(int percent
);
252 * Is emitted if the sort-role gets resolved asynchronously and provides
253 * the progress-information of the sorting in percent. It is assured
254 * that the last sortProgress-signal contains 100 as value.
256 void directorySortingProgress(int percent
);
259 * Is emitted if an information message (e.g. "Connecting to host...")
262 void infoMessage(const QString
&message
);
265 * Is emitted if an error message (e.g. "Unknown location")
268 void errorMessage(const QString
&message
);
271 * Is emitted if a redirection from the current URL \a oldUrl
272 * to the new URL \a newUrl has been done.
274 void directoryRedirection(const QUrl
&oldUrl
, const QUrl
&newUrl
);
277 * Is emitted when the URL passed by KFileItemModel::setUrl() represents a file.
278 * In this case no signal errorMessage() will be emitted.
280 void urlIsFileError(const QUrl
&url
);
283 * It is emitted for files when they change and
284 * for dirs when files are added or removed.
286 void fileItemsChanged(const KFileItemList
&changedFileItems
);
289 * It is emitted when the parent directory was removed.
291 void currentDirectoryRemoved();
294 void onGroupedSortingChanged(bool current
) override
;
295 void onSortRoleChanged(const QByteArray
¤t
, const QByteArray
&previous
, bool resortItems
= true) override
;
296 void onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
, bool resortItems
= true) override
;
297 void onGroupRoleChanged(const QByteArray
¤t
, const QByteArray
&previous
, bool resortItems
= true) override
;
298 void onGroupOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
, bool resortItems
= true) override
;
302 * Resorts all items dependent on the set sortRole(), sortOrder(),
303 * groupRole(), groupOrder() and foldersFirst() settings.
305 void resortAllItems();
307 void slotCompleted();
309 void slotItemsAdded(const QUrl
&directoryUrl
, const KFileItemList
&items
);
310 void slotItemsDeleted(const KFileItemList
&items
);
311 void slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
>> &items
);
313 void slotSortingChoiceChanged();
314 void slotListerError(KIO::Job
*job
);
316 void dispatchPendingItemsToInsert();
320 // User visible roles:
324 ModificationTimeRole
,
335 // User visible roles available with Baloo:
360 // Non-visible roles:
366 ExpandedParentsCountRole
,
367 // Mandatory last entry:
373 QHash
<QByteArray
, QVariant
> values
;
377 struct ItemGroupInfo
{
381 bool operator==(const ItemGroupInfo
&other
) const;
382 bool operator!=(const ItemGroupInfo
&other
) const;
383 bool operator<(const ItemGroupInfo
&other
) const;
386 enum RemoveItemsBehavior
{ KeepItemData
, DeleteItemData
, DeleteItemDataIfUnfiltered
};
388 void insertItems(QList
<ItemData
*> &items
);
389 void removeItems(const KItemRangeList
&itemRanges
, RemoveItemsBehavior behavior
);
392 * Helper method for insertItems() and removeItems(): Creates
393 * a list of ItemData elements based on the given items.
394 * Note that the ItemData instances are created dynamically and
395 * must be deleted by the caller.
397 QList
<ItemData
*> createItemDataList(const QUrl
&parentUrl
, const KFileItemList
&items
) const;
400 * Prepares the items for sorting. Normally, the hash 'values' in ItemData is filled
401 * lazily to save time and memory, but for some sort roles, it is expected that the
402 * sort role data is stored in 'values'.
404 void prepareItemsForSorting(QList
<ItemData
*> &itemDataList
);
406 static int expandedParentsCount(const ItemData
*data
);
408 void removeExpandedItems();
411 * This function is called by setData() and slotRefreshItems(). It emits
412 * the itemsChanged() signal, checks if the sort order is still correct,
413 * and starts m_resortAllItemsTimer if that is not the case.
415 void emitItemsChangedAndTriggerResorting(const KItemRangeList
&itemRanges
, const QSet
<QByteArray
> &changedRoles
);
418 * Resets all values from m_requestRole to false.
423 * @return Role-type for the given role.
424 * Runtime complexity is O(1).
426 RoleType
typeForRole(const QByteArray
&role
) const;
429 * @return Role-byte-array for the given role-type.
430 * Runtime complexity is O(1).
432 QByteArray
roleForType(RoleType roleType
) const;
434 QHash
<QByteArray
, QVariant
> retrieveData(const KFileItem
&item
, const ItemData
*parent
) const;
437 * @return True if role values benefit from natural or case insensitive sorting.
439 static bool isRoleValueNatural(const RoleType roleType
);
442 * @return True if \a a has a KFileItem whose text is 'less than' the one
443 * of \a b according to QString::operator<(const QString&).
445 static bool nameLessThan(const ItemData
*a
, const ItemData
*b
);
448 * @return True if the item-data \a a should be ordered before the item-data
449 * \b. The item-data may have different parent-items.
451 bool lessThan(const ItemData
*a
, const ItemData
*b
, const QCollator
&collator
) const;
454 * Sorts the items between \a begin and \a end using the comparison
455 * function lessThan().
457 void sort(const QList
<ItemData
*>::iterator
&begin
, const QList
<ItemData
*>::iterator
&end
) const;
460 * Helper method for lessThan() and expandedParentsCountCompare(): Compares
461 * the passed item-data using m_sortRole as criteria. Both items must
462 * have the same parent item, otherwise the comparison will be wrong.
464 int sortRoleCompare(const ItemData
*a
, const ItemData
*b
, const QCollator
&collator
) const;
467 * Helper method for lessThan() and expandedParentsCountCompare(): Compares
468 * the passed item-data using m_groupRole as criteria. Both items must
469 * have the same parent item, otherwise the comparison will be wrong.
471 int groupRoleCompare(const ItemData
*a
, const ItemData
*b
, const QCollator
&collator
) const;
473 int stringCompare(const QString
&a
, const QString
&b
, const QCollator
&collator
) const;
475 ItemGroupInfo
nameRoleGroup(const ItemData
*itemData
, bool withString
= true) const;
476 ItemGroupInfo
sizeRoleGroup(const ItemData
*itemData
, bool withString
= true) const;
477 ItemGroupInfo
timeRoleGroup(const std::function
<QDateTime(const ItemData
*)> &fileTimeCb
, const ItemData
*itemData
, bool withString
= true) const;
478 ItemGroupInfo
permissionRoleGroup(const ItemData
*itemData
, bool withString
= true) const;
479 ItemGroupInfo
ratingRoleGroup(const ItemData
*itemData
, bool withString
= true) const;
480 ItemGroupInfo
typeRoleGroup(const ItemData
*itemData
) const;
481 ItemGroupInfo
genericStringRoleGroup(const QByteArray
&role
, const ItemData
*itemData
) const;
483 QList
<QPair
<int, QVariant
>> nameRoleGroups() const;
484 QList
<QPair
<int, QVariant
>> sizeRoleGroups() const;
485 QList
<QPair
<int, QVariant
>> timeRoleGroups(const std::function
<QDateTime(const ItemData
*)> &fileTimeCb
) const;
486 QList
<QPair
<int, QVariant
>> permissionRoleGroups() const;
487 QList
<QPair
<int, QVariant
>> ratingRoleGroups() const;
488 QList
<QPair
<int, QVariant
>> typeRoleGroups() const;
489 QList
<QPair
<int, QVariant
>> genericStringRoleGroups(const QByteArray
&typeForRole
) const;
492 * Helper method for all xxxRoleGroups() methods to check whether the
493 * item with the given index is a child-item. A child-item is defined
494 * as item having an expansion-level > 0. All xxxRoleGroups() methods
495 * should skip the grouping if the item is a child-item (although
496 * KItemListView would be capable to show sub-groups in groups this
497 * results in visual clutter for most usecases).
499 bool isChildItem(int index
) const;
501 void scheduleResortAllItems();
504 * Is invoked by KFileItemModelRolesUpdater and results in emitting the
505 * sortProgress signal with a percent-value of the progress.
507 void emitSortProgress(int resolvedCount
);
510 * Applies the filters set through @ref setNameFilter and @ref setMimeTypeFilters.
515 * Removes filtered items whose expanded parents have been deleted
516 * or collapsed via setExpanded(parentIndex, false).
518 void removeFilteredChildren(const KItemRangeList
&parents
);
521 * Loads the selected choice of sorting method from Dolphin General Settings
523 void loadSortingSettings();
526 * Maps the QByteArray-roles to RoleTypes and provides translation- and
530 const char *const role
;
531 const RoleType roleType
;
532 const KLazyLocalizedString roleTranslation
;
533 const KLazyLocalizedString groupTranslation
;
534 const KLazyLocalizedString tooltipTranslation
;
535 const bool requiresBaloo
;
536 const bool requiresIndexer
;
540 * @return Map of user visible roles that are accessible by KFileItemModel::rolesInformation().
542 static const RoleInfoMap
*rolesInfoMap(int &count
);
545 * Determines the MIME-types of all items that can be done within
548 static void determineMimeTypes(const KFileItemList
&items
, int timeout
);
551 * @return Returns a copy of \a value that is implicitly shared
552 * with other users to save memory.
554 static QByteArray
sharedValue(const QByteArray
&value
);
557 * Checks if the model's internal data structures are consistent.
559 bool isConsistent() const;
562 * Filters out the expanded folders that don't pass the filter themselves and don't have any filter-passing children.
563 * Will update the removedItemRanges arguments to include the parents that have been filtered.
564 * @returns the number of parents that have been filtered.
565 * @param removedItemRanges The ranges of items being deleted/filtered, will get updated
566 * @param parentsToEnsureVisible Parents that must be visible no matter what due to being ancestors of newly visible items
568 int filterChildlessParents(KItemRangeList
&removedItemRanges
, const QSet
<ItemData
*> &parentsToEnsureVisible
= QSet
<ItemData
*>());
571 KDirLister
*m_dirLister
= nullptr;
573 QCollator m_collator
;
574 bool m_naturalSorting
;
575 bool m_sortDirsFirst
;
576 bool m_sortHiddenLast
;
580 RoleType m_groupRole
;
581 QByteArray m_sortExtraInfo
;
582 QByteArray m_groupExtraInfo
;
584 int m_sortingProgressPercent
; // Value of directorySortingProgress() signal
585 QSet
<QByteArray
> m_roles
;
587 QList
<ItemData
*> m_itemData
;
589 // m_items is a cache for the method index(const QUrl&). If it contains N
590 // entries, it is guaranteed that these correspond to the first N items in
591 // the model, i.e., that (for every i between 0 and N - 1)
592 // m_items.value(fileItem(i).url()) == i
593 mutable QHash
<QUrl
, int> m_items
;
595 KFileItemModelFilter m_filter
;
596 QHash
<KFileItem
, ItemData
*> m_filteredItems
; // Items that got hidden by KFileItemModel::setNameFilter()
598 bool m_requestRole
[RolesCount
];
600 QTimer
*m_maximumUpdateIntervalTimer
;
601 QTimer
*m_resortAllItemsTimer
;
602 QList
<ItemData
*> m_pendingItemsToInsert
;
604 // Cache for KFileItemModel::groups()
605 mutable QList
<QPair
<int, QVariant
>> m_groups
;
607 // Stores the URLs (key: target url, value: url) of the expanded directories.
608 QHash
<QUrl
, QUrl
> m_expandedDirs
;
610 // URLs that must be expanded. The expanding is initially triggered in setExpanded()
611 // and done step after step in slotCompleted().
612 QSet
<QUrl
> m_urlsToExpand
;
614 friend class KFileItemModelRolesUpdater
; // Accesses emitSortProgress() method
615 friend class KFileItemModelTest
; // For unit testing
616 friend class KFileItemModelBenchmark
; // For unit testing
617 friend class KFileItemListViewTest
; // For unit testing
618 friend class DolphinPart
; // Accesses m_dirLister
621 inline bool KFileItemModel::isRoleValueNatural(RoleType roleType
)
623 return (roleType
== TypeRole
|| roleType
== ExtensionRole
|| roleType
== TagsRole
|| roleType
== CommentRole
|| roleType
== TitleRole
624 || roleType
== ArtistRole
|| roleType
== GenreRole
|| roleType
== AlbumRole
|| roleType
== PathRole
|| roleType
== DestinationRole
625 || roleType
== OriginUrlRole
|| roleType
== OwnerRole
|| roleType
== GroupRole
);
628 inline bool KFileItemModel::nameLessThan(const ItemData
*a
, const ItemData
*b
)
630 return a
->item
.text() < b
->item
.text();
633 inline bool KFileItemModel::isChildItem(int index
) const
635 if (m_itemData
.at(index
)->parent
) {
642 inline bool KFileItemModel::ItemGroupInfo::operator==(const ItemGroupInfo
&other
) const
644 return comparable
== other
.comparable
&& text
== other
.text
;
647 inline bool KFileItemModel::ItemGroupInfo::operator!=(const ItemGroupInfo
&other
) const
649 return comparable
!= other
.comparable
|| text
!= other
.text
;