]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kfileitemmodel.h
Extract sorting-algorithm from KFileItemModel into custom class
[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/kfileitemmodelfilter_p.h>
27 #include <kitemviews/kitemmodelbase.h>
28
29 #include <QHash>
30
31 class KDirLister;
32 class QTimer;
33
34 /**
35 * @brief KItemModelBase implementation for KFileItems.
36 *
37 * KFileItemModel is connected with one KDirLister. Each time the KDirLister
38 * emits new items, removes items or changes items the model gets synchronized.
39 *
40 * KFileItemModel supports sorting and grouping of items. Additional roles that
41 * are not part of KFileItem can be added with KFileItemModel::setData().
42 *
43 * Also the recursive expansion of sub-directories is supported by
44 * KFileItemModel::setExpanded().
45 *
46 * TODO: In the longterm instead of passing a KDirLister just an URL should
47 * be passed and a KDirLister used internally. This solves the following issues:
48 * - The user of the API does not need to decide whether he listens to KDirLister
49 * or KFileItemModel.
50 * - It resolves minor conceptual differences between KDirLister and KFileItemModel.
51 * E.g. there is no way for KFileItemModel to check whether a completed() signal
52 * will be emitted after newItems() will be send by KDirLister or not (in the case
53 * of setShowingDotFiles() no completed() signal will get emitted).
54 */
55 class LIBDOLPHINPRIVATE_EXPORT KFileItemModel : public KItemModelBase
56 {
57 Q_OBJECT
58
59 public:
60 explicit KFileItemModel(KDirLister* dirLister, QObject* parent = 0);
61 virtual ~KFileItemModel();
62
63 virtual int count() const;
64 virtual QHash<QByteArray, QVariant> data(int index) const;
65 virtual bool setData(int index, const QHash<QByteArray, QVariant>& values);
66
67 /**
68 * Sets a separate sorting with folders first (true) or a mixed sorting of files and folders (false).
69 */
70 void setSortFoldersFirst(bool foldersFirst);
71 bool sortFoldersFirst() const;
72
73 void setShowHiddenFiles(bool show);
74 bool showHiddenFiles() const;
75
76 /**
77 * If set to true, only folders are shown as items of the model. Files
78 * are ignored.
79 */
80 void setShowFoldersOnly(bool enabled);
81 bool showFoldersOnly() const;
82
83 /** @reimp */
84 virtual QMimeData* createMimeData(const QSet<int>& indexes) const;
85
86 /** @reimp */
87 virtual int indexForKeyboardSearch(const QString& text, int startFromIndex = 0) const;
88
89 /** @reimp */
90 virtual bool supportsDropping(int index) const;
91
92 /** @reimp */
93 virtual QString roleDescription(const QByteArray& typeForRole) const;
94
95 /** @reimp */
96 virtual QList<QPair<int, QVariant> > groups() const;
97
98 /**
99 * @return The file-item for the index \a index. If the index is in a valid
100 * range it is assured that the file-item is not null. The runtime
101 * complexity of this call is O(1).
102 */
103 KFileItem fileItem(int index) const;
104
105 /**
106 * @return The file-item for the url \a url. If no file-item with the given
107 * URL is found KFileItem::isNull() will be true for the returned
108 * file-item. The runtime complexity of this call is O(1).
109 */
110 KFileItem fileItem(const KUrl& url) const;
111
112 /**
113 * @return The index for the file-item \a item. -1 is returned if no file-item
114 * is found or if the file-item is null. The runtime
115 * complexity of this call is O(1).
116 */
117 int index(const KFileItem& item) const;
118
119 /**
120 * @return The index for the URL \a url. -1 is returned if no file-item
121 * is found. The runtime complexity of this call is O(1).
122 */
123 int index(const KUrl& url) const;
124
125 /**
126 * @return Root item of all items.
127 */
128 KFileItem rootItem() const;
129
130 /**
131 * Clears all items of the model.
132 */
133 void clear();
134
135 // TODO: "name" + "isDir" is default in ctor
136 void setRoles(const QSet<QByteArray>& roles);
137 QSet<QByteArray> roles() const;
138
139 virtual bool setExpanded(int index, bool expanded);
140 virtual bool isExpanded(int index) const;
141 virtual bool isExpandable(int index) const;
142 virtual int expandedParentsCount(int index) const;
143
144 QSet<KUrl> expandedUrls() const;
145
146 /**
147 * Marks the URLs in \a urls as subfolders which were expanded previously.
148 * They are re-expanded one by one each time the KDirLister's completed() signal is received.
149 * Note that a manual triggering of the KDirLister is required.
150 */
151 void restoreExpandedUrls(const QSet<KUrl>& urls);
152
153 /**
154 * Expands all parent-items of \a url.
155 */
156 void expandParentItems(const KUrl& url);
157
158 void setNameFilter(const QString& nameFilter);
159 QString nameFilter() const;
160
161 struct RoleInfo
162 { QByteArray role;
163 QString translation;
164 QString group;
165 bool requiresNepomuk;
166 bool requiresIndexer;
167 };
168
169 /**
170 * @return Provides static information for all available roles that
171 * are supported by KFileItemModel. Some roles can only be
172 * determined if Nepomuk is enabled and/or the Nepomuk
173 * indexing is enabled.
174 */
175 static QList<RoleInfo> rolesInformation();
176
177 signals:
178 /**
179 * Is emitted after the loading of a directory has been completed or new
180 * items have been inserted to an already loaded directory. Usually
181 * one or more itemsInserted() signals are emitted before loadingCompleted()
182 * (the only exception is loading an empty directory, where only a
183 * loadingCompleted() signal gets emitted).
184 */
185 void loadingCompleted();
186
187 protected:
188 virtual void onGroupedSortingChanged(bool current);
189 virtual void onSortRoleChanged(const QByteArray& current, const QByteArray& previous);
190 virtual void onSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous);
191
192 private slots:
193 /**
194 * Resorts all items dependent on the set sortRole(), sortOrder()
195 * and foldersFirst() settings.
196 */
197 void resortAllItems();
198
199 void slotCompleted();
200 void slotCanceled();
201 void slotNewItems(const KFileItemList& items);
202 void slotItemsDeleted(const KFileItemList& items);
203 void slotRefreshItems(const QList<QPair<KFileItem, KFileItem> >& items);
204 void slotClear();
205 void slotClear(const KUrl& url);
206 void slotNaturalSortingChanged();
207
208 void dispatchPendingItemsToInsert();
209
210 private:
211 enum RoleType {
212 // User visible roles:
213 NoRole, NameRole, SizeRole, DateRole, PermissionsRole, OwnerRole,
214 GroupRole, TypeRole, DestinationRole, PathRole,
215 // User visible roles available with Nepomuk:
216 CommentRole, TagsRole, RatingRole, ImageSizeRole, OrientationRole,
217 WordCountRole, LineCountRole, ArtistRole, AlbumRole, DurationRole, TrackRole,
218 CopiedFromRole,
219 // Non-visible roles:
220 IsDirRole, IsExpandedRole, IsExpandableRole, ExpandedParentsCountRole,
221 // Mandatory last entry:
222 RolesCount
223 };
224
225 struct ItemData
226 {
227 KFileItem item;
228 QHash<QByteArray, QVariant> values;
229 ItemData* parent;
230 };
231
232 void insertItems(const KFileItemList& items);
233 void removeItems(const KFileItemList& items);
234
235 /**
236 * Helper method for insertItems() and removeItems(): Creates
237 * a list of ItemData elements based on the given items.
238 * Note that the ItemData instances are created dynamically and
239 * must be deleted by the caller.
240 */
241 QList<ItemData*> createItemDataList(const KFileItemList& items) const;
242
243 void removeExpandedItems();
244
245 /**
246 * Resets all values from m_requestRole to false.
247 */
248 void resetRoles();
249
250 /**
251 * @return Role-type for the given role.
252 * Runtime complexity is O(1).
253 */
254 RoleType typeForRole(const QByteArray& role) const;
255
256 /**
257 * @return Role-byte-array for the given role-type.
258 * Runtime complexity is O(1).
259 */
260 QByteArray roleForType(RoleType roleType) const;
261
262 QHash<QByteArray, QVariant> retrieveData(const KFileItem& item) const;
263
264 /**
265 * @return True if the item-data \a a should be ordered before the item-data
266 * \b. The item-data may have different parent-items.
267 */
268 bool lessThan(const ItemData* a, const ItemData* b) const;
269
270 /**
271 * Helper method for lessThan() and expandedParentsCountCompare(): Compares
272 * the passed item-data using m_sortRole as criteria. Both items must
273 * have the same parent item, otherwise the comparison will be wrong.
274 */
275 int sortRoleCompare(const ItemData* a, const ItemData* b) const;
276
277 int stringCompare(const QString& a, const QString& b) const;
278
279 /**
280 * Compares the expansion level of both items. The "expansion level" is defined
281 * by the number of parent directories. However simply comparing just the numbers
282 * is not sufficient, it is also important to check the hierarchy for having
283 * a correct order like shown in a tree.
284 */
285 int expandedParentsCountCompare(const ItemData* a, const ItemData* b) const;
286
287 /**
288 * Helper method for expandedParentsCountCompare().
289 */
290 QString subPath(const KFileItem& item,
291 const QString& itemPath,
292 int start,
293 bool* isDir) const;
294
295 bool useMaximumUpdateInterval() const;
296
297 QList<QPair<int, QVariant> > nameRoleGroups() const;
298 QList<QPair<int, QVariant> > sizeRoleGroups() const;
299 QList<QPair<int, QVariant> > dateRoleGroups() const;
300 QList<QPair<int, QVariant> > permissionRoleGroups() const;
301 QList<QPair<int, QVariant> > ratingRoleGroups() const;
302 QList<QPair<int, QVariant> > genericStringRoleGroups(const QByteArray& typeForRole) const;
303
304 /**
305 * Helper method for all xxxRoleGroups() methods to check whether the
306 * item with the given index is a child-item. A child-item is defined
307 * as item having an expansion-level > 0. All xxxRoleGroups() methods
308 * should skip the grouping if the item is a child-item (although
309 * KItemListView would be capable to show sub-groups in groups this
310 * results in visual clutter for most usecases).
311 */
312 bool isChildItem(int index) const;
313
314 /**
315 * @return Recursive list of child items that have \a item as upper most parent.
316 */
317 KFileItemList childItems(const KFileItem& item) const;
318
319 /**
320 * Maps the QByteArray-roles to RoleTypes and provides translation- and
321 * group-contexts.
322 */
323 struct RoleInfoMap
324 {
325 const char* const role;
326 const RoleType roleType;
327 const char* const roleTranslationContext;
328 const char* const roleTranslation;
329 const char* const groupTranslationContext;
330 const char* const groupTranslation;
331 const bool requiresNepomuk;
332 const bool requiresIndexer;
333 };
334
335 /**
336 * @return Map of user visible roles that are accessible by KFileItemModel::rolesInformation().
337 */
338 static const RoleInfoMap* rolesInfoMap(int& count);
339
340 private:
341 QWeakPointer<KDirLister> m_dirLister;
342
343 bool m_naturalSorting;
344 bool m_sortFoldersFirst;
345
346 RoleType m_sortRole;
347 QSet<QByteArray> m_roles;
348 Qt::CaseSensitivity m_caseSensitivity;
349
350 QList<ItemData*> m_itemData;
351 QHash<KUrl, int> m_items; // Allows O(1) access for KFileItemModel::index(const KFileItem& item)
352
353 KFileItemModelFilter m_filter;
354 QSet<KFileItem> m_filteredItems; // Items that got hidden by KFileItemModel::setNameFilter()
355
356 bool m_requestRole[RolesCount];
357
358 QTimer* m_maximumUpdateIntervalTimer;
359 QTimer* m_resortAllItemsTimer;
360 KFileItemList m_pendingItemsToInsert;
361
362 // Cache for KFileItemModel::groups()
363 mutable QList<QPair<int, QVariant> > m_groups;
364
365 // Stores the smallest expansion level of the root-URL. Is required to calculate
366 // the "expandedParentsCount" role in an efficient way. A value < 0 indicates a
367 // special meaning:
368 enum ExpandedParentsCountRootTypes
369 {
370 // m_expandedParentsCountRoot is uninitialized and must be determined by checking
371 // the root URL from the KDirLister.
372 UninitializedExpandedParentsCountRoot = -1,
373 // All items should be forced to get an expanded parents count of 0 even if they
374 // represent child items. This is useful for slaves that provide no parent items
375 // for child items like e.g. the search IO slaves.
376 ForceExpandedParentsCountRoot = -2
377 };
378 mutable int m_expandedParentsCountRoot;
379
380 // Stores the URLs of the expanded folders.
381 QSet<KUrl> m_expandedUrls;
382
383 // URLs that must be expanded. The expanding is initially triggered in setExpanded()
384 // and done step after step in slotCompleted().
385 QSet<KUrl> m_urlsToExpand;
386
387 friend class KFileItemModelSortAlgorithm; // Accesses lessThan() method
388 friend class KFileItemModelTest; // For unit testing
389 };
390
391 inline bool KFileItemModel::isChildItem(int index) const
392 {
393 return m_requestRole[ExpandedParentsCountRole] && m_itemData.at(index)->values.value("expandedParentsCount").toInt() > 0;
394 }
395
396 #endif
397
398