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