]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kfileitemmodel.h
Merge branch 'Applications/17.08'
[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 <KFileItem>
25 #include <QUrl>
26 #include <kitemviews/kitemmodelbase.h>
27 #include <kitemviews/private/kfileitemmodelfilter.h>
28
29 #include <QCollator>
30 #include <QHash>
31 #include <QSet>
32
33 #include <functional>
34
35 class KFileItemModelDirLister;
36 class QTimer;
37
38 /**
39 * @brief KItemModelBase implementation for KFileItems.
40 *
41 * Allows to load items of a directory. Sorting and grouping of
42 * items are supported. Roles that are not part of KFileItem can
43 * be added with KFileItemModel::setData().
44 *
45 * Recursive expansion of sub-directories is supported by
46 * KFileItemModel::setExpanded().
47 */
48 class DOLPHIN_EXPORT KFileItemModel : public KItemModelBase
49 {
50 Q_OBJECT
51
52 public:
53 explicit KFileItemModel(QObject* parent = 0);
54 virtual ~KFileItemModel();
55
56 /**
57 * Loads the directory specified by \a url. The signals
58 * directoryLoadingStarted(), directoryLoadingProgress() and directoryLoadingCompleted()
59 * indicate the current state of the loading process. The items
60 * of the directory are added after the loading has been completed.
61 */
62 void loadDirectory(const QUrl& url);
63
64 /**
65 * Throws away all currently loaded items and refreshes the directory
66 * by reloading all items again.
67 */
68 void refreshDirectory(const QUrl& url);
69
70 /**
71 * @return Parent directory of the items that are shown. In case
72 * if a directory tree is shown, KFileItemModel::dir() returns
73 * the root-parent of all items.
74 * @see rootItem()
75 */
76 QUrl directory() const;
77
78 /**
79 * Cancels the loading of a directory which has been started by either
80 * loadDirectory() or refreshDirectory().
81 */
82 void cancelDirectoryLoading();
83
84 virtual int count() const Q_DECL_OVERRIDE;
85 virtual QHash<QByteArray, QVariant> data(int index) const Q_DECL_OVERRIDE;
86 virtual bool setData(int index, const QHash<QByteArray, QVariant>& values) Q_DECL_OVERRIDE;
87
88 /**
89 * Sets a separate sorting with directories first (true) or a mixed
90 * sorting of files and directories (false).
91 */
92 void setSortDirectoriesFirst(bool dirsFirst);
93 bool sortDirectoriesFirst() 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 virtual QMimeData* createMimeData(const KItemSet& indexes) const Q_DECL_OVERRIDE;
106
107 virtual int indexForKeyboardSearch(const QString& text, int startFromIndex = 0) const Q_DECL_OVERRIDE;
108
109 virtual bool supportsDropping(int index) const Q_DECL_OVERRIDE;
110
111 virtual QString roleDescription(const QByteArray& role) const Q_DECL_OVERRIDE;
112
113 virtual QList<QPair<int, QVariant> > groups() const Q_DECL_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 virtual bool setExpanded(int index, bool expanded) Q_DECL_OVERRIDE;
160 virtual bool isExpanded(int index) const Q_DECL_OVERRIDE;
161 virtual bool isExpandable(int index) const Q_DECL_OVERRIDE;
162 virtual int expandedParentsCount(int index) const Q_DECL_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 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 protected:
261 virtual void onGroupedSortingChanged(bool current) Q_DECL_OVERRIDE;
262 virtual void onSortRoleChanged(const QByteArray& current, const QByteArray& previous) Q_DECL_OVERRIDE;
263 virtual void onSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous) Q_DECL_OVERRIDE;
264
265 private slots:
266 /**
267 * Resorts all items dependent on the set sortRole(), sortOrder()
268 * and foldersFirst() settings.
269 */
270 void resortAllItems();
271
272 void slotCompleted();
273 void slotCanceled();
274 void slotItemsAdded(const QUrl& directoryUrl, const KFileItemList& items);
275 void slotItemsDeleted(const KFileItemList& items);
276 void slotRefreshItems(const QList<QPair<KFileItem, KFileItem> >& items);
277 void slotClear();
278 void slotSortingChoiceChanged();
279
280 void dispatchPendingItemsToInsert();
281
282 private:
283 enum RoleType {
284 // User visible roles:
285 NoRole, NameRole, SizeRole, ModificationTimeRole, CreationTimeRole, AccessTimeRole, PermissionsRole, OwnerRole,
286 GroupRole, TypeRole, DestinationRole, PathRole, DeletionTimeRole,
287 // User visible roles available with Baloo:
288 CommentRole, TagsRole, RatingRole, ImageSizeRole, OrientationRole,
289 WordCountRole, TitleRole, LineCountRole, ArtistRole, GenreRole, AlbumRole, DurationRole, TrackRole, ReleaseYearRole,
290 OriginUrlRole,
291 // Non-visible roles:
292 IsDirRole, IsLinkRole, IsHiddenRole, IsExpandedRole, IsExpandableRole, ExpandedParentsCountRole,
293 // Mandatory last entry:
294 RolesCount
295 };
296
297 struct ItemData
298 {
299 KFileItem item;
300 QHash<QByteArray, QVariant> values;
301 ItemData* parent;
302 };
303
304 enum RemoveItemsBehavior {
305 KeepItemData,
306 DeleteItemData
307 };
308
309 void insertItems(QList<ItemData*>& items);
310 void removeItems(const KItemRangeList& itemRanges, RemoveItemsBehavior behavior);
311
312 /**
313 * Helper method for insertItems() and removeItems(): Creates
314 * a list of ItemData elements based on the given items.
315 * Note that the ItemData instances are created dynamically and
316 * must be deleted by the caller.
317 */
318 QList<ItemData*> createItemDataList(const QUrl& parentUrl, const KFileItemList& items) const;
319
320 /**
321 * Prepares the items for sorting. Normally, the hash 'values' in ItemData is filled
322 * lazily to save time and memory, but for some sort roles, it is expected that the
323 * sort role data is stored in 'values'.
324 */
325 void prepareItemsForSorting(QList<ItemData*>& itemDataList);
326
327 static int expandedParentsCount(const ItemData* data);
328
329 void removeExpandedItems();
330
331 /**
332 * This function is called by setData() and slotRefreshItems(). It emits
333 * the itemsChanged() signal, checks if the sort order is still correct,
334 * and starts m_resortAllItemsTimer if that is not the case.
335 */
336 void emitItemsChangedAndTriggerResorting(const KItemRangeList& itemRanges, const QSet<QByteArray>& changedRoles);
337
338 /**
339 * Resets all values from m_requestRole to false.
340 */
341 void resetRoles();
342
343 /**
344 * @return Role-type for the given role.
345 * Runtime complexity is O(1).
346 */
347 RoleType typeForRole(const QByteArray& role) const;
348
349 /**
350 * @return Role-byte-array for the given role-type.
351 * Runtime complexity is O(1).
352 */
353 QByteArray roleForType(RoleType roleType) const;
354
355 QHash<QByteArray, QVariant> retrieveData(const KFileItem& item, const ItemData* parent) const;
356
357 /**
358 * @return True if \a a has a KFileItem whose text is 'less than' the one
359 * of \a b according to QString::operator<(const QString&).
360 */
361 static bool nameLessThan(const ItemData* a, const ItemData* b);
362
363 /**
364 * @return True if the item-data \a a should be ordered before the item-data
365 * \b. The item-data may have different parent-items.
366 */
367 bool lessThan(const ItemData* a, const ItemData* b, const QCollator& collator) const;
368
369 /**
370 * Sorts the items between \a begin and \a end using the comparison
371 * function lessThan().
372 */
373 void sort(QList<ItemData*>::iterator begin, QList<ItemData*>::iterator end) const;
374
375 /**
376 * Helper method for lessThan() and expandedParentsCountCompare(): Compares
377 * the passed item-data using m_sortRole as criteria. Both items must
378 * have the same parent item, otherwise the comparison will be wrong.
379 */
380 int sortRoleCompare(const ItemData* a, const ItemData* b, const QCollator& collator) const;
381
382 int stringCompare(const QString& a, const QString& b, const QCollator& collator) const;
383
384 bool useMaximumUpdateInterval() const;
385
386 QList<QPair<int, QVariant> > nameRoleGroups() const;
387 QList<QPair<int, QVariant> > sizeRoleGroups() const;
388 QList<QPair<int, QVariant> > timeRoleGroups(std::function<QDateTime(const ItemData *)> fileTimeCb) const;
389 QList<QPair<int, QVariant> > permissionRoleGroups() const;
390 QList<QPair<int, QVariant> > ratingRoleGroups() const;
391 QList<QPair<int, QVariant> > genericStringRoleGroups(const QByteArray& typeForRole) const;
392
393 /**
394 * Helper method for all xxxRoleGroups() methods to check whether the
395 * item with the given index is a child-item. A child-item is defined
396 * as item having an expansion-level > 0. All xxxRoleGroups() methods
397 * should skip the grouping if the item is a child-item (although
398 * KItemListView would be capable to show sub-groups in groups this
399 * results in visual clutter for most usecases).
400 */
401 bool isChildItem(int index) const;
402
403 /**
404 * Is invoked by KFileItemModelRolesUpdater and results in emitting the
405 * sortProgress signal with a percent-value of the progress.
406 */
407 void emitSortProgress(int resolvedCount);
408
409 /**
410 * Applies the filters set through @ref setNameFilter and @ref setMimeTypeFilters.
411 */
412 void applyFilters();
413
414 /**
415 * Removes filtered items whose expanded parents have been deleted
416 * or collapsed via setExpanded(parentIndex, false).
417 */
418 void removeFilteredChildren(const KItemRangeList& parents);
419
420 /**
421 * Loads the selected choice of sorting method from Dolphin General Settings
422 */
423 void loadSortingSettings();
424
425 /**
426 * Maps the QByteArray-roles to RoleTypes and provides translation- and
427 * group-contexts.
428 */
429 struct RoleInfoMap
430 {
431 const char* const role;
432 const RoleType roleType;
433 const char* const roleTranslationContext;
434 const char* const roleTranslation;
435 const char* const groupTranslationContext;
436 const char* const groupTranslation;
437 const bool requiresBaloo;
438 const bool requiresIndexer;
439 };
440
441 /**
442 * @return Map of user visible roles that are accessible by KFileItemModel::rolesInformation().
443 */
444 static const RoleInfoMap* rolesInfoMap(int& count);
445
446 /**
447 * Determines the MIME-types of all items that can be done within
448 * the given timeout.
449 */
450 static void determineMimeTypes(const KFileItemList& items, int timeout);
451
452 /**
453 * @return Returns a copy of \a value that is implicitly shared
454 * with other users to save memory.
455 */
456 static QByteArray sharedValue(const QByteArray& value);
457
458 /**
459 * Checks if the model's internal data structures are consistent.
460 */
461 bool isConsistent() const;
462
463 private:
464 KFileItemModelDirLister* m_dirLister;
465
466 QCollator m_collator;
467 bool m_naturalSorting;
468 bool m_sortDirsFirst;
469
470 RoleType m_sortRole;
471 int m_sortingProgressPercent; // Value of directorySortingProgress() signal
472 QSet<QByteArray> m_roles;
473
474 QList<ItemData*> m_itemData;
475
476 // m_items is a cache for the method index(const QUrl&). If it contains N
477 // entries, it is guaranteed that these correspond to the first N items in
478 // the model, i.e., that (for every i between 0 and N - 1)
479 // m_items.value(fileItem(i).url()) == i
480 mutable QHash<QUrl, int> m_items;
481
482 KFileItemModelFilter m_filter;
483 QHash<KFileItem, ItemData*> m_filteredItems; // Items that got hidden by KFileItemModel::setNameFilter()
484
485 bool m_requestRole[RolesCount];
486
487 QTimer* m_maximumUpdateIntervalTimer;
488 QTimer* m_resortAllItemsTimer;
489 QList<ItemData*> m_pendingItemsToInsert;
490
491 // Cache for KFileItemModel::groups()
492 mutable QList<QPair<int, QVariant> > m_groups;
493
494 // Stores the URLs (key: target url, value: url) of the expanded directories.
495 QHash<QUrl, QUrl> m_expandedDirs;
496
497 // URLs that must be expanded. The expanding is initially triggered in setExpanded()
498 // and done step after step in slotCompleted().
499 QSet<QUrl> m_urlsToExpand;
500
501 friend class KFileItemModelLessThan; // Accesses lessThan() method
502 friend class KFileItemModelRolesUpdater; // Accesses emitSortProgress() method
503 friend class KFileItemModelTest; // For unit testing
504 friend class KFileItemModelBenchmark; // For unit testing
505 friend class KFileItemListViewTest; // For unit testing
506 friend class DolphinPart; // Accesses m_dirLister
507 };
508
509 inline bool KFileItemModel::nameLessThan(const ItemData* a, const ItemData* b)
510 {
511 return a->item.text() < b->item.text();
512 }
513
514
515 inline bool KFileItemModel::isChildItem(int index) const
516 {
517 if (m_itemData.at(index)->parent) {
518 return true;
519 } else {
520 return false;
521 }
522 }
523
524 #endif
525
526