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