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