]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kfileitemmodel.h
Configurable Show hidden files and folders last toggle
[dolphin.git] / src / kitemviews / kfileitemmodel.h
1 /*
2 * SPDX-FileCopyrightText: 2011 Peter Penz <peter.penz19@gmail.com>
3 *
4 * SPDX-License-Identifier: GPL-2.0-or-later
5 */
6
7 #ifndef KFILEITEMMODEL_H
8 #define KFILEITEMMODEL_H
9
10 #include "dolphin_export.h"
11 #include "kitemviews/kitemmodelbase.h"
12 #include "kitemviews/private/kfileitemmodelfilter.h"
13
14 #include <KFileItem>
15
16 #include <QCollator>
17 #include <QHash>
18 #include <QSet>
19 #include <QUrl>
20
21 #include <functional>
22
23 class KFileItemModelDirLister;
24 class QTimer;
25
26 /**
27 * @brief KItemModelBase implementation for KFileItems.
28 *
29 * Allows to load items of a directory. Sorting and grouping of
30 * items are supported. Roles that are not part of KFileItem can
31 * be added with KFileItemModel::setData().
32 *
33 * Recursive expansion of sub-directories is supported by
34 * KFileItemModel::setExpanded().
35 */
36 class DOLPHIN_EXPORT KFileItemModel : public KItemModelBase
37 {
38 Q_OBJECT
39
40 public:
41 explicit KFileItemModel(QObject* parent = nullptr);
42 ~KFileItemModel() override;
43
44 /**
45 * Loads the directory specified by \a url. The signals
46 * directoryLoadingStarted(), directoryLoadingProgress() and directoryLoadingCompleted()
47 * indicate the current state of the loading process. The items
48 * of the directory are added after the loading has been completed.
49 */
50 void loadDirectory(const QUrl& url);
51
52 /**
53 * Throws away all currently loaded items and refreshes the directory
54 * by reloading all items again.
55 */
56 void refreshDirectory(const QUrl& url);
57
58 /**
59 * @return Parent directory of the items that are shown. In case
60 * if a directory tree is shown, KFileItemModel::dir() returns
61 * the root-parent of all items.
62 * @see rootItem()
63 */
64 QUrl directory() const override;
65
66 /**
67 * Cancels the loading of a directory which has been started by either
68 * loadDirectory() or refreshDirectory().
69 */
70 void cancelDirectoryLoading();
71
72 int count() const override;
73 QHash<QByteArray, QVariant> data(int index) const override;
74 bool setData(int index, const QHash<QByteArray, QVariant>& values) override;
75
76 /**
77 * Sets a separate sorting with directories first (true) or a mixed
78 * sorting of files and directories (false).
79 */
80 void setSortDirectoriesFirst(bool dirsFirst);
81 bool sortDirectoriesFirst() const;
82
83 /**
84 * Sets a separate sorting with hidden files and folders last (true) or not (false).
85 */
86 void setSortHiddenLast(bool hiddenLast);
87 bool sortHiddenLast() const;
88
89 void setShowHiddenFiles(bool show);
90 bool showHiddenFiles() const;
91
92 /**
93 * If set to true, only directories are shown as items of the model. Files
94 * are ignored.
95 */
96 void setShowDirectoriesOnly(bool enabled);
97 bool showDirectoriesOnly() const;
98
99 QMimeData* createMimeData(const KItemSet& indexes) const override;
100
101 int indexForKeyboardSearch(const QString& text, int startFromIndex = 0) const override;
102
103 bool supportsDropping(int index) const override;
104
105 QString roleDescription(const QByteArray& role) const override;
106
107 QList<QPair<int, QVariant> > groups() const override;
108
109 /**
110 * @return The file-item for the index \a index. If the index is in a valid
111 * range it is assured that the file-item is not null. The runtime
112 * complexity of this call is O(1).
113 */
114 KFileItem fileItem(int index) const;
115
116 /**
117 * @return The file-item for the url \a url. If no file-item with the given
118 * URL is found KFileItem::isNull() will be true for the returned
119 * file-item. The runtime complexity of this call is O(1).
120 */
121 KFileItem fileItem(const QUrl& url) const;
122
123 /**
124 * @return The index for the file-item \a item. -1 is returned if no file-item
125 * is found or if the file-item is null. The amortized runtime
126 * complexity of this call is O(1).
127 */
128 int index(const KFileItem& item) const;
129
130 /**
131 * @return The index for the URL \a url. -1 is returned if no file-item
132 * is found. The amortized runtime complexity of this call is O(1).
133 */
134 int index(const QUrl &url) const;
135
136 /**
137 * @return Root item of all items representing the item
138 * for KFileItemModel::dir().
139 */
140 KFileItem rootItem() const;
141
142 /**
143 * Clears all items of the model.
144 */
145 void clear();
146
147 /**
148 * Sets the roles that should be shown for each item.
149 */
150 void setRoles(const QSet<QByteArray>& roles);
151 QSet<QByteArray> roles() const;
152
153 bool setExpanded(int index, bool expanded) override;
154 bool isExpanded(int index) const override;
155 bool isExpandable(int index) const override;
156 int expandedParentsCount(int index) const override;
157
158 QSet<QUrl> expandedDirectories() const;
159
160 /**
161 * Marks the URLs in \a urls as sub-directories which were expanded previously.
162 * After calling loadDirectory() or refreshDirectory() the marked sub-directories
163 * will be expanded step-by-step.
164 */
165 void restoreExpandedDirectories(const QSet<QUrl>& urls);
166
167 /**
168 * Expands all parent-directories of the item \a url.
169 */
170 void expandParentDirectories(const QUrl& url);
171
172 void setNameFilter(const QString& nameFilter);
173 QString nameFilter() const;
174
175 void setMimeTypeFilters(const QStringList& filters);
176 QStringList mimeTypeFilters() const;
177
178 struct RoleInfo
179 { QByteArray role;
180 QString translation;
181 QString group;
182 bool requiresBaloo;
183 bool requiresIndexer;
184 };
185
186 /**
187 * @return Provides static information for all available roles that
188 * are supported by KFileItemModel. Some roles can only be
189 * determined if Baloo is enabled and/or the Baloo
190 * indexing is enabled.
191 */
192 static QList<RoleInfo> rolesInformation();
193
194 Q_SIGNALS:
195 /**
196 * Is emitted if the loading of a directory has been started. It is
197 * assured that a signal directoryLoadingCompleted() will be send after
198 * the loading has been finished. For tracking the loading progress
199 * the signal directoryLoadingProgress() gets emitted in between.
200 */
201 void directoryLoadingStarted();
202
203 /**
204 * Is emitted after the loading of a directory has been completed or new
205 * items have been inserted to an already loaded directory. Usually
206 * one or more itemsInserted() signals are emitted before loadingCompleted()
207 * (the only exception is loading an empty directory, where only a
208 * loadingCompleted() signal gets emitted).
209 */
210 void directoryLoadingCompleted();
211
212 /**
213 * Is emitted after the loading of a directory has been canceled.
214 */
215 void directoryLoadingCanceled();
216
217 /**
218 * Informs about the progress in percent when loading a directory. It is assured
219 * that the signal directoryLoadingStarted() has been emitted before.
220 */
221 void directoryLoadingProgress(int percent);
222
223 /**
224 * Is emitted if the sort-role gets resolved asynchronously and provides
225 * the progress-information of the sorting in percent. It is assured
226 * that the last sortProgress-signal contains 100 as value.
227 */
228 void directorySortingProgress(int percent);
229
230 /**
231 * Is emitted if an information message (e.g. "Connecting to host...")
232 * should be shown.
233 */
234 void infoMessage(const QString& message);
235
236 /**
237 * Is emitted if an error message (e.g. "Unknown location")
238 * should be shown.
239 */
240 void errorMessage(const QString& message);
241
242 /**
243 * Is emitted if a redirection from the current URL \a oldUrl
244 * to the new URL \a newUrl has been done.
245 */
246 void directoryRedirection(const QUrl& oldUrl, const QUrl& newUrl);
247
248 /**
249 * Is emitted when the URL passed by KFileItemModel::setUrl() represents a file.
250 * In this case no signal errorMessage() will be emitted.
251 */
252 void urlIsFileError(const QUrl& url);
253
254 /**
255 * It is emitted for files when they change and
256 * for dirs when files are added or removed.
257 */
258 void fileItemsChanged(const KFileItemList &changedFileItems);
259
260 protected:
261 void onGroupedSortingChanged(bool current) override;
262 void onSortRoleChanged(const QByteArray& current, const QByteArray& previous, bool resortItems = true) override;
263 void onSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous) override;
264
265 private Q_SLOTS:
266 /**
267 * Resorts all items dependent on the set sortRole(), sortOrder()
268 * and foldersFirst() settings.
269 */
270 void resortAllItems();
271
272 void slotCompleted();
273 void slotCanceled();
274 void slotItemsAdded(const QUrl& directoryUrl, const KFileItemList& items);
275 void slotItemsDeleted(const KFileItemList& items);
276 void slotRefreshItems(const QList<QPair<KFileItem, KFileItem> >& items);
277 void slotClear();
278 void slotSortingChoiceChanged();
279
280 void dispatchPendingItemsToInsert();
281
282 private:
283 enum RoleType {
284 // User visible roles:
285 NoRole, NameRole, SizeRole, ModificationTimeRole, CreationTimeRole, AccessTimeRole, PermissionsRole, OwnerRole,
286 GroupRole, TypeRole, DestinationRole, PathRole, DeletionTimeRole,
287 // User visible roles available with Baloo:
288 CommentRole, TagsRole, RatingRole, WidthRole, HeightRole, ImageDateTimeRole, OrientationRole,
289 WordCountRole, TitleRole, LineCountRole, ArtistRole, GenreRole, AlbumRole, DurationRole, TrackRole, ReleaseYearRole,
290 BitrateRole, OriginUrlRole, AspectRatioRole, FrameRateRole,
291 // Non-visible roles:
292 IsDirRole, IsLinkRole, IsHiddenRole, IsExpandedRole, IsExpandableRole, ExpandedParentsCountRole,
293 // Mandatory last entry:
294 RolesCount
295 };
296
297 struct ItemData
298 {
299 KFileItem item;
300 QHash<QByteArray, QVariant> values;
301 ItemData* parent;
302 };
303
304 enum RemoveItemsBehavior {
305 KeepItemData,
306 DeleteItemData
307 };
308
309 void insertItems(QList<ItemData*>& items);
310 void removeItems(const KItemRangeList& itemRanges, RemoveItemsBehavior behavior);
311
312 /**
313 * Helper method for insertItems() and removeItems(): Creates
314 * a list of ItemData elements based on the given items.
315 * Note that the ItemData instances are created dynamically and
316 * must be deleted by the caller.
317 */
318 QList<ItemData*> createItemDataList(const QUrl& parentUrl, const KFileItemList& items) const;
319
320 /**
321 * Prepares the items for sorting. Normally, the hash 'values' in ItemData is filled
322 * lazily to save time and memory, but for some sort roles, it is expected that the
323 * sort role data is stored in 'values'.
324 */
325 void prepareItemsForSorting(QList<ItemData*>& itemDataList);
326
327 static int expandedParentsCount(const ItemData* data);
328
329 void removeExpandedItems();
330
331 /**
332 * This function is called by setData() and slotRefreshItems(). It emits
333 * the itemsChanged() signal, checks if the sort order is still correct,
334 * and starts m_resortAllItemsTimer if that is not the case.
335 */
336 void emitItemsChangedAndTriggerResorting(const KItemRangeList& itemRanges, const QSet<QByteArray>& changedRoles);
337
338 /**
339 * Resets all values from m_requestRole to false.
340 */
341 void resetRoles();
342
343 /**
344 * @return Role-type for the given role.
345 * Runtime complexity is O(1).
346 */
347 RoleType typeForRole(const QByteArray& role) const;
348
349 /**
350 * @return Role-byte-array for the given role-type.
351 * Runtime complexity is O(1).
352 */
353 QByteArray roleForType(RoleType roleType) const;
354
355 QHash<QByteArray, QVariant> retrieveData(const KFileItem& item, const ItemData* parent) const;
356
357 /**
358 * @return True if role values benefit from natural or case insensitive sorting.
359 */
360 static bool isRoleValueNatural(const RoleType roleType);
361
362 /**
363 * @return True if \a a has a KFileItem whose text is 'less than' the one
364 * of \a b according to QString::operator<(const QString&).
365 */
366 static bool nameLessThan(const ItemData* a, const ItemData* b);
367
368 /**
369 * @return True if the item-data \a a should be ordered before the item-data
370 * \b. The item-data may have different parent-items.
371 */
372 bool lessThan(const ItemData* a, const ItemData* b, const QCollator& collator) const;
373
374 /**
375 * Sorts the items between \a begin and \a end using the comparison
376 * function lessThan().
377 */
378 void sort(const QList<ItemData*>::iterator &begin, const QList<ItemData*>::iterator &end) const;
379
380 /**
381 * Helper method for lessThan() and expandedParentsCountCompare(): Compares
382 * the passed item-data using m_sortRole as criteria. Both items must
383 * have the same parent item, otherwise the comparison will be wrong.
384 */
385 int sortRoleCompare(const ItemData* a, const ItemData* b, const QCollator& collator) const;
386
387 int stringCompare(const QString& a, const QString& b, const QCollator& collator) const;
388
389 QList<QPair<int, QVariant> > nameRoleGroups() const;
390 QList<QPair<int, QVariant> > sizeRoleGroups() const;
391 QList<QPair<int, QVariant> > timeRoleGroups(const std::function<QDateTime(const ItemData *)> &fileTimeCb) const;
392 QList<QPair<int, QVariant> > permissionRoleGroups() const;
393 QList<QPair<int, QVariant> > ratingRoleGroups() const;
394 QList<QPair<int, QVariant> > genericStringRoleGroups(const QByteArray& typeForRole) const;
395
396 /**
397 * Helper method for all xxxRoleGroups() methods to check whether the
398 * item with the given index is a child-item. A child-item is defined
399 * as item having an expansion-level > 0. All xxxRoleGroups() methods
400 * should skip the grouping if the item is a child-item (although
401 * KItemListView would be capable to show sub-groups in groups this
402 * results in visual clutter for most usecases).
403 */
404 bool isChildItem(int index) const;
405
406 /**
407 * Is invoked by KFileItemModelRolesUpdater and results in emitting the
408 * sortProgress signal with a percent-value of the progress.
409 */
410 void emitSortProgress(int resolvedCount);
411
412 /**
413 * Applies the filters set through @ref setNameFilter and @ref setMimeTypeFilters.
414 */
415 void applyFilters();
416
417 /**
418 * Removes filtered items whose expanded parents have been deleted
419 * or collapsed via setExpanded(parentIndex, false).
420 */
421 void removeFilteredChildren(const KItemRangeList& parents);
422
423 /**
424 * Loads the selected choice of sorting method from Dolphin General Settings
425 */
426 void loadSortingSettings();
427
428 /**
429 * Maps the QByteArray-roles to RoleTypes and provides translation- and
430 * group-contexts.
431 */
432 struct RoleInfoMap
433 {
434 const char* const role;
435 const RoleType roleType;
436 const char* const roleTranslationContext;
437 const char* const roleTranslation;
438 const char* const groupTranslationContext;
439 const char* const groupTranslation;
440 const bool requiresBaloo;
441 const bool requiresIndexer;
442 };
443
444 /**
445 * @return Map of user visible roles that are accessible by KFileItemModel::rolesInformation().
446 */
447 static const RoleInfoMap* rolesInfoMap(int& count);
448
449 /**
450 * Determines the MIME-types of all items that can be done within
451 * the given timeout.
452 */
453 static void determineMimeTypes(const KFileItemList& items, int timeout);
454
455 /**
456 * @return Returns a copy of \a value that is implicitly shared
457 * with other users to save memory.
458 */
459 static QByteArray sharedValue(const QByteArray& value);
460
461 /**
462 * Checks if the model's internal data structures are consistent.
463 */
464 bool isConsistent() const;
465
466 private:
467 KFileItemModelDirLister* m_dirLister;
468
469 QCollator m_collator;
470 bool m_naturalSorting;
471 bool m_sortDirsFirst;
472 bool m_sortHiddenLast;
473
474 RoleType m_sortRole;
475 int m_sortingProgressPercent; // Value of directorySortingProgress() signal
476 QSet<QByteArray> m_roles;
477
478 QList<ItemData*> m_itemData;
479
480 // m_items is a cache for the method index(const QUrl&). If it contains N
481 // entries, it is guaranteed that these correspond to the first N items in
482 // the model, i.e., that (for every i between 0 and N - 1)
483 // m_items.value(fileItem(i).url()) == i
484 mutable QHash<QUrl, int> m_items;
485
486 KFileItemModelFilter m_filter;
487 QHash<KFileItem, ItemData*> m_filteredItems; // Items that got hidden by KFileItemModel::setNameFilter()
488
489 bool m_requestRole[RolesCount];
490
491 QTimer* m_maximumUpdateIntervalTimer;
492 QTimer* m_resortAllItemsTimer;
493 QList<ItemData*> m_pendingItemsToInsert;
494
495 // Cache for KFileItemModel::groups()
496 mutable QList<QPair<int, QVariant> > m_groups;
497
498 // Stores the URLs (key: target url, value: url) of the expanded directories.
499 QHash<QUrl, QUrl> m_expandedDirs;
500
501 // URLs that must be expanded. The expanding is initially triggered in setExpanded()
502 // and done step after step in slotCompleted().
503 QSet<QUrl> m_urlsToExpand;
504
505 friend class KFileItemModelRolesUpdater; // Accesses emitSortProgress() method
506 friend class KFileItemModelTest; // For unit testing
507 friend class KFileItemModelBenchmark; // For unit testing
508 friend class KFileItemListViewTest; // For unit testing
509 friend class DolphinPart; // Accesses m_dirLister
510 };
511
512 inline bool KFileItemModel::isRoleValueNatural(RoleType roleType)
513 {
514 return (roleType == TypeRole ||
515 roleType == TagsRole ||
516 roleType == CommentRole ||
517 roleType == TitleRole ||
518 roleType == ArtistRole ||
519 roleType == GenreRole ||
520 roleType == AlbumRole ||
521 roleType == PathRole ||
522 roleType == DestinationRole ||
523 roleType == OriginUrlRole ||
524 roleType == OwnerRole ||
525 roleType == GroupRole);
526 }
527
528 inline bool KFileItemModel::nameLessThan(const ItemData* a, const ItemData* b)
529 {
530 return a->item.text() < b->item.text();
531 }
532
533 inline bool KFileItemModel::isChildItem(int index) const
534 {
535 if (m_itemData.at(index)->parent) {
536 return true;
537 } else {
538 return false;
539 }
540 }
541
542 #endif
543
544