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