]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kfileitemmodel.h
Do not show '-' for additional info which is not available for an item
[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 <KUrl>
26 #include <kitemviews/kitemmodelbase.h>
27 #include <kitemviews/private/kfileitemmodelfilter.h>
28
29 #include <QHash>
30
31 class KFileItemModelDirLister;
32 class QTimer;
33
34 /**
35 * @brief KItemModelBase implementation for KFileItems.
36 *
37 * Allows to load items of a directory. Sorting and grouping of
38 * items are supported. Roles that are not part of KFileItem can
39 * be added with KFileItemModel::setData().
40 *
41 * Recursive expansion of sub-directories is supported by
42 * KFileItemModel::setExpanded().
43 */
44 class LIBDOLPHINPRIVATE_EXPORT KFileItemModel : public KItemModelBase
45 {
46 Q_OBJECT
47
48 public:
49 explicit KFileItemModel(QObject* parent = 0);
50 virtual ~KFileItemModel();
51
52 /**
53 * Loads the directory specified by \a url. The signals
54 * directoryLoadingStarted(), directoryLoadingProgress() and directoryLoadingCompleted()
55 * indicate the current state of the loading process. The items
56 * of the directory are added after the loading has been completed.
57 */
58 void loadDirectory(const KUrl& url);
59
60 /**
61 * Throws away all currently loaded items and refreshes the directory
62 * by reloading all items again.
63 */
64 void refreshDirectory(const KUrl& url);
65
66 /**
67 * @return Parent directory of the items that are shown. In case
68 * if a directory tree is shown, KFileItemModel::dir() returns
69 * the root-parent of all items.
70 * @see rootItem()
71 */
72 KUrl directory() const;
73
74 /**
75 * Cancels the loading of a directory which has been started by either
76 * loadDirectory() or refreshDirectory().
77 */
78 void cancelDirectoryLoading();
79
80 virtual int count() const;
81 virtual QHash<QByteArray, QVariant> data(int index) const;
82 virtual bool setData(int index, const QHash<QByteArray, QVariant>& values);
83
84 /**
85 * Sets a separate sorting with directories first (true) or a mixed
86 * sorting of files and directories (false).
87 */
88 void setSortDirectoriesFirst(bool dirsFirst);
89 bool sortDirectoriesFirst() const;
90
91 void setShowHiddenFiles(bool show);
92 bool showHiddenFiles() const;
93
94 /**
95 * If set to true, only directories are shown as items of the model. Files
96 * are ignored.
97 */
98 void setShowDirectoriesOnly(bool enabled);
99 bool showDirectoriesOnly() const;
100
101 /** @reimp */
102 virtual QMimeData* createMimeData(const QSet<int>& indexes) const;
103
104 /** @reimp */
105 virtual int indexForKeyboardSearch(const QString& text, int startFromIndex = 0) const;
106
107 /** @reimp */
108 virtual bool supportsDropping(int index) const;
109
110 /** @reimp */
111 virtual QString roleDescription(const QByteArray& role) const;
112
113 /** @reimp */
114 virtual QList<QPair<int, QVariant> > groups() const;
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 KUrl& 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 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 runtime complexity of this call is O(1).
140 */
141 int index(const KUrl& 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 virtual bool setExpanded(int index, bool expanded);
161 virtual bool isExpanded(int index) const;
162 virtual bool isExpandable(int index) const;
163 virtual int expandedParentsCount(int index) const;
164
165 QSet<KUrl> 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<KUrl>& urls);
173
174 /**
175 * Expands all parent-directories of the item \a url.
176 */
177 void expandParentDirectories(const KUrl& 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 requiresNepomuk;
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 Nepomuk is enabled and/or the Nepomuk
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 * Informs about the progress in percent when loading a directory. It is assured
221 * that the signal directoryLoadingStarted() has been emitted before.
222 */
223 void directoryLoadingProgress(int percent);
224
225 /**
226 * Is emitted if the sort-role gets resolved asynchronously and provides
227 * the progress-information of the sorting in percent. It is assured
228 * that the last sortProgress-signal contains 100 as value.
229 */
230 void directorySortingProgress(int percent);
231
232 /**
233 * Is emitted if an information message (e.g. "Connecting to host...")
234 * should be shown.
235 */
236 void infoMessage(const QString& message);
237
238 /**
239 * Is emitted if an error message (e.g. "Unknown location")
240 * should be shown.
241 */
242 void errorMessage(const QString& message);
243
244 /**
245 * Is emitted if a redirection from the current URL \a oldUrl
246 * to the new URL \a newUrl has been done.
247 */
248 void directoryRedirection(const KUrl& oldUrl, const KUrl& newUrl);
249
250 /**
251 * Is emitted when the URL passed by KFileItemModel::setUrl() represents a file.
252 * In this case no signal errorMessage() will be emitted.
253 */
254 void urlIsFileError(const KUrl& url);
255
256 protected:
257 virtual void onGroupedSortingChanged(bool current);
258 virtual void onSortRoleChanged(const QByteArray& current, const QByteArray& previous);
259 virtual void onSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous);
260
261 private slots:
262 /**
263 * Resorts all items dependent on the set sortRole(), sortOrder()
264 * and foldersFirst() settings.
265 */
266 void resortAllItems();
267
268 void slotCompleted();
269 void slotCanceled();
270 void slotNewItems(const KFileItemList& items);
271 void slotItemsDeleted(const KFileItemList& items);
272 void slotRefreshItems(const QList<QPair<KFileItem, KFileItem> >& items);
273 void slotClear();
274 void slotClear(const KUrl& url);
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 Nepomuk:
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 void insertItems(const KFileItemList& items);
302 void removeItems(const KFileItemList& items);
303
304 /**
305 * Helper method for insertItems() and removeItems(): Creates
306 * a list of ItemData elements based on the given items.
307 * Note that the ItemData instances are created dynamically and
308 * must be deleted by the caller.
309 */
310 QList<ItemData*> createItemDataList(const KFileItemList& items) const;
311
312 void removeExpandedItems();
313
314 /**
315 * Resets all values from m_requestRole to false.
316 */
317 void resetRoles();
318
319 /**
320 * @return Role-type for the given role.
321 * Runtime complexity is O(1).
322 */
323 RoleType typeForRole(const QByteArray& role) const;
324
325 /**
326 * @return Role-byte-array for the given role-type.
327 * Runtime complexity is O(1).
328 */
329 QByteArray roleForType(RoleType roleType) const;
330
331 QHash<QByteArray, QVariant> retrieveData(const KFileItem& item) const;
332
333 /**
334 * @return True if the item-data \a a should be ordered before the item-data
335 * \b. The item-data may have different parent-items.
336 */
337 bool lessThan(const ItemData* a, const ItemData* b) const;
338
339 /**
340 * Helper method for lessThan() and expandedParentsCountCompare(): Compares
341 * the passed item-data using m_sortRole as criteria. Both items must
342 * have the same parent item, otherwise the comparison will be wrong.
343 */
344 int sortRoleCompare(const ItemData* a, const ItemData* b) const;
345
346 int stringCompare(const QString& a, const QString& b) const;
347
348 /**
349 * Compares the expansion level of both items. The "expansion level" is defined
350 * by the number of parent directories. However simply comparing just the numbers
351 * is not sufficient, it is also important to check the hierarchy for having
352 * a correct order like shown in a tree.
353 */
354 int expandedParentsCountCompare(const ItemData* a, const ItemData* b) const;
355
356 /**
357 * Helper method for expandedParentsCountCompare().
358 */
359 QString subPath(const KFileItem& item,
360 const QString& itemPath,
361 int start,
362 bool* isDir) const;
363
364 bool useMaximumUpdateInterval() const;
365
366 QList<QPair<int, QVariant> > nameRoleGroups() const;
367 QList<QPair<int, QVariant> > sizeRoleGroups() const;
368 QList<QPair<int, QVariant> > dateRoleGroups() const;
369 QList<QPair<int, QVariant> > permissionRoleGroups() const;
370 QList<QPair<int, QVariant> > ratingRoleGroups() const;
371 QList<QPair<int, QVariant> > genericStringRoleGroups(const QByteArray& typeForRole) const;
372
373 /**
374 * Helper method for all xxxRoleGroups() methods to check whether the
375 * item with the given index is a child-item. A child-item is defined
376 * as item having an expansion-level > 0. All xxxRoleGroups() methods
377 * should skip the grouping if the item is a child-item (although
378 * KItemListView would be capable to show sub-groups in groups this
379 * results in visual clutter for most usecases).
380 */
381 bool isChildItem(int index) const;
382
383 /**
384 * @return Recursive list of child items that have \a item as upper most parent.
385 */
386 KFileItemList childItems(const KFileItem& item) const;
387
388 /**
389 * Is invoked by KFileItemModelRolesUpdater and results in emitting the
390 * sortProgress signal with a percent-value of the progress.
391 */
392 void emitSortProgress(int resolvedCount);
393
394 /**
395 * Applies the filters set through @ref setNameFilter and @ref setMimeTypeFilters.
396 */
397 void applyFilters();
398
399 /**
400 * Maps the QByteArray-roles to RoleTypes and provides translation- and
401 * group-contexts.
402 */
403 struct RoleInfoMap
404 {
405 const char* const role;
406 const RoleType roleType;
407 const char* const roleTranslationContext;
408 const char* const roleTranslation;
409 const char* const groupTranslationContext;
410 const char* const groupTranslation;
411 const bool requiresNepomuk;
412 const bool requiresIndexer;
413 };
414
415 /**
416 * @return Map of user visible roles that are accessible by KFileItemModel::rolesInformation().
417 */
418 static const RoleInfoMap* rolesInfoMap(int& count);
419
420 /**
421 * Determines the MIME-types of all items that can be done within
422 * the given timeout.
423 */
424 static void determineMimeTypes(const KFileItemList& items, int timeout);
425
426 private:
427 KFileItemModelDirLister* m_dirLister;
428
429 bool m_naturalSorting;
430 bool m_sortDirsFirst;
431
432 RoleType m_sortRole;
433 int m_sortingProgressPercent; // Value of directorySortingProgress() signal
434 QSet<QByteArray> m_roles;
435 Qt::CaseSensitivity m_caseSensitivity;
436
437 QList<ItemData*> m_itemData;
438 QHash<KUrl, int> m_items; // Allows O(1) access for KFileItemModel::index(const KFileItem& item)
439
440 KFileItemModelFilter m_filter;
441 QSet<KFileItem> m_filteredItems; // Items that got hidden by KFileItemModel::setNameFilter()
442
443 bool m_requestRole[RolesCount];
444
445 QTimer* m_maximumUpdateIntervalTimer;
446 QTimer* m_resortAllItemsTimer;
447 KFileItemList m_pendingItemsToInsert;
448
449 // Cache for KFileItemModel::groups()
450 mutable QList<QPair<int, QVariant> > m_groups;
451
452 // Stores the smallest expansion level of the root-URL. Is required to calculate
453 // the "expandedParentsCount" role in an efficient way. A value < 0 indicates a
454 // special meaning:
455 enum ExpandedParentsCountRootTypes
456 {
457 // m_expandedParentsCountRoot is uninitialized and must be determined by checking
458 // the root URL from the KDirLister.
459 UninitializedExpandedParentsCountRoot = -1,
460 // All items should be forced to get an expanded parents count of 0 even if they
461 // represent child items. This is useful for slaves that provide no parent items
462 // for child items like e.g. the search IO slaves.
463 ForceExpandedParentsCountRoot = -2
464 };
465 mutable int m_expandedParentsCountRoot;
466
467 // Stores the URLs of the expanded directories.
468 QSet<KUrl> m_expandedDirs;
469
470 // URLs that must be expanded. The expanding is initially triggered in setExpanded()
471 // and done step after step in slotCompleted().
472 QSet<KUrl> m_urlsToExpand;
473
474 friend class KFileItemModelSortAlgorithm; // Accesses lessThan() method
475 friend class KFileItemModelRolesUpdater; // Accesses emitSortProgress() method
476 friend class KFileItemModelTest; // For unit testing
477 friend class KFileItemListViewTest; // For unit testing
478 };
479
480 inline bool KFileItemModel::isChildItem(int index) const
481 {
482 return m_requestRole[ExpandedParentsCountRole] && m_itemData.at(index)->values.value("expandedParentsCount").toInt() > 0;
483 }
484
485 #endif
486
487