]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kfileitemmodel.h
Merge branch 'release/21.12'
[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 DeleteItemDataIfUnfiltered
314 };
315
316 void insertItems(QList<ItemData*>& items);
317 void removeItems(const KItemRangeList& itemRanges, RemoveItemsBehavior behavior);
318
319 /**
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.
324 */
325 QList<ItemData*> createItemDataList(const QUrl& parentUrl, const KFileItemList& items) const;
326
327 /**
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'.
331 */
332 void prepareItemsForSorting(QList<ItemData*>& itemDataList);
333
334 static int expandedParentsCount(const ItemData* data);
335
336 void removeExpandedItems();
337
338 /**
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.
342 */
343 void emitItemsChangedAndTriggerResorting(const KItemRangeList& itemRanges, const QSet<QByteArray>& changedRoles);
344
345 /**
346 * Resets all values from m_requestRole to false.
347 */
348 void resetRoles();
349
350 /**
351 * @return Role-type for the given role.
352 * Runtime complexity is O(1).
353 */
354 RoleType typeForRole(const QByteArray& role) const;
355
356 /**
357 * @return Role-byte-array for the given role-type.
358 * Runtime complexity is O(1).
359 */
360 QByteArray roleForType(RoleType roleType) const;
361
362 QHash<QByteArray, QVariant> retrieveData(const KFileItem& item, const ItemData* parent) const;
363
364 /**
365 * @return True if role values benefit from natural or case insensitive sorting.
366 */
367 static bool isRoleValueNatural(const RoleType roleType);
368
369 /**
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&).
372 */
373 static bool nameLessThan(const ItemData* a, const ItemData* b);
374
375 /**
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.
378 */
379 bool lessThan(const ItemData* a, const ItemData* b, const QCollator& collator) const;
380
381 /**
382 * Sorts the items between \a begin and \a end using the comparison
383 * function lessThan().
384 */
385 void sort(const QList<ItemData*>::iterator &begin, const QList<ItemData*>::iterator &end) const;
386
387 /**
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.
391 */
392 int sortRoleCompare(const ItemData* a, const ItemData* b, const QCollator& collator) const;
393
394 int stringCompare(const QString& a, const QString& b, const QCollator& collator) const;
395
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;
402
403 /**
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).
410 */
411 bool isChildItem(int index) const;
412
413 /**
414 * Is invoked by KFileItemModelRolesUpdater and results in emitting the
415 * sortProgress signal with a percent-value of the progress.
416 */
417 void emitSortProgress(int resolvedCount);
418
419 /**
420 * Applies the filters set through @ref setNameFilter and @ref setMimeTypeFilters.
421 */
422 void applyFilters();
423
424 /**
425 * Removes filtered items whose expanded parents have been deleted
426 * or collapsed via setExpanded(parentIndex, false).
427 */
428 void removeFilteredChildren(const KItemRangeList& parents);
429
430 /**
431 * Loads the selected choice of sorting method from Dolphin General Settings
432 */
433 void loadSortingSettings();
434
435 /**
436 * Maps the QByteArray-roles to RoleTypes and provides translation- and
437 * group-contexts.
438 */
439 struct RoleInfoMap
440 {
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;
449 };
450
451 /**
452 * @return Map of user visible roles that are accessible by KFileItemModel::rolesInformation().
453 */
454 static const RoleInfoMap* rolesInfoMap(int& count);
455
456 /**
457 * Determines the MIME-types of all items that can be done within
458 * the given timeout.
459 */
460 static void determineMimeTypes(const KFileItemList& items, int timeout);
461
462 /**
463 * @return Returns a copy of \a value that is implicitly shared
464 * with other users to save memory.
465 */
466 static QByteArray sharedValue(const QByteArray& value);
467
468 /**
469 * Checks if the model's internal data structures are consistent.
470 */
471 bool isConsistent() const;
472
473 /**
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
479 */
480 int filterChildlessParents(KItemRangeList &removedItemRanges, const QSet<ItemData *> &parentsToEnsureVisible = QSet<ItemData *>());
481
482 private:
483 KDirLister *m_dirLister = nullptr;
484
485 QCollator m_collator;
486 bool m_naturalSorting;
487 bool m_sortDirsFirst;
488 bool m_sortHiddenLast;
489
490 RoleType m_sortRole;
491 int m_sortingProgressPercent; // Value of directorySortingProgress() signal
492 QSet<QByteArray> m_roles;
493
494 QList<ItemData*> m_itemData;
495
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;
501
502 KFileItemModelFilter m_filter;
503 QHash<KFileItem, ItemData*> m_filteredItems; // Items that got hidden by KFileItemModel::setNameFilter()
504
505 bool m_requestRole[RolesCount];
506
507 QTimer* m_maximumUpdateIntervalTimer;
508 QTimer* m_resortAllItemsTimer;
509 QList<ItemData*> m_pendingItemsToInsert;
510
511 // Cache for KFileItemModel::groups()
512 mutable QList<QPair<int, QVariant> > m_groups;
513
514 // Stores the URLs (key: target url, value: url) of the expanded directories.
515 QHash<QUrl, QUrl> m_expandedDirs;
516
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;
520
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
526 };
527
528 inline bool KFileItemModel::isRoleValueNatural(RoleType roleType)
529 {
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);
542 }
543
544 inline bool KFileItemModel::nameLessThan(const ItemData* a, const ItemData* b)
545 {
546 return a->item.text() < b->item.text();
547 }
548
549 inline bool KFileItemModel::isChildItem(int index) const
550 {
551 if (m_itemData.at(index)->parent) {
552 return true;
553 } else {
554 return false;
555 }
556 }
557
558 #endif
559
560