]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kfileitemmodel.cpp
Reimplement name-filtering
[dolphin.git] / src / kitemviews / kfileitemmodel.cpp
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 #include "kfileitemmodel.h"
21
22 #include <KDirLister>
23 #include <KDirModel>
24 #include <KLocale>
25 #include <KStringHandler>
26 #include <KDebug>
27
28 #include <QMimeData>
29 #include <QTimer>
30
31 #define KFILEITEMMODEL_DEBUG
32
33 KFileItemModel::KFileItemModel(KDirLister* dirLister, QObject* parent) :
34 KItemModelBase("name", parent),
35 m_dirLister(dirLister),
36 m_naturalSorting(true),
37 m_sortFoldersFirst(true),
38 m_sortRole(NameRole),
39 m_roles(),
40 m_caseSensitivity(Qt::CaseInsensitive),
41 m_itemData(),
42 m_items(),
43 m_nameFilter(),
44 m_filteredItems(),
45 m_requestRole(),
46 m_minimumUpdateIntervalTimer(0),
47 m_maximumUpdateIntervalTimer(0),
48 m_resortAllItemsTimer(0),
49 m_pendingItemsToInsert(),
50 m_pendingEmitLoadingCompleted(false),
51 m_groups(),
52 m_rootExpansionLevel(-1),
53 m_expandedUrls(),
54 m_urlsToExpand()
55 {
56 // Apply default roles that should be determined
57 resetRoles();
58 m_requestRole[NameRole] = true;
59 m_requestRole[IsDirRole] = true;
60 m_roles.insert("name");
61 m_roles.insert("isDir");
62
63 Q_ASSERT(dirLister);
64
65 connect(dirLister, SIGNAL(canceled()), this, SLOT(slotCanceled()));
66 connect(dirLister, SIGNAL(completed()), this, SLOT(slotCompleted()));
67 connect(dirLister, SIGNAL(newItems(KFileItemList)), this, SLOT(slotNewItems(KFileItemList)));
68 connect(dirLister, SIGNAL(itemsDeleted(KFileItemList)), this, SLOT(slotItemsDeleted(KFileItemList)));
69 connect(dirLister, SIGNAL(refreshItems(QList<QPair<KFileItem,KFileItem> >)), this, SLOT(slotRefreshItems(QList<QPair<KFileItem,KFileItem> >)));
70 connect(dirLister, SIGNAL(clear()), this, SLOT(slotClear()));
71 connect(dirLister, SIGNAL(clear(KUrl)), this, SLOT(slotClear(KUrl)));
72
73 // Although the layout engine of KItemListView is fast it is very inefficient to e.g.
74 // emit 50 itemsInserted()-signals each 100 ms. m_minimumUpdateIntervalTimer assures that updates
75 // are done in 1 second intervals for equal operations.
76 m_minimumUpdateIntervalTimer = new QTimer(this);
77 m_minimumUpdateIntervalTimer->setInterval(1000);
78 m_minimumUpdateIntervalTimer->setSingleShot(true);
79 connect(m_minimumUpdateIntervalTimer, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
80
81 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
82 // before the completed() or canceled() signal has been emitted.
83 m_maximumUpdateIntervalTimer = new QTimer(this);
84 m_maximumUpdateIntervalTimer->setInterval(2000);
85 m_maximumUpdateIntervalTimer->setSingleShot(true);
86 connect(m_maximumUpdateIntervalTimer, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
87
88 // When changing the value of an item which represents the sort-role a resorting must be
89 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
90 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
91 // resorting is postponed until the timer has been exceeded.
92 m_resortAllItemsTimer = new QTimer(this);
93 m_resortAllItemsTimer->setInterval(500);
94 m_resortAllItemsTimer->setSingleShot(true);
95 connect(m_resortAllItemsTimer, SIGNAL(timeout()), this, SLOT(resortAllItems()));
96
97 Q_ASSERT(m_minimumUpdateIntervalTimer->interval() <= m_maximumUpdateIntervalTimer->interval());
98 }
99
100 KFileItemModel::~KFileItemModel()
101 {
102 qDeleteAll(m_itemData);
103 m_itemData.clear();
104 }
105
106 int KFileItemModel::count() const
107 {
108 return m_itemData.count();
109 }
110
111 QHash<QByteArray, QVariant> KFileItemModel::data(int index) const
112 {
113 if (index >= 0 && index < count()) {
114 return m_itemData.at(index)->values;
115 }
116 return QHash<QByteArray, QVariant>();
117 }
118
119 bool KFileItemModel::setData(int index, const QHash<QByteArray, QVariant>& values)
120 {
121 if (index < 0 || index >= count()) {
122 return false;
123 }
124
125 QHash<QByteArray, QVariant> currentValues = m_itemData.at(index)->values;
126
127 // Determine which roles have been changed
128 QSet<QByteArray> changedRoles;
129 QHashIterator<QByteArray, QVariant> it(values);
130 while (it.hasNext()) {
131 it.next();
132 const QByteArray role = it.key();
133 const QVariant value = it.value();
134
135 if (currentValues[role] != value) {
136 currentValues[role] = value;
137 changedRoles.insert(role);
138 }
139 }
140
141 if (changedRoles.isEmpty()) {
142 return false;
143 }
144
145 m_itemData[index]->values = currentValues;
146 emit itemsChanged(KItemRangeList() << KItemRange(index, 1), changedRoles);
147
148 if (changedRoles.contains(sortRole())) {
149 m_resortAllItemsTimer->start();
150 }
151
152 return true;
153 }
154
155 void KFileItemModel::setSortFoldersFirst(bool foldersFirst)
156 {
157 if (foldersFirst != m_sortFoldersFirst) {
158 m_sortFoldersFirst = foldersFirst;
159 resortAllItems();
160 }
161 }
162
163 bool KFileItemModel::sortFoldersFirst() const
164 {
165 return m_sortFoldersFirst;
166 }
167
168 QMimeData* KFileItemModel::createMimeData(const QSet<int>& indexes) const
169 {
170 QMimeData* data = new QMimeData();
171
172 // The following code has been taken from KDirModel::mimeData()
173 // (kdelibs/kio/kio/kdirmodel.cpp)
174 // Copyright (C) 2006 David Faure <faure@kde.org>
175 KUrl::List urls;
176 KUrl::List mostLocalUrls;
177 bool canUseMostLocalUrls = true;
178
179 QSetIterator<int> it(indexes);
180 while (it.hasNext()) {
181 const int index = it.next();
182 const KFileItem item = fileItem(index);
183 if (!item.isNull()) {
184 urls << item.url();
185
186 bool isLocal;
187 mostLocalUrls << item.mostLocalUrl(isLocal);
188 if (!isLocal) {
189 canUseMostLocalUrls = false;
190 }
191 }
192 }
193
194 const bool different = canUseMostLocalUrls && mostLocalUrls != urls;
195 urls = KDirModel::simplifiedUrlList(urls); // TODO: Check if we still need KDirModel for this in KDE 5.0
196 if (different) {
197 mostLocalUrls = KDirModel::simplifiedUrlList(mostLocalUrls);
198 urls.populateMimeData(mostLocalUrls, data);
199 } else {
200 urls.populateMimeData(data);
201 }
202
203 return data;
204 }
205
206 int KFileItemModel::indexForKeyboardSearch(const QString& text, int startFromIndex) const
207 {
208 startFromIndex = qMax(0, startFromIndex);
209 for (int i = startFromIndex; i < count(); ++i) {
210 if (data(i)["name"].toString().startsWith(text, Qt::CaseInsensitive)) {
211 return i;
212 }
213 }
214 for (int i = 0; i < startFromIndex; ++i) {
215 if (data(i)["name"].toString().startsWith(text, Qt::CaseInsensitive)) {
216 return i;
217 }
218 }
219 return -1;
220 }
221
222 bool KFileItemModel::supportsDropping(int index) const
223 {
224 const KFileItem item = fileItem(index);
225 return item.isNull() ? false : item.isDir();
226 }
227
228 QString KFileItemModel::roleDescription(const QByteArray& role) const
229 {
230 QString descr;
231
232 switch (roleIndex(role)) {
233 case NameRole: descr = i18nc("@item:intable", "Name"); break;
234 case SizeRole: descr = i18nc("@item:intable", "Size"); break;
235 case DateRole: descr = i18nc("@item:intable", "Date"); break;
236 case PermissionsRole: descr = i18nc("@item:intable", "Permissions"); break;
237 case OwnerRole: descr = i18nc("@item:intable", "Owner"); break;
238 case GroupRole: descr = i18nc("@item:intable", "Group"); break;
239 case TypeRole: descr = i18nc("@item:intable", "Type"); break;
240 case DestinationRole: descr = i18nc("@item:intable", "Destination"); break;
241 case PathRole: descr = i18nc("@item:intable", "Path"); break;
242 case CommentRole: descr = i18nc("@item:intable", "Comment"); break;
243 case TagsRole: descr = i18nc("@item:intable", "Tags"); break;
244 case RatingRole: descr = i18nc("@item:intable", "Rating"); break;
245 case NoRole: break;
246 case IsDirRole: break;
247 case IsExpandedRole: break;
248 case ExpansionLevelRole: break;
249 default: Q_ASSERT(false); break;
250 }
251
252 return descr;
253 }
254
255 QList<QPair<int, QVariant> > KFileItemModel::groups() const
256 {
257 if (!m_itemData.isEmpty() && m_groups.isEmpty()) {
258 #ifdef KFILEITEMMODEL_DEBUG
259 QElapsedTimer timer;
260 timer.start();
261 #endif
262 switch (roleIndex(sortRole())) {
263 case NameRole: m_groups = nameRoleGroups(); break;
264 case SizeRole: m_groups = sizeRoleGroups(); break;
265 case DateRole: m_groups = dateRoleGroups(); break;
266 case PermissionsRole: m_groups = permissionRoleGroups(); break;
267 case OwnerRole: m_groups = genericStringRoleGroups("owner"); break;
268 case GroupRole: m_groups = genericStringRoleGroups("group"); break;
269 case TypeRole: m_groups = genericStringRoleGroups("type"); break;
270 case DestinationRole: m_groups = genericStringRoleGroups("destination"); break;
271 case PathRole: m_groups = genericStringRoleGroups("path"); break;
272 case CommentRole: m_groups = genericStringRoleGroups("comment"); break;
273 case TagsRole: m_groups = genericStringRoleGroups("tags"); break;
274 case RatingRole: m_groups = ratingRoleGroups(); break;
275 case NoRole: break;
276 case IsDirRole: break;
277 case IsExpandedRole: break;
278 case ExpansionLevelRole: break;
279 default: Q_ASSERT(false); break;
280 }
281
282 #ifdef KFILEITEMMODEL_DEBUG
283 kDebug() << "[TIME] Calculating groups for" << count() << "items:" << timer.elapsed();
284 #endif
285 }
286
287 return m_groups;
288 }
289
290 KFileItem KFileItemModel::fileItem(int index) const
291 {
292 if (index >= 0 && index < count()) {
293 return m_itemData.at(index)->item;
294 }
295
296 return KFileItem();
297 }
298
299 KFileItem KFileItemModel::fileItem(const KUrl& url) const
300 {
301 const int index = m_items.value(url, -1);
302 if (index >= 0) {
303 return m_itemData.at(index)->item;
304 }
305 return KFileItem();
306 }
307
308 int KFileItemModel::index(const KFileItem& item) const
309 {
310 if (item.isNull()) {
311 return -1;
312 }
313
314 return m_items.value(item.url(), -1);
315 }
316
317 int KFileItemModel::index(const KUrl& url) const
318 {
319 KUrl urlToFind = url;
320 urlToFind.adjustPath(KUrl::RemoveTrailingSlash);
321 return m_items.value(urlToFind, -1);
322 }
323
324 KFileItem KFileItemModel::rootItem() const
325 {
326 const KDirLister* dirLister = m_dirLister.data();
327 if (dirLister) {
328 return dirLister->rootItem();
329 }
330 return KFileItem();
331 }
332
333 void KFileItemModel::clear()
334 {
335 slotClear();
336 }
337
338 void KFileItemModel::setRoles(const QSet<QByteArray>& roles)
339 {
340 m_roles = roles;
341
342 if (count() > 0) {
343 const bool supportedExpanding = m_requestRole[IsExpandedRole] && m_requestRole[ExpansionLevelRole];
344 const bool willSupportExpanding = roles.contains("isExpanded") && roles.contains("expansionLevel");
345 if (supportedExpanding && !willSupportExpanding) {
346 // No expanding is supported anymore. Take care to delete all items that have an expansion level
347 // that is not 0 (and hence are part of an expanded item).
348 removeExpandedItems();
349 }
350 }
351
352 resetRoles();
353
354 QSetIterator<QByteArray> it(roles);
355 while (it.hasNext()) {
356 const QByteArray& role = it.next();
357 m_requestRole[roleIndex(role)] = true;
358 }
359
360 if (count() > 0) {
361 // Update m_data with the changed requested roles
362 const int maxIndex = count() - 1;
363 for (int i = 0; i <= maxIndex; ++i) {
364 m_itemData[i]->values = retrieveData(m_itemData.at(i)->item);
365 }
366
367 kWarning() << "TODO: Emitting itemsChanged() with no information what has changed!";
368 emit itemsChanged(KItemRangeList() << KItemRange(0, count()), QSet<QByteArray>());
369 }
370 }
371
372 QSet<QByteArray> KFileItemModel::roles() const
373 {
374 return m_roles;
375 }
376
377 bool KFileItemModel::setExpanded(int index, bool expanded)
378 {
379 if (isExpanded(index) == expanded || index < 0 || index >= count()) {
380 return false;
381 }
382
383 QHash<QByteArray, QVariant> values;
384 values.insert("isExpanded", expanded);
385 if (!setData(index, values)) {
386 return false;
387 }
388
389 const KUrl url = m_itemData.at(index)->item.url();
390 if (expanded) {
391 m_expandedUrls.insert(url);
392
393 KDirLister* dirLister = m_dirLister.data();
394 if (dirLister) {
395 dirLister->openUrl(url, KDirLister::Keep);
396 return true;
397 }
398 } else {
399 m_expandedUrls.remove(url);
400
401 KFileItemList itemsToRemove;
402 const int expansionLevel = data(index)["expansionLevel"].toInt();
403 ++index;
404 while (index < count() && data(index)["expansionLevel"].toInt() > expansionLevel) {
405 itemsToRemove.append(m_itemData.at(index)->item);
406 ++index;
407 }
408 removeItems(itemsToRemove);
409 return true;
410 }
411
412 return false;
413 }
414
415 bool KFileItemModel::isExpanded(int index) const
416 {
417 if (index >= 0 && index < count()) {
418 return m_itemData.at(index)->values.value("isExpanded").toBool();
419 }
420 return false;
421 }
422
423 bool KFileItemModel::isExpandable(int index) const
424 {
425 if (index >= 0 && index < count()) {
426 return m_itemData.at(index)->item.isDir();
427 }
428 return false;
429 }
430
431 QSet<KUrl> KFileItemModel::expandedUrls() const
432 {
433 return m_expandedUrls;
434 }
435
436 void KFileItemModel::restoreExpandedUrls(const QSet<KUrl>& urls)
437 {
438 m_urlsToExpand = urls;
439 }
440
441 void KFileItemModel::setExpanded(const QSet<KUrl>& urls)
442 {
443
444 const KDirLister* dirLister = m_dirLister.data();
445 if (!dirLister) {
446 return;
447 }
448
449 const int pos = dirLister->url().url().length();
450
451 // Assure that each sub-path of the URLs that should be
452 // expanded is added to m_urlsToExpand too. KDirLister
453 // does not care whether the parent-URL has already been
454 // expanded.
455 QSetIterator<KUrl> it1(urls);
456 while (it1.hasNext()) {
457 const KUrl& url = it1.next();
458
459 KUrl urlToExpand = dirLister->url();
460 const QStringList subDirs = url.url().mid(pos).split(QDir::separator());
461 for (int i = 0; i < subDirs.count(); ++i) {
462 urlToExpand.addPath(subDirs.at(i));
463 m_urlsToExpand.insert(urlToExpand);
464 }
465 }
466
467 // KDirLister::open() must called at least once to trigger an initial
468 // loading. The pending URLs that must be restored are handled
469 // in slotCompleted().
470 QSetIterator<KUrl> it2(m_urlsToExpand);
471 while (it2.hasNext()) {
472 const int idx = index(it2.next());
473 if (idx >= 0 && !isExpanded(idx)) {
474 setExpanded(idx, true);
475 break;
476 }
477 }
478 }
479
480 void KFileItemModel::setNameFilter(const QString& nameFilter)
481 {
482 if (m_nameFilter != nameFilter) {
483 // TODO #1: Assure that expanded items only can get hidden
484 // if no child item is visible
485
486 // TODO #2: If the user entered a '*' use a regular expression
487
488 m_nameFilter = nameFilter;
489
490 const QString filter = nameFilter.toLower();
491
492 // Check which shown items from m_itemData must get
493 // hidden and hence moved to m_filteredItems.
494 KFileItemList newFilteredItems;
495
496 foreach (ItemData* itemData, m_itemData) {
497 if (!matchesNameFilter(itemData->item, filter)) {
498 m_filteredItems.append(itemData->item);
499 newFilteredItems.append(itemData->item);
500 }
501 }
502
503 if (!newFilteredItems.isEmpty()) {
504 slotItemsDeleted(newFilteredItems);
505 }
506
507 // Check which hidden items from m_filteredItems should
508 // get visible again and hence removed from m_filteredItems.
509 KFileItemList newVisibleItems;
510
511 for (int i = m_filteredItems.count() - 1; i >= 0; --i) {
512 const KFileItem item = m_filteredItems.at(i);
513 if (matchesNameFilter(item, filter)) {
514 newVisibleItems.append(item);
515 m_filteredItems.removeAt(i);
516 }
517 }
518
519 if (!newVisibleItems.isEmpty()) {
520 slotNewItems(newVisibleItems);
521 dispatchPendingItemsToInsert();
522 }
523 }
524 }
525
526 QString KFileItemModel::nameFilter() const
527 {
528 return m_nameFilter;
529 }
530
531 void KFileItemModel::onGroupedSortingChanged(bool current)
532 {
533 Q_UNUSED(current);
534 m_groups.clear();
535 }
536
537 void KFileItemModel::onSortRoleChanged(const QByteArray& current, const QByteArray& previous)
538 {
539 Q_UNUSED(previous);
540 m_sortRole = roleIndex(current);
541
542 #ifdef KFILEITEMMODEL_DEBUG
543 if (!m_requestRole[m_sortRole]) {
544 kWarning() << "The sort-role has been changed to a role that has not been received yet";
545 }
546 #endif
547
548 resortAllItems();
549 }
550
551 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous)
552 {
553 Q_UNUSED(current);
554 Q_UNUSED(previous);
555 resortAllItems();
556 }
557
558 void KFileItemModel::resortAllItems()
559 {
560 m_resortAllItemsTimer->stop();
561
562 const int itemCount = count();
563 if (itemCount <= 0) {
564 return;
565 }
566
567 #ifdef KFILEITEMMODEL_DEBUG
568 QElapsedTimer timer;
569 timer.start();
570 kDebug() << "===========================================================";
571 kDebug() << "Resorting" << itemCount << "items";
572 #endif
573
574 // Remember the order of the current URLs so
575 // that it can be determined which indexes have
576 // been moved because of the resorting.
577 QList<KUrl> oldUrls;
578 oldUrls.reserve(itemCount);
579 foreach (const ItemData* itemData, m_itemData) {
580 oldUrls.append(itemData->item.url());
581 }
582
583 m_groups.clear();
584 m_items.clear();
585
586 // Resort the items
587 sort(m_itemData.begin(), m_itemData.end());
588 for (int i = 0; i < itemCount; ++i) {
589 m_items.insert(m_itemData.at(i)->item.url(), i);
590 }
591
592 // Determine the indexes that have been moved
593 bool emitItemsMoved = false;
594 QList<int> movedToIndexes;
595 movedToIndexes.reserve(itemCount);
596 for (int i = 0; i < itemCount; i++) {
597 const int newIndex = m_items.value(oldUrls.at(i).url());
598 movedToIndexes.append(newIndex);
599 if (!emitItemsMoved && newIndex != i) {
600 emitItemsMoved = true;
601 }
602 }
603
604 if (emitItemsMoved) {
605 emit itemsMoved(KItemRange(0, itemCount), movedToIndexes);
606 }
607
608 #ifdef KFILEITEMMODEL_DEBUG
609 kDebug() << "[TIME] Resorting of" << itemCount << "items:" << timer.elapsed();
610 #endif
611 }
612
613 void KFileItemModel::slotCompleted()
614 {
615 if (m_urlsToExpand.isEmpty() && m_minimumUpdateIntervalTimer->isActive()) {
616 // dispatchPendingItems() will be called when the timer
617 // has been expired.
618 m_pendingEmitLoadingCompleted = true;
619 return;
620 }
621
622 m_pendingEmitLoadingCompleted = false;
623 dispatchPendingItemsToInsert();
624
625 if (!m_urlsToExpand.isEmpty()) {
626 // Try to find a URL that can be expanded.
627 // Note that the parent folder must be expanded before any of its subfolders become visible.
628 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
629 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
630 foreach(const KUrl& url, m_urlsToExpand) {
631 const int index = m_items.value(url, -1);
632 if (index >= 0) {
633 m_urlsToExpand.remove(url);
634 if (setExpanded(index, true)) {
635 // The dir lister has been triggered. This slot will be called
636 // again after the directory has been expanded.
637 return;
638 }
639 }
640 }
641
642 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
643 // if these URLs have been deleted in the meantime.
644 m_urlsToExpand.clear();
645 }
646
647 emit loadingCompleted();
648 m_minimumUpdateIntervalTimer->start();
649 }
650
651 void KFileItemModel::slotCanceled()
652 {
653 m_minimumUpdateIntervalTimer->stop();
654 m_maximumUpdateIntervalTimer->stop();
655 dispatchPendingItemsToInsert();
656 }
657
658 void KFileItemModel::slotNewItems(const KFileItemList& items)
659 {
660 m_pendingItemsToInsert.append(items);
661
662 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer->isActive()) {
663 // Assure that items get dispatched if no completed() or canceled() signal is
664 // emitted during the maximum update interval.
665 m_maximumUpdateIntervalTimer->start();
666 }
667 }
668
669 void KFileItemModel::slotItemsDeleted(const KFileItemList& items)
670 {
671 if (!m_pendingItemsToInsert.isEmpty()) {
672 insertItems(m_pendingItemsToInsert);
673 m_pendingItemsToInsert.clear();
674 }
675 removeItems(items);
676 }
677
678 void KFileItemModel::slotRefreshItems(const QList<QPair<KFileItem, KFileItem> >& items)
679 {
680 Q_ASSERT(!items.isEmpty());
681 #ifdef KFILEITEMMODEL_DEBUG
682 kDebug() << "Refreshing" << items.count() << "items";
683 #endif
684
685 m_groups.clear();
686
687 // Get the indexes of all items that have been refreshed
688 QList<int> indexes;
689 indexes.reserve(items.count());
690
691 QListIterator<QPair<KFileItem, KFileItem> > it(items);
692 while (it.hasNext()) {
693 const QPair<KFileItem, KFileItem>& itemPair = it.next();
694 const int index = m_items.value(itemPair.second.url(), -1);
695 if (index >= 0) {
696 indexes.append(index);
697 }
698 }
699
700 // If the changed items have been created recently, they might not be in m_items yet.
701 // In that case, the list 'indexes' might be empty.
702 if (indexes.isEmpty()) {
703 return;
704 }
705
706 // Extract the item-ranges out of the changed indexes
707 qSort(indexes);
708
709 KItemRangeList itemRangeList;
710 int rangeIndex = 0;
711 int rangeCount = 1;
712 int previousIndex = indexes.at(0);
713
714 const int maxIndex = indexes.count() - 1;
715 for (int i = 1; i <= maxIndex; ++i) {
716 const int currentIndex = indexes.at(i);
717 if (currentIndex == previousIndex + 1) {
718 ++rangeCount;
719 } else {
720 itemRangeList.append(KItemRange(rangeIndex, rangeCount));
721
722 rangeIndex = currentIndex;
723 rangeCount = 1;
724 }
725 previousIndex = currentIndex;
726 }
727
728 if (rangeCount > 0) {
729 itemRangeList.append(KItemRange(rangeIndex, rangeCount));
730 }
731
732 emit itemsChanged(itemRangeList, QSet<QByteArray>());
733 }
734
735 void KFileItemModel::slotClear()
736 {
737 #ifdef KFILEITEMMODEL_DEBUG
738 kDebug() << "Clearing all items";
739 #endif
740
741 m_groups.clear();
742
743 m_minimumUpdateIntervalTimer->stop();
744 m_maximumUpdateIntervalTimer->stop();
745 m_resortAllItemsTimer->stop();
746 m_pendingItemsToInsert.clear();
747
748 m_rootExpansionLevel = -1;
749
750 const int removedCount = m_itemData.count();
751 if (removedCount > 0) {
752 qDeleteAll(m_itemData);
753 m_itemData.clear();
754 m_items.clear();
755 emit itemsRemoved(KItemRangeList() << KItemRange(0, removedCount));
756 }
757
758 m_expandedUrls.clear();
759 }
760
761 void KFileItemModel::slotClear(const KUrl& url)
762 {
763 Q_UNUSED(url);
764 }
765
766 void KFileItemModel::dispatchPendingItemsToInsert()
767 {
768 if (!m_pendingItemsToInsert.isEmpty()) {
769 insertItems(m_pendingItemsToInsert);
770 m_pendingItemsToInsert.clear();
771 }
772
773 if (m_pendingEmitLoadingCompleted) {
774 emit loadingCompleted();
775 }
776 }
777
778 void KFileItemModel::insertItems(const KFileItemList& items)
779 {
780 if (items.isEmpty()) {
781 return;
782 }
783
784 #ifdef KFILEITEMMODEL_DEBUG
785 QElapsedTimer timer;
786 timer.start();
787 kDebug() << "===========================================================";
788 kDebug() << "Inserting" << items.count() << "items";
789 #endif
790
791 m_groups.clear();
792
793 QList<ItemData*> sortedItems = createItemDataList(items);
794 sort(sortedItems.begin(), sortedItems.end());
795
796 #ifdef KFILEITEMMODEL_DEBUG
797 kDebug() << "[TIME] Sorting:" << timer.elapsed();
798 #endif
799
800 KItemRangeList itemRanges;
801 int targetIndex = 0;
802 int sourceIndex = 0;
803 int insertedAtIndex = -1; // Index for the current item-range
804 int insertedCount = 0; // Count for the current item-range
805 int previouslyInsertedCount = 0; // Sum of previously inserted items for all ranges
806 while (sourceIndex < sortedItems.count()) {
807 // Find target index from m_items to insert the current item
808 // in a sorted order
809 const int previousTargetIndex = targetIndex;
810 while (targetIndex < m_itemData.count()) {
811 if (!lessThan(m_itemData.at(targetIndex), sortedItems.at(sourceIndex))) {
812 break;
813 }
814 ++targetIndex;
815 }
816
817 if (targetIndex - previousTargetIndex > 0 && insertedAtIndex >= 0) {
818 itemRanges << KItemRange(insertedAtIndex, insertedCount);
819 previouslyInsertedCount += insertedCount;
820 insertedAtIndex = targetIndex - previouslyInsertedCount;
821 insertedCount = 0;
822 }
823
824 // Insert item at the position targetIndex by transfering
825 // the ownership of the item-data from sortedItems to m_itemData.
826 // m_items will be inserted after the loop (see comment below)
827 m_itemData.insert(targetIndex, sortedItems.at(sourceIndex));
828 ++insertedCount;
829
830 if (insertedAtIndex < 0) {
831 insertedAtIndex = targetIndex;
832 Q_ASSERT(previouslyInsertedCount == 0);
833 }
834 ++targetIndex;
835 ++sourceIndex;
836 }
837
838 // The indexes of all m_items must be adjusted, not only the index
839 // of the new items
840 const int itemDataCount = m_itemData.count();
841 for (int i = 0; i < itemDataCount; ++i) {
842 m_items.insert(m_itemData.at(i)->item.url(), i);
843 }
844
845 itemRanges << KItemRange(insertedAtIndex, insertedCount);
846 emit itemsInserted(itemRanges);
847
848 #ifdef KFILEITEMMODEL_DEBUG
849 kDebug() << "[TIME] Inserting of" << items.count() << "items:" << timer.elapsed();
850 #endif
851 }
852
853 void KFileItemModel::removeItems(const KFileItemList& items)
854 {
855 if (items.isEmpty()) {
856 return;
857 }
858
859 #ifdef KFILEITEMMODEL_DEBUG
860 kDebug() << "Removing " << items.count() << "items";
861 #endif
862
863 m_groups.clear();
864
865 QList<ItemData*> sortedItems = createItemDataList(items);
866 sort(sortedItems.begin(), sortedItems.end());
867
868 QList<int> indexesToRemove;
869 indexesToRemove.reserve(items.count());
870
871 // Calculate the item ranges that will get deleted
872 KItemRangeList itemRanges;
873 int removedAtIndex = -1;
874 int removedCount = 0;
875 int targetIndex = 0;
876 foreach (const ItemData* itemData, sortedItems) {
877 const KFileItem& itemToRemove = itemData->item;
878
879 const int previousTargetIndex = targetIndex;
880 while (targetIndex < m_itemData.count()) {
881 if (m_itemData.at(targetIndex)->item.url() == itemToRemove.url()) {
882 break;
883 }
884 ++targetIndex;
885 }
886 if (targetIndex >= m_itemData.count()) {
887 kWarning() << "Item that should be deleted has not been found!";
888 return;
889 }
890
891 if (targetIndex - previousTargetIndex > 0 && removedAtIndex >= 0) {
892 itemRanges << KItemRange(removedAtIndex, removedCount);
893 removedAtIndex = targetIndex;
894 removedCount = 0;
895 }
896
897 indexesToRemove.append(targetIndex);
898 if (removedAtIndex < 0) {
899 removedAtIndex = targetIndex;
900 }
901 ++removedCount;
902 ++targetIndex;
903 }
904 qDeleteAll(sortedItems);
905 sortedItems.clear();
906
907 // Delete the items
908 for (int i = indexesToRemove.count() - 1; i >= 0; --i) {
909 const int indexToRemove = indexesToRemove.at(i);
910 delete m_itemData.at(indexToRemove);
911 m_itemData.removeAt(indexToRemove);
912 }
913
914 // The indexes of all m_items must be adjusted, not only the index
915 // of the removed items
916 const int itemDataCount = m_itemData.count();
917 for (int i = 0; i < itemDataCount; ++i) {
918 m_items.insert(m_itemData.at(i)->item.url(), i);
919 }
920
921 if (count() <= 0) {
922 m_rootExpansionLevel = -1;
923 }
924
925 itemRanges << KItemRange(removedAtIndex, removedCount);
926 emit itemsRemoved(itemRanges);
927 }
928
929 QList<KFileItemModel::ItemData*> KFileItemModel::createItemDataList(const KFileItemList& items) const
930 {
931 QList<ItemData*> itemDataList;
932 itemDataList.reserve(items.count());
933
934 foreach (const KFileItem& item, items) {
935 ItemData* itemData = new ItemData();
936 itemData->item = item;
937 itemData->values = retrieveData(item);
938 itemDataList.append(itemData);
939 }
940
941 return itemDataList;
942 }
943
944 void KFileItemModel::removeExpandedItems()
945 {
946 KFileItemList expandedItems;
947
948 const int maxIndex = m_itemData.count() - 1;
949 for (int i = 0; i <= maxIndex; ++i) {
950 const ItemData* itemData = m_itemData.at(i);
951 if (itemData->values.value("expansionLevel").toInt() > 0) {
952 expandedItems.append(itemData->item);
953 }
954 }
955
956 // The m_rootExpansionLevel may not get reset before all items with
957 // a bigger expansionLevel have been removed.
958 Q_ASSERT(m_rootExpansionLevel >= 0);
959 removeItems(expandedItems);
960
961 m_rootExpansionLevel = -1;
962 m_expandedUrls.clear();
963 }
964
965 void KFileItemModel::resetRoles()
966 {
967 for (int i = 0; i < RolesCount; ++i) {
968 m_requestRole[i] = false;
969 }
970 }
971
972 KFileItemModel::Role KFileItemModel::roleIndex(const QByteArray& role) const
973 {
974 static QHash<QByteArray, Role> rolesHash;
975 if (rolesHash.isEmpty()) {
976 rolesHash.insert("name", NameRole);
977 rolesHash.insert("size", SizeRole);
978 rolesHash.insert("date", DateRole);
979 rolesHash.insert("permissions", PermissionsRole);
980 rolesHash.insert("owner", OwnerRole);
981 rolesHash.insert("group", GroupRole);
982 rolesHash.insert("type", TypeRole);
983 rolesHash.insert("destination", DestinationRole);
984 rolesHash.insert("path", PathRole);
985 rolesHash.insert("comment", CommentRole);
986 rolesHash.insert("tags", TagsRole);
987 rolesHash.insert("rating", RatingRole);
988 rolesHash.insert("isDir", IsDirRole);
989 rolesHash.insert("isExpanded", IsExpandedRole);
990 rolesHash.insert("expansionLevel", ExpansionLevelRole);
991 }
992 return rolesHash.value(role, NoRole);
993 }
994
995 QHash<QByteArray, QVariant> KFileItemModel::retrieveData(const KFileItem& item) const
996 {
997 // It is important to insert only roles that are fast to retrieve. E.g.
998 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
999 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1000 QHash<QByteArray, QVariant> data;
1001 data.insert("iconPixmap", QPixmap());
1002 data.insert("url", item.url());
1003
1004 const bool isDir = item.isDir();
1005 if (m_requestRole[IsDirRole]) {
1006 data.insert("isDir", isDir);
1007 }
1008
1009 if (m_requestRole[NameRole]) {
1010 data.insert("name", item.text());
1011 }
1012
1013 if (m_requestRole[SizeRole]) {
1014 if (isDir) {
1015 data.insert("size", QVariant());
1016 } else {
1017 data.insert("size", item.size());
1018 }
1019 }
1020
1021 if (m_requestRole[DateRole]) {
1022 // Don't use KFileItem::timeString() as this is too expensive when
1023 // having several thousands of items. Instead the formatting of the
1024 // date-time will be done on-demand by the view when the date will be shown.
1025 const KDateTime dateTime = item.time(KFileItem::ModificationTime);
1026 data.insert("date", dateTime.dateTime());
1027 }
1028
1029 if (m_requestRole[PermissionsRole]) {
1030 data.insert("permissions", item.permissionsString());
1031 }
1032
1033 if (m_requestRole[OwnerRole]) {
1034 data.insert("owner", item.user());
1035 }
1036
1037 if (m_requestRole[GroupRole]) {
1038 data.insert("group", item.group());
1039 }
1040
1041 if (m_requestRole[DestinationRole]) {
1042 QString destination = item.linkDest();
1043 if (destination.isEmpty()) {
1044 destination = i18nc("@item:intable", "No destination");
1045 }
1046 data.insert("destination", destination);
1047 }
1048
1049 if (m_requestRole[PathRole]) {
1050 data.insert("path", item.localPath());
1051 }
1052
1053 if (m_requestRole[IsExpandedRole]) {
1054 data.insert("isExpanded", false);
1055 }
1056
1057 if (m_requestRole[ExpansionLevelRole]) {
1058 if (m_rootExpansionLevel < 0 && m_dirLister.data()) {
1059 const QString rootDir = m_dirLister.data()->url().directory(KUrl::AppendTrailingSlash);
1060 m_rootExpansionLevel = rootDir.count('/');
1061 if (m_rootExpansionLevel == 1) {
1062 // Special case: The root is already reached and no parent is available
1063 --m_rootExpansionLevel;
1064 }
1065 }
1066 const QString dir = item.url().directory(KUrl::AppendTrailingSlash);
1067 const int level = dir.count('/') - m_rootExpansionLevel - 1;
1068 data.insert("expansionLevel", level);
1069 }
1070
1071 if (item.isMimeTypeKnown()) {
1072 data.insert("iconName", item.iconName());
1073
1074 if (m_requestRole[TypeRole]) {
1075 data.insert("type", item.mimeComment());
1076 }
1077 }
1078
1079 return data;
1080 }
1081
1082 bool KFileItemModel::lessThan(const ItemData* a, const ItemData* b) const
1083 {
1084 const KFileItem& itemA = a->item;
1085 const KFileItem& itemB = b->item;
1086
1087 int result = 0;
1088
1089 if (m_rootExpansionLevel >= 0) {
1090 result = expansionLevelsCompare(itemA, itemB);
1091 if (result != 0) {
1092 // The items have parents with different expansion levels
1093 return (sortOrder() == Qt::AscendingOrder) ? result < 0 : result > 0;
1094 }
1095 }
1096
1097 if (m_sortFoldersFirst || m_sortRole == SizeRole) {
1098 const bool isDirA = itemA.isDir();
1099 const bool isDirB = itemB.isDir();
1100 if (isDirA && !isDirB) {
1101 return true;
1102 } else if (!isDirA && isDirB) {
1103 return false;
1104 }
1105 }
1106
1107 switch (m_sortRole) {
1108 case NameRole: {
1109 result = stringCompare(itemA.text(), itemB.text());
1110 if (result == 0) {
1111 // KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1112 result = stringCompare(itemA.name(m_caseSensitivity == Qt::CaseInsensitive),
1113 itemB.name(m_caseSensitivity == Qt::CaseInsensitive));
1114 }
1115 break;
1116 }
1117
1118 case DateRole: {
1119 const KDateTime dateTimeA = itemA.time(KFileItem::ModificationTime);
1120 const KDateTime dateTimeB = itemB.time(KFileItem::ModificationTime);
1121 if (dateTimeA < dateTimeB) {
1122 result = -1;
1123 } else if (dateTimeA > dateTimeB) {
1124 result = +1;
1125 }
1126 break;
1127 }
1128
1129 case SizeRole: {
1130 if (itemA.isDir()) {
1131 Q_ASSERT(itemB.isDir()); // see "if (m_sortFoldersFirst || m_sortRole == SizeRole)" above
1132
1133 const QVariant valueA = a->values.value("size");
1134 const QVariant valueB = b->values.value("size");
1135
1136 if (valueA.isNull()) {
1137 result = -1;
1138 } else if (valueB.isNull()) {
1139 result = +1;
1140 } else {
1141 result = valueA.value<KIO::filesize_t>() - valueB.value<KIO::filesize_t>();
1142 }
1143 } else {
1144 Q_ASSERT(!itemB.isDir()); // see "if (m_sortFoldersFirst || m_sortRole == SizeRole)" above
1145 result = itemA.size() - itemB.size();
1146 }
1147 break;
1148 }
1149
1150 case TypeRole: {
1151 result = QString::compare(a->values.value("type").toString(),
1152 b->values.value("type").toString());
1153 break;
1154 }
1155
1156 case CommentRole: {
1157 result = QString::compare(a->values.value("comment").toString(),
1158 b->values.value("comment").toString());
1159 break;
1160 }
1161
1162 case TagsRole: {
1163 result = QString::compare(a->values.value("tags").toString(),
1164 b->values.value("tags").toString());
1165 break;
1166 }
1167
1168 case RatingRole: {
1169 result = a->values.value("rating").toInt() - b->values.value("rating").toInt();
1170 break;
1171 }
1172
1173 default:
1174 break;
1175 }
1176
1177 if (result == 0) {
1178 // It must be assured that the sort order is always unique even if two values have been
1179 // equal. In this case a comparison of the URL is done which is unique in all cases
1180 // within KDirLister.
1181 result = QString::compare(itemA.url().url(), itemB.url().url(), Qt::CaseSensitive);
1182 }
1183
1184 return (sortOrder() == Qt::AscendingOrder) ? result < 0 : result > 0;
1185 }
1186
1187 void KFileItemModel::sort(QList<ItemData*>::iterator begin,
1188 QList<ItemData*>::iterator end)
1189 {
1190 // The implementation is based on qStableSortHelper() from qalgorithms.h
1191 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1192 // In opposite to qStableSort() it allows to use a member-function for the comparison of elements.
1193
1194 const int span = end - begin;
1195 if (span < 2) {
1196 return;
1197 }
1198
1199 const QList<ItemData*>::iterator middle = begin + span / 2;
1200 sort(begin, middle);
1201 sort(middle, end);
1202 merge(begin, middle, end);
1203 }
1204
1205 void KFileItemModel::merge(QList<ItemData*>::iterator begin,
1206 QList<ItemData*>::iterator pivot,
1207 QList<ItemData*>::iterator end)
1208 {
1209 // The implementation is based on qMerge() from qalgorithms.h
1210 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1211
1212 const int len1 = pivot - begin;
1213 const int len2 = end - pivot;
1214
1215 if (len1 == 0 || len2 == 0) {
1216 return;
1217 }
1218
1219 if (len1 + len2 == 2) {
1220 if (lessThan(*(begin + 1), *(begin))) {
1221 qSwap(*begin, *(begin + 1));
1222 }
1223 return;
1224 }
1225
1226 QList<ItemData*>::iterator firstCut;
1227 QList<ItemData*>::iterator secondCut;
1228 int len2Half;
1229 if (len1 > len2) {
1230 const int len1Half = len1 / 2;
1231 firstCut = begin + len1Half;
1232 secondCut = lowerBound(pivot, end, *firstCut);
1233 len2Half = secondCut - pivot;
1234 } else {
1235 len2Half = len2 / 2;
1236 secondCut = pivot + len2Half;
1237 firstCut = upperBound(begin, pivot, *secondCut);
1238 }
1239
1240 reverse(firstCut, pivot);
1241 reverse(pivot, secondCut);
1242 reverse(firstCut, secondCut);
1243
1244 const QList<ItemData*>::iterator newPivot = firstCut + len2Half;
1245 merge(begin, firstCut, newPivot);
1246 merge(newPivot, secondCut, end);
1247 }
1248
1249 QList<KFileItemModel::ItemData*>::iterator KFileItemModel::lowerBound(QList<ItemData*>::iterator begin,
1250 QList<ItemData*>::iterator end,
1251 const ItemData* value)
1252 {
1253 // The implementation is based on qLowerBound() from qalgorithms.h
1254 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1255
1256 QList<ItemData*>::iterator middle;
1257 int n = int(end - begin);
1258 int half;
1259
1260 while (n > 0) {
1261 half = n >> 1;
1262 middle = begin + half;
1263 if (lessThan(*middle, value)) {
1264 begin = middle + 1;
1265 n -= half + 1;
1266 } else {
1267 n = half;
1268 }
1269 }
1270 return begin;
1271 }
1272
1273 QList<KFileItemModel::ItemData*>::iterator KFileItemModel::upperBound(QList<ItemData*>::iterator begin,
1274 QList<ItemData*>::iterator end,
1275 const ItemData* value)
1276 {
1277 // The implementation is based on qUpperBound() from qalgorithms.h
1278 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1279
1280 QList<ItemData*>::iterator middle;
1281 int n = end - begin;
1282 int half;
1283
1284 while (n > 0) {
1285 half = n >> 1;
1286 middle = begin + half;
1287 if (lessThan(value, *middle)) {
1288 n = half;
1289 } else {
1290 begin = middle + 1;
1291 n -= half + 1;
1292 }
1293 }
1294 return begin;
1295 }
1296
1297 void KFileItemModel::reverse(QList<ItemData*>::iterator begin,
1298 QList<ItemData*>::iterator end)
1299 {
1300 // The implementation is based on qReverse() from qalgorithms.h
1301 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
1302
1303 --end;
1304 while (begin < end) {
1305 qSwap(*begin++, *end--);
1306 }
1307 }
1308
1309 int KFileItemModel::stringCompare(const QString& a, const QString& b) const
1310 {
1311 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1312 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1313 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1314 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1315
1316 if (m_caseSensitivity == Qt::CaseInsensitive) {
1317 const int result = m_naturalSorting ? KStringHandler::naturalCompare(a, b, Qt::CaseInsensitive)
1318 : QString::compare(a, b, Qt::CaseInsensitive);
1319 if (result != 0) {
1320 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1321 // comparison, still a deterministic sort order is required. A case sensitive
1322 // comparison is done as fallback.
1323 return result;
1324 }
1325 }
1326
1327 return m_naturalSorting ? KStringHandler::naturalCompare(a, b, Qt::CaseSensitive)
1328 : QString::compare(a, b, Qt::CaseSensitive);
1329 }
1330
1331 int KFileItemModel::expansionLevelsCompare(const KFileItem& a, const KFileItem& b) const
1332 {
1333 const KUrl urlA = a.url();
1334 const KUrl urlB = b.url();
1335 if (urlA.directory() == urlB.directory()) {
1336 // Both items have the same directory as parent
1337 return 0;
1338 }
1339
1340 // Check whether one item is the parent of the other item
1341 if (urlA.isParentOf(urlB)) {
1342 return -1;
1343 } else if (urlB.isParentOf(urlA)) {
1344 return +1;
1345 }
1346
1347 // Determine the maximum common path of both items and
1348 // remember the index in 'index'
1349 const QString pathA = urlA.path();
1350 const QString pathB = urlB.path();
1351
1352 const int maxIndex = qMin(pathA.length(), pathB.length()) - 1;
1353 int index = 0;
1354 while (index <= maxIndex && pathA.at(index) == pathB.at(index)) {
1355 ++index;
1356 }
1357 if (index > maxIndex) {
1358 index = maxIndex;
1359 }
1360 while ((pathA.at(index) != QLatin1Char('/') || pathB.at(index) != QLatin1Char('/')) && index > 0) {
1361 --index;
1362 }
1363
1364 // Determine the first sub-path after the common path and
1365 // check whether it represents a directory or already a file
1366 bool isDirA = true;
1367 const QString subPathA = subPath(a, pathA, index, &isDirA);
1368 bool isDirB = true;
1369 const QString subPathB = subPath(b, pathB, index, &isDirB);
1370
1371 if (isDirA && !isDirB) {
1372 return -1;
1373 } else if (!isDirA && isDirB) {
1374 return +1;
1375 }
1376
1377 return stringCompare(subPathA, subPathB);
1378 }
1379
1380 QString KFileItemModel::subPath(const KFileItem& item,
1381 const QString& itemPath,
1382 int start,
1383 bool* isDir) const
1384 {
1385 Q_ASSERT(isDir);
1386 const int pathIndex = itemPath.indexOf('/', start + 1);
1387 *isDir = (pathIndex > 0) || item.isDir();
1388 return itemPath.mid(start, pathIndex - start);
1389 }
1390
1391 bool KFileItemModel::useMaximumUpdateInterval() const
1392 {
1393 const KDirLister* dirLister = m_dirLister.data();
1394 return dirLister && !dirLister->url().isLocalFile();
1395 }
1396
1397 QList<QPair<int, QVariant> > KFileItemModel::nameRoleGroups() const
1398 {
1399 Q_ASSERT(!m_itemData.isEmpty());
1400
1401 const int maxIndex = count() - 1;
1402 QList<QPair<int, QVariant> > groups;
1403
1404 QString groupValue;
1405 QChar firstChar;
1406 bool isLetter = false;
1407 for (int i = 0; i <= maxIndex; ++i) {
1408 if (isChildItem(i)) {
1409 continue;
1410 }
1411
1412 const QString name = m_itemData.at(i)->values.value("name").toString();
1413
1414 // Use the first character of the name as group indication
1415 QChar newFirstChar = name.at(0).toUpper();
1416 if (newFirstChar == QLatin1Char('~') && name.length() > 1) {
1417 newFirstChar = name.at(1);
1418 }
1419
1420 if (firstChar != newFirstChar) {
1421 QString newGroupValue;
1422 if (newFirstChar >= QLatin1Char('A') && newFirstChar <= QLatin1Char('Z')) {
1423 // Apply group 'A' - 'Z'
1424 newGroupValue = newFirstChar;
1425 isLetter = true;
1426 } else if (newFirstChar >= QLatin1Char('0') && newFirstChar <= QLatin1Char('9')) {
1427 // Apply group '0 - 9' for any name that starts with a digit
1428 newGroupValue = i18nc("@title:group Groups that start with a digit", "0 - 9");
1429 isLetter = false;
1430 } else {
1431 if (isLetter) {
1432 // If the current group is 'A' - 'Z' check whether a locale character
1433 // fits into the existing group.
1434 // TODO: This does not work in the case if e.g. the group 'O' starts with
1435 // an umlaut 'O' -> provide unit-test to document this known issue
1436 const QChar prevChar(firstChar.unicode() - ushort(1));
1437 const QChar nextChar(firstChar.unicode() + ushort(1));
1438 const QString currChar(newFirstChar);
1439 const bool partOfCurrentGroup = currChar.localeAwareCompare(prevChar) > 0 &&
1440 currChar.localeAwareCompare(nextChar) < 0;
1441 if (partOfCurrentGroup) {
1442 continue;
1443 }
1444 }
1445 newGroupValue = i18nc("@title:group", "Others");
1446 isLetter = false;
1447 }
1448
1449 if (newGroupValue != groupValue) {
1450 groupValue = newGroupValue;
1451 groups.append(QPair<int, QVariant>(i, newGroupValue));
1452 }
1453
1454 firstChar = newFirstChar;
1455 }
1456 }
1457 return groups;
1458 }
1459
1460 QList<QPair<int, QVariant> > KFileItemModel::sizeRoleGroups() const
1461 {
1462 Q_ASSERT(!m_itemData.isEmpty());
1463
1464 const int maxIndex = count() - 1;
1465 QList<QPair<int, QVariant> > groups;
1466
1467 QString groupValue;
1468 for (int i = 0; i <= maxIndex; ++i) {
1469 if (isChildItem(i)) {
1470 continue;
1471 }
1472
1473 const KFileItem& item = m_itemData.at(i)->item;
1474 const KIO::filesize_t fileSize = !item.isNull() ? item.size() : ~0U;
1475 QString newGroupValue;
1476 if (!item.isNull() && item.isDir()) {
1477 newGroupValue = i18nc("@title:group Size", "Folders");
1478 } else if (fileSize < 5 * 1024 * 1024) {
1479 newGroupValue = i18nc("@title:group Size", "Small");
1480 } else if (fileSize < 10 * 1024 * 1024) {
1481 newGroupValue = i18nc("@title:group Size", "Medium");
1482 } else {
1483 newGroupValue = i18nc("@title:group Size", "Big");
1484 }
1485
1486 if (newGroupValue != groupValue) {
1487 groupValue = newGroupValue;
1488 groups.append(QPair<int, QVariant>(i, newGroupValue));
1489 }
1490 }
1491
1492 return groups;
1493 }
1494
1495 QList<QPair<int, QVariant> > KFileItemModel::dateRoleGroups() const
1496 {
1497 Q_ASSERT(!m_itemData.isEmpty());
1498
1499 const int maxIndex = count() - 1;
1500 QList<QPair<int, QVariant> > groups;
1501
1502 const QDate currentDate = KDateTime::currentLocalDateTime().date();
1503
1504 int yearForCurrentWeek = 0;
1505 int currentWeek = currentDate.weekNumber(&yearForCurrentWeek);
1506 if (yearForCurrentWeek == currentDate.year() + 1) {
1507 currentWeek = 53;
1508 }
1509
1510 QDate previousModifiedDate;
1511 QString groupValue;
1512 for (int i = 0; i <= maxIndex; ++i) {
1513 if (isChildItem(i)) {
1514 continue;
1515 }
1516
1517 const KDateTime modifiedTime = m_itemData.at(i)->item.time(KFileItem::ModificationTime);
1518 const QDate modifiedDate = modifiedTime.date();
1519 if (modifiedDate == previousModifiedDate) {
1520 // The current item is in the same group as the previous item
1521 continue;
1522 }
1523 previousModifiedDate = modifiedDate;
1524
1525 const int daysDistance = modifiedDate.daysTo(currentDate);
1526
1527 int yearForModifiedWeek = 0;
1528 int modifiedWeek = modifiedDate.weekNumber(&yearForModifiedWeek);
1529 if (yearForModifiedWeek == modifiedDate.year() + 1) {
1530 modifiedWeek = 53;
1531 }
1532
1533 QString newGroupValue;
1534 if (currentDate.year() == modifiedDate.year() && currentDate.month() == modifiedDate.month()) {
1535 if (modifiedWeek > currentWeek) {
1536 // Usecase: modified date = 2010-01-01, current date = 2010-01-22
1537 // modified week = 53, current week = 3
1538 modifiedWeek = 0;
1539 }
1540 switch (currentWeek - modifiedWeek) {
1541 case 0:
1542 switch (daysDistance) {
1543 case 0: newGroupValue = i18nc("@title:group Date", "Today"); break;
1544 case 1: newGroupValue = i18nc("@title:group Date", "Yesterday"); break;
1545 default: newGroupValue = modifiedTime.toString(i18nc("@title:group The week day name: %A", "%A"));
1546 }
1547 break;
1548 case 1:
1549 newGroupValue = i18nc("@title:group Date", "Last Week");
1550 break;
1551 case 2:
1552 newGroupValue = i18nc("@title:group Date", "Two Weeks Ago");
1553 break;
1554 case 3:
1555 newGroupValue = i18nc("@title:group Date", "Three Weeks Ago");
1556 break;
1557 case 4:
1558 case 5:
1559 newGroupValue = i18nc("@title:group Date", "Earlier this Month");
1560 break;
1561 default:
1562 Q_ASSERT(false);
1563 }
1564 } else {
1565 const QDate lastMonthDate = currentDate.addMonths(-1);
1566 if (lastMonthDate.year() == modifiedDate.year() && lastMonthDate.month() == modifiedDate.month()) {
1567 if (daysDistance == 1) {
1568 newGroupValue = modifiedTime.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Yesterday (%B, %Y)"));
1569 } else if (daysDistance <= 7) {
1570 newGroupValue = modifiedTime.toString(i18nc("@title:group The week day name: %A, %B is full month name in current locale, and %Y is full year number", "%A (%B, %Y)"));
1571 } else if (daysDistance <= 7 * 2) {
1572 newGroupValue = modifiedTime.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Last Week (%B, %Y)"));
1573 } else if (daysDistance <= 7 * 3) {
1574 newGroupValue = modifiedTime.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Two Weeks Ago (%B, %Y)"));
1575 } else if (daysDistance <= 7 * 4) {
1576 newGroupValue = modifiedTime.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Three Weeks Ago (%B, %Y)"));
1577 } else {
1578 newGroupValue = modifiedTime.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Earlier on %B, %Y"));
1579 }
1580 } else {
1581 newGroupValue = modifiedTime.toString(i18nc("@title:group The month and year: %B is full month name in current locale, and %Y is full year number", "%B, %Y"));
1582 }
1583 }
1584
1585 if (newGroupValue != groupValue) {
1586 groupValue = newGroupValue;
1587 groups.append(QPair<int, QVariant>(i, newGroupValue));
1588 }
1589 }
1590
1591 return groups;
1592 }
1593
1594 QList<QPair<int, QVariant> > KFileItemModel::permissionRoleGroups() const
1595 {
1596 Q_ASSERT(!m_itemData.isEmpty());
1597
1598 const int maxIndex = count() - 1;
1599 QList<QPair<int, QVariant> > groups;
1600
1601 QString permissionsString;
1602 QString groupValue;
1603 for (int i = 0; i <= maxIndex; ++i) {
1604 if (isChildItem(i)) {
1605 continue;
1606 }
1607
1608 const ItemData* itemData = m_itemData.at(i);
1609 const QString newPermissionsString = itemData->values.value("permissions").toString();
1610 if (newPermissionsString == permissionsString) {
1611 continue;
1612 }
1613 permissionsString = newPermissionsString;
1614
1615 const QFileInfo info(itemData->item.url().pathOrUrl());
1616
1617 // Set user string
1618 QString user;
1619 if (info.permission(QFile::ReadUser)) {
1620 user = i18nc("@item:intext Access permission, concatenated", "Read, ");
1621 }
1622 if (info.permission(QFile::WriteUser)) {
1623 user += i18nc("@item:intext Access permission, concatenated", "Write, ");
1624 }
1625 if (info.permission(QFile::ExeUser)) {
1626 user += i18nc("@item:intext Access permission, concatenated", "Execute, ");
1627 }
1628 user = user.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user.mid(0, user.count() - 2);
1629
1630 // Set group string
1631 QString group;
1632 if (info.permission(QFile::ReadGroup)) {
1633 group = i18nc("@item:intext Access permission, concatenated", "Read, ");
1634 }
1635 if (info.permission(QFile::WriteGroup)) {
1636 group += i18nc("@item:intext Access permission, concatenated", "Write, ");
1637 }
1638 if (info.permission(QFile::ExeGroup)) {
1639 group += i18nc("@item:intext Access permission, concatenated", "Execute, ");
1640 }
1641 group = group.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group.mid(0, group.count() - 2);
1642
1643 // Set others string
1644 QString others;
1645 if (info.permission(QFile::ReadOther)) {
1646 others = i18nc("@item:intext Access permission, concatenated", "Read, ");
1647 }
1648 if (info.permission(QFile::WriteOther)) {
1649 others += i18nc("@item:intext Access permission, concatenated", "Write, ");
1650 }
1651 if (info.permission(QFile::ExeOther)) {
1652 others += i18nc("@item:intext Access permission, concatenated", "Execute, ");
1653 }
1654 others = others.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others.mid(0, others.count() - 2);
1655
1656 const QString newGroupValue = i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user, group, others);
1657 if (newGroupValue != groupValue) {
1658 groupValue = newGroupValue;
1659 groups.append(QPair<int, QVariant>(i, newGroupValue));
1660 }
1661 }
1662
1663 return groups;
1664 }
1665
1666 QList<QPair<int, QVariant> > KFileItemModel::ratingRoleGroups() const
1667 {
1668 Q_ASSERT(!m_itemData.isEmpty());
1669
1670 const int maxIndex = count() - 1;
1671 QList<QPair<int, QVariant> > groups;
1672
1673 int groupValue;
1674 for (int i = 0; i <= maxIndex; ++i) {
1675 if (isChildItem(i)) {
1676 continue;
1677 }
1678 const int newGroupValue = m_itemData.at(i)->values.value("rating").toInt();
1679 if (newGroupValue != groupValue) {
1680 groupValue = newGroupValue;
1681 groups.append(QPair<int, QVariant>(i, newGroupValue));
1682 }
1683 }
1684
1685 return groups;
1686 }
1687
1688 QList<QPair<int, QVariant> > KFileItemModel::genericStringRoleGroups(const QByteArray& role) const
1689 {
1690 Q_ASSERT(!m_itemData.isEmpty());
1691
1692 const int maxIndex = count() - 1;
1693 QList<QPair<int, QVariant> > groups;
1694
1695 QString groupValue;
1696 for (int i = 0; i <= maxIndex; ++i) {
1697 if (isChildItem(i)) {
1698 continue;
1699 }
1700 const QString newGroupValue = m_itemData.at(i)->values.value(role).toString();
1701 if (newGroupValue != groupValue) {
1702 groupValue = newGroupValue;
1703 groups.append(QPair<int, QVariant>(i, newGroupValue));
1704 }
1705 }
1706
1707 return groups;
1708 }
1709
1710 bool KFileItemModel::matchesNameFilter(const KFileItem& item, const QString& nameFilter)
1711 {
1712 const QString itemText = item.text().toLower();
1713 return itemText.contains(nameFilter);
1714 }
1715
1716 #include "kfileitemmodel.moc"