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