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