]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kfileitemmodel.cpp
Show the role-description in the header of the details view
[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(QByteArray(), "name", parent),
35 m_dirLister(dirLister),
36 m_naturalSorting(true),
37 m_sortFoldersFirst(true),
38 m_groupRole(NoRole),
39 m_sortRole(NameRole),
40 m_caseSensitivity(Qt::CaseInsensitive),
41 m_sortedItems(),
42 m_items(),
43 m_data(),
44 m_requestRole(),
45 m_minimumUpdateIntervalTimer(0),
46 m_maximumUpdateIntervalTimer(0),
47 m_pendingItemsToInsert(),
48 m_pendingEmitLoadingCompleted(false),
49 m_rootExpansionLevel(-1),
50 m_expandedUrls(),
51 m_restoredExpandedUrls()
52 {
53 resetRoles();
54 m_requestRole[NameRole] = true;
55 m_requestRole[IsDirRole] = true;
56
57 Q_ASSERT(dirLister);
58
59 connect(dirLister, SIGNAL(canceled()), this, SLOT(slotCanceled()));
60 connect(dirLister, SIGNAL(completed()), this, SLOT(slotCompleted()));
61 connect(dirLister, SIGNAL(newItems(KFileItemList)), this, SLOT(slotNewItems(KFileItemList)));
62 connect(dirLister, SIGNAL(itemsDeleted(KFileItemList)), this, SLOT(slotItemsDeleted(KFileItemList)));
63 connect(dirLister, SIGNAL(refreshItems(QList<QPair<KFileItem,KFileItem> >)), this, SLOT(slotRefreshItems(QList<QPair<KFileItem,KFileItem> >)));
64 connect(dirLister, SIGNAL(clear()), this, SLOT(slotClear()));
65 connect(dirLister, SIGNAL(clear(KUrl)), this, SLOT(slotClear(KUrl)));
66
67 // Although the layout engine of KItemListView is fast it is very inefficient to e.g.
68 // emit 50 itemsInserted()-signals each 100 ms. m_minimumUpdateIntervalTimer assures that updates
69 // are done in 1 second intervals for equal operations.
70 m_minimumUpdateIntervalTimer = new QTimer(this);
71 m_minimumUpdateIntervalTimer->setInterval(1000);
72 m_minimumUpdateIntervalTimer->setSingleShot(true);
73 connect(m_minimumUpdateIntervalTimer, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
74
75 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
76 // before the completed() or canceled() signal has been emitted.
77 m_maximumUpdateIntervalTimer = new QTimer(this);
78 m_maximumUpdateIntervalTimer->setInterval(2000);
79 m_maximumUpdateIntervalTimer->setSingleShot(true);
80 connect(m_maximumUpdateIntervalTimer, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
81
82 Q_ASSERT(m_minimumUpdateIntervalTimer->interval() <= m_maximumUpdateIntervalTimer->interval());
83 }
84
85 KFileItemModel::~KFileItemModel()
86 {
87 }
88
89 int KFileItemModel::count() const
90 {
91 return m_data.count();
92 }
93
94 QHash<QByteArray, QVariant> KFileItemModel::data(int index) const
95 {
96 if (index >= 0 && index < count()) {
97 return m_data.at(index);
98 }
99 return QHash<QByteArray, QVariant>();
100 }
101
102 bool KFileItemModel::setData(int index, const QHash<QByteArray, QVariant>& values)
103 {
104 if (index >= 0 && index < count()) {
105 QHash<QByteArray, QVariant> currentValue = m_data.at(index);
106
107 QSet<QByteArray> changedRoles;
108 QHashIterator<QByteArray, QVariant> it(values);
109 while (it.hasNext()) {
110 it.next();
111 const QByteArray role = it.key();
112 const QVariant value = it.value();
113
114 if (currentValue[role] != value) {
115 currentValue[role] = value;
116 changedRoles.insert(role);
117 }
118 }
119
120 if (!changedRoles.isEmpty()) {
121 m_data[index] = currentValue;
122 emit itemsChanged(KItemRangeList() << KItemRange(index, 1), changedRoles);
123 }
124
125 return true;
126 }
127 return false;
128 }
129
130 bool KFileItemModel::supportsGrouping() const
131 {
132 return true;
133 }
134
135 bool KFileItemModel::supportsSorting() const
136 {
137 return true;
138 }
139
140 void KFileItemModel::setSortFoldersFirst(bool foldersFirst)
141 {
142 if (foldersFirst != m_sortFoldersFirst) {
143 m_sortFoldersFirst = foldersFirst;
144 resortAllItems();
145 }
146 }
147
148 bool KFileItemModel::sortFoldersFirst() const
149 {
150 return m_sortFoldersFirst;
151 }
152
153 QMimeData* KFileItemModel::createMimeData(const QSet<int>& indexes) const
154 {
155 QMimeData* data = new QMimeData();
156
157 // The following code has been taken from KDirModel::mimeData()
158 // (kdelibs/kio/kio/kdirmodel.cpp)
159 // Copyright (C) 2006 David Faure <faure@kde.org>
160 KUrl::List urls;
161 KUrl::List mostLocalUrls;
162 bool canUseMostLocalUrls = true;
163
164 QSetIterator<int> it(indexes);
165 while (it.hasNext()) {
166 const int index = it.next();
167 const KFileItem item = fileItem(index);
168 if (!item.isNull()) {
169 urls << item.url();
170
171 bool isLocal;
172 mostLocalUrls << item.mostLocalUrl(isLocal);
173 if (!isLocal) {
174 canUseMostLocalUrls = false;
175 }
176 }
177 }
178
179 const bool different = canUseMostLocalUrls && mostLocalUrls != urls;
180 urls = KDirModel::simplifiedUrlList(urls); // TODO: Check if we still need KDirModel for this in KDE 5.0
181 if (different) {
182 mostLocalUrls = KDirModel::simplifiedUrlList(mostLocalUrls);
183 urls.populateMimeData(mostLocalUrls, data);
184 } else {
185 urls.populateMimeData(data);
186 }
187
188 return data;
189 }
190
191 int KFileItemModel::indexForKeyboardSearch(const QString& text, int startFromIndex) const
192 {
193 startFromIndex = qMax(0, startFromIndex);
194 for (int i = startFromIndex; i < count(); i++) {
195 if (data(i)["name"].toString().startsWith(text, Qt::CaseInsensitive)) {
196 kDebug() << data(i)["name"].toString();
197 return i;
198 }
199 }
200 for (int i = 0; i < startFromIndex; i++) {
201 if (data(i)["name"].toString().startsWith(text, Qt::CaseInsensitive)) {
202 kDebug() << data(i)["name"].toString();
203 return i;
204 }
205 }
206 return -1;
207 }
208
209 bool KFileItemModel::supportsDropping(int index) const
210 {
211 const KFileItem item = fileItem(index);
212 return item.isNull() ? false : item.isDir();
213 }
214
215 QString KFileItemModel::roleDescription(const QByteArray& role) const
216 {
217 QString descr;
218
219 switch (roleIndex(role)) {
220 case NameRole: descr = i18nc("@item:intable", "Name"); break;
221 case SizeRole: descr = i18nc("@item:intable", "Size"); break;
222 case DateRole: descr = i18nc("@item:intable", "Date"); break;
223 case PermissionsRole: descr = i18nc("@item:intable", "Permissions"); break;
224 case OwnerRole: descr = i18nc("@item:intable", "Owner"); break;
225 case GroupRole: descr = i18nc("@item:intable", "Group"); break;
226 case TypeRole: descr = i18nc("@item:intable", "Type"); break;
227 case DestinationRole: descr = i18nc("@item:intable", "Destination"); break;
228 case PathRole: descr = i18nc("@item:intable", "Path"); break;
229 case NoRole: break;
230 case IsDirRole: break;
231 case IsExpandedRole: break;
232 case ExpansionLevelRole: break;
233 default: Q_ASSERT(false); break;
234 }
235
236 return descr;
237 }
238
239 KFileItem KFileItemModel::fileItem(int index) const
240 {
241 if (index >= 0 && index < count()) {
242 return m_sortedItems.at(index);
243 }
244
245 return KFileItem();
246 }
247
248 KFileItem KFileItemModel::fileItem(const KUrl& url) const
249 {
250 const int index = m_items.value(url, -1);
251 if (index >= 0) {
252 return m_sortedItems.at(index);
253 }
254 return KFileItem();
255 }
256
257 int KFileItemModel::index(const KFileItem& item) const
258 {
259 if (item.isNull()) {
260 return -1;
261 }
262
263 return m_items.value(item.url(), -1);
264 }
265
266 KFileItem KFileItemModel::rootItem() const
267 {
268 const KDirLister* dirLister = m_dirLister.data();
269 if (dirLister) {
270 return dirLister->rootItem();
271 }
272 return KFileItem();
273 }
274
275 void KFileItemModel::clear()
276 {
277 slotClear();
278 }
279
280 void KFileItemModel::setRoles(const QSet<QByteArray>& roles)
281 {
282 if (count() > 0) {
283 const bool supportedExpanding = m_requestRole[IsExpandedRole] && m_requestRole[ExpansionLevelRole];
284 const bool willSupportExpanding = roles.contains("isExpanded") && roles.contains("expansionLevel");
285 if (supportedExpanding && !willSupportExpanding) {
286 // No expanding is supported anymore. Take care to delete all items that have an expansion level
287 // that is not 0 (and hence are part of an expanded item).
288 removeExpandedItems();
289 }
290 }
291
292 resetRoles();
293 QSetIterator<QByteArray> it(roles);
294 while (it.hasNext()) {
295 const QByteArray& role = it.next();
296 m_requestRole[roleIndex(role)] = true;
297 }
298
299 if (count() > 0) {
300 // Update m_data with the changed requested roles
301 const int maxIndex = count() - 1;
302 for (int i = 0; i <= maxIndex; ++i) {
303 m_data[i] = retrieveData(m_sortedItems.at(i));
304 }
305
306 kWarning() << "TODO: Emitting itemsChanged() with no information what has changed!";
307 emit itemsChanged(KItemRangeList() << KItemRange(0, count()), QSet<QByteArray>());
308 }
309 }
310
311 QSet<QByteArray> KFileItemModel::roles() const
312 {
313 QSet<QByteArray> roles;
314 for (int i = 0; i < RolesCount; ++i) {
315 if (m_requestRole[i]) {
316 switch (i) {
317 case NoRole: break;
318 case NameRole: roles.insert("name"); break;
319 case SizeRole: roles.insert("size"); break;
320 case DateRole: roles.insert("date"); break;
321 case PermissionsRole: roles.insert("permissions"); break;
322 case OwnerRole: roles.insert("owner"); break;
323 case GroupRole: roles.insert("group"); break;
324 case TypeRole: roles.insert("type"); break;
325 case DestinationRole: roles.insert("destination"); break;
326 case PathRole: roles.insert("path"); break;
327 case IsDirRole: roles.insert("isDir"); break;
328 case IsExpandedRole: roles.insert("isExpanded"); break;
329 case ExpansionLevelRole: roles.insert("expansionLevel"); break;
330 default: Q_ASSERT(false); break;
331 }
332 }
333 }
334 return roles;
335 }
336
337 bool KFileItemModel::setExpanded(int index, bool expanded)
338 {
339 if (isExpanded(index) == expanded || index < 0 || index >= count()) {
340 return false;
341 }
342
343 QHash<QByteArray, QVariant> values;
344 values.insert("isExpanded", expanded);
345 if (!setData(index, values)) {
346 return false;
347 }
348
349 const KUrl url = m_sortedItems.at(index).url();
350 if (expanded) {
351 m_expandedUrls.insert(url);
352
353 KDirLister* dirLister = m_dirLister.data();
354 if (dirLister) {
355 dirLister->openUrl(url, KDirLister::Keep);
356 return true;
357 }
358 } else {
359 m_expandedUrls.remove(url);
360
361 KFileItemList itemsToRemove;
362 const int expansionLevel = data(index)["expansionLevel"].toInt();
363 ++index;
364 while (index < count() && data(index)["expansionLevel"].toInt() > expansionLevel) {
365 itemsToRemove.append(m_sortedItems.at(index));
366 ++index;
367 }
368 removeItems(itemsToRemove);
369 return true;
370 }
371
372 return false;
373 }
374
375 bool KFileItemModel::isExpanded(int index) const
376 {
377 if (index >= 0 && index < count()) {
378 return m_data.at(index).value("isExpanded").toBool();
379 }
380 return false;
381 }
382
383 bool KFileItemModel::isExpandable(int index) const
384 {
385 if (index >= 0 && index < count()) {
386 return m_sortedItems.at(index).isDir();
387 }
388 return false;
389 }
390
391 QSet<KUrl> KFileItemModel::expandedUrls() const
392 {
393 return m_expandedUrls;
394 }
395
396 void KFileItemModel::restoreExpandedUrls(const QSet<KUrl>& urls)
397 {
398 m_restoredExpandedUrls = urls;
399 }
400
401 void KFileItemModel::onGroupRoleChanged(const QByteArray& current, const QByteArray& previous)
402 {
403 Q_UNUSED(previous);
404 m_groupRole = roleIndex(current);
405 }
406
407 void KFileItemModel::onSortRoleChanged(const QByteArray& current, const QByteArray& previous)
408 {
409 Q_UNUSED(previous);
410 m_sortRole = roleIndex(current);
411 resortAllItems();
412 }
413
414 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous)
415 {
416 Q_UNUSED(current);
417 Q_UNUSED(previous);
418 resortAllItems();
419 }
420
421 void KFileItemModel::slotCompleted()
422 {
423 if (m_restoredExpandedUrls.isEmpty() && m_minimumUpdateIntervalTimer->isActive()) {
424 // dispatchPendingItems() will be called when the timer
425 // has been expired.
426 m_pendingEmitLoadingCompleted = true;
427 return;
428 }
429
430 m_pendingEmitLoadingCompleted = false;
431 dispatchPendingItemsToInsert();
432
433 if (!m_restoredExpandedUrls.isEmpty()) {
434 // Try to find a URL that can be expanded.
435 // Note that the parent folder must be expanded before any of its subfolders become visible.
436 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
437 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
438 foreach(const KUrl& url, m_restoredExpandedUrls) {
439 const int index = m_items.value(url, -1);
440 if (index >= 0) {
441 // We have found an expandable URL. Expand it and return - when
442 // the dir lister has finished, this slot will be called again.
443 m_restoredExpandedUrls.remove(url);
444 setExpanded(index, true);
445 return;
446 }
447 }
448
449 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
450 // if these URLs have been deleted in the meantime.
451 m_restoredExpandedUrls.clear();
452 }
453
454 emit loadingCompleted();
455 m_minimumUpdateIntervalTimer->start();
456 }
457
458 void KFileItemModel::slotCanceled()
459 {
460 m_minimumUpdateIntervalTimer->stop();
461 m_maximumUpdateIntervalTimer->stop();
462 dispatchPendingItemsToInsert();
463 }
464
465 void KFileItemModel::slotNewItems(const KFileItemList& items)
466 {
467 m_pendingItemsToInsert.append(items);
468
469 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer->isActive()) {
470 // Assure that items get dispatched if no completed() or canceled() signal is
471 // emitted during the maximum update interval.
472 m_maximumUpdateIntervalTimer->start();
473 }
474 }
475
476 void KFileItemModel::slotItemsDeleted(const KFileItemList& items)
477 {
478 if (!m_pendingItemsToInsert.isEmpty()) {
479 insertItems(m_pendingItemsToInsert);
480 m_pendingItemsToInsert.clear();
481 }
482 removeItems(items);
483 }
484
485 void KFileItemModel::slotRefreshItems(const QList<QPair<KFileItem, KFileItem> >& items)
486 {
487 Q_ASSERT(!items.isEmpty());
488 #ifdef KFILEITEMMODEL_DEBUG
489 kDebug() << "Refreshing" << items.count() << "items";
490 #endif
491
492 // Get the indexes of all items that have been refreshed
493 QList<int> indexes;
494 indexes.reserve(items.count());
495
496 QListIterator<QPair<KFileItem, KFileItem> > it(items);
497 while (it.hasNext()) {
498 const QPair<KFileItem, KFileItem>& itemPair = it.next();
499 const int index = m_items.value(itemPair.second.url(), -1);
500 if (index >= 0) {
501 indexes.append(index);
502 }
503 }
504
505 // If the changed items have been created recently, they might not be in m_items yet.
506 // In that case, the list 'indexes' might be empty.
507 if (indexes.isEmpty()) {
508 return;
509 }
510
511 // Extract the item-ranges out of the changed indexes
512 qSort(indexes);
513
514 KItemRangeList itemRangeList;
515 int rangeIndex = 0;
516 int rangeCount = 1;
517 int previousIndex = indexes.at(0);
518
519 const int maxIndex = indexes.count() - 1;
520 for (int i = 1; i <= maxIndex; ++i) {
521 const int currentIndex = indexes.at(i);
522 if (currentIndex == previousIndex + 1) {
523 ++rangeCount;
524 } else {
525 itemRangeList.append(KItemRange(rangeIndex, rangeCount));
526
527 rangeIndex = currentIndex;
528 rangeCount = 1;
529 }
530 previousIndex = currentIndex;
531 }
532
533 if (rangeCount > 0) {
534 itemRangeList.append(KItemRange(rangeIndex, rangeCount));
535 }
536
537 emit itemsChanged(itemRangeList, QSet<QByteArray>());
538 }
539
540 void KFileItemModel::slotClear()
541 {
542 #ifdef KFILEITEMMODEL_DEBUG
543 kDebug() << "Clearing all items";
544 #endif
545
546 m_minimumUpdateIntervalTimer->stop();
547 m_maximumUpdateIntervalTimer->stop();
548 m_pendingItemsToInsert.clear();
549
550 m_rootExpansionLevel = -1;
551
552 const int removedCount = m_data.count();
553 if (removedCount > 0) {
554 m_sortedItems.clear();
555 m_items.clear();
556 m_data.clear();
557 emit itemsRemoved(KItemRangeList() << KItemRange(0, removedCount));
558 }
559
560 m_expandedUrls.clear();
561 }
562
563 void KFileItemModel::slotClear(const KUrl& url)
564 {
565 Q_UNUSED(url);
566 }
567
568 void KFileItemModel::dispatchPendingItemsToInsert()
569 {
570 if (!m_pendingItemsToInsert.isEmpty()) {
571 insertItems(m_pendingItemsToInsert);
572 m_pendingItemsToInsert.clear();
573 }
574
575 if (m_pendingEmitLoadingCompleted) {
576 emit loadingCompleted();
577 }
578 }
579
580 void KFileItemModel::insertItems(const KFileItemList& items)
581 {
582 if (items.isEmpty()) {
583 return;
584 }
585
586 #ifdef KFILEITEMMODEL_DEBUG
587 QElapsedTimer timer;
588 timer.start();
589 kDebug() << "===========================================================";
590 kDebug() << "Inserting" << items.count() << "items";
591 #endif
592
593 KFileItemList sortedItems = items;
594 sort(sortedItems.begin(), sortedItems.end());
595
596 #ifdef KFILEITEMMODEL_DEBUG
597 kDebug() << "[TIME] Sorting:" << timer.elapsed();
598 #endif
599
600 KItemRangeList itemRanges;
601 int targetIndex = 0;
602 int sourceIndex = 0;
603 int insertedAtIndex = -1; // Index for the current item-range
604 int insertedCount = 0; // Count for the current item-range
605 int previouslyInsertedCount = 0; // Sum of previously inserted items for all ranges
606 while (sourceIndex < sortedItems.count()) {
607 // Find target index from m_items to insert the current item
608 // in a sorted order
609 const int previousTargetIndex = targetIndex;
610 while (targetIndex < m_sortedItems.count()) {
611 if (!lessThan(m_sortedItems.at(targetIndex), sortedItems.at(sourceIndex))) {
612 break;
613 }
614 ++targetIndex;
615 }
616
617 if (targetIndex - previousTargetIndex > 0 && insertedAtIndex >= 0) {
618 itemRanges << KItemRange(insertedAtIndex, insertedCount);
619 previouslyInsertedCount += insertedCount;
620 insertedAtIndex = targetIndex - previouslyInsertedCount;
621 insertedCount = 0;
622 }
623
624 // Insert item at the position targetIndex
625 const KFileItem item = sortedItems.at(sourceIndex);
626 m_sortedItems.insert(targetIndex, item);
627 m_data.insert(targetIndex, retrieveData(item));
628 // m_items will be inserted after the loop (see comment below)
629 ++insertedCount;
630
631 if (insertedAtIndex < 0) {
632 insertedAtIndex = targetIndex;
633 Q_ASSERT(previouslyInsertedCount == 0);
634 }
635 ++targetIndex;
636 ++sourceIndex;
637 }
638
639 // The indexes of all m_items must be adjusted, not only the index
640 // of the new items
641 for (int i = 0; i < m_sortedItems.count(); ++i) {
642 m_items.insert(m_sortedItems.at(i).url(), i);
643 }
644
645 itemRanges << KItemRange(insertedAtIndex, insertedCount);
646 emit itemsInserted(itemRanges);
647
648 #ifdef KFILEITEMMODEL_DEBUG
649 kDebug() << "[TIME] Inserting of" << items.count() << "items:" << timer.elapsed();
650 #endif
651 }
652
653 void KFileItemModel::removeItems(const KFileItemList& items)
654 {
655 if (items.isEmpty()) {
656 return;
657 }
658
659 #ifdef KFILEITEMMODEL_DEBUG
660 kDebug() << "Removing " << items.count() << "items";
661 #endif
662
663 KFileItemList sortedItems = items;
664 sort(sortedItems.begin(), sortedItems.end());
665
666 QList<int> indexesToRemove;
667 indexesToRemove.reserve(items.count());
668
669 // Calculate the item ranges that will get deleted
670 KItemRangeList itemRanges;
671 int removedAtIndex = -1;
672 int removedCount = 0;
673 int targetIndex = 0;
674 foreach (const KFileItem& itemToRemove, sortedItems) {
675 const int previousTargetIndex = targetIndex;
676 while (targetIndex < m_sortedItems.count()) {
677 if (m_sortedItems.at(targetIndex).url() == itemToRemove.url()) {
678 break;
679 }
680 ++targetIndex;
681 }
682 if (targetIndex >= m_sortedItems.count()) {
683 kWarning() << "Item that should be deleted has not been found!";
684 return;
685 }
686
687 if (targetIndex - previousTargetIndex > 0 && removedAtIndex >= 0) {
688 itemRanges << KItemRange(removedAtIndex, removedCount);
689 removedAtIndex = targetIndex;
690 removedCount = 0;
691 }
692
693 indexesToRemove.append(targetIndex);
694 if (removedAtIndex < 0) {
695 removedAtIndex = targetIndex;
696 }
697 ++removedCount;
698 ++targetIndex;
699 }
700
701 // Delete the items
702 for (int i = indexesToRemove.count() - 1; i >= 0; --i) {
703 const int indexToRemove = indexesToRemove.at(i);
704 m_items.remove(m_sortedItems.at(indexToRemove).url());
705 m_sortedItems.removeAt(indexToRemove);
706 m_data.removeAt(indexToRemove);
707 }
708
709 // The indexes of all m_items must be adjusted, not only the index
710 // of the removed items
711 for (int i = 0; i < m_sortedItems.count(); ++i) {
712 m_items.insert(m_sortedItems.at(i).url(), i);
713 }
714
715 if (count() <= 0) {
716 m_rootExpansionLevel = -1;
717 }
718
719 itemRanges << KItemRange(removedAtIndex, removedCount);
720 emit itemsRemoved(itemRanges);
721 }
722
723 void KFileItemModel::resortAllItems()
724 {
725 const int itemCount = count();
726 if (itemCount <= 0) {
727 return;
728 }
729
730 KFileItemList sortedItems = m_sortedItems;
731 m_sortedItems.clear();
732 m_items.clear();
733 m_data.clear();
734 emit itemsRemoved(KItemRangeList() << KItemRange(0, itemCount));
735
736 sort(sortedItems.begin(), sortedItems.end());
737 int index = 0;
738 foreach (const KFileItem& item, sortedItems) {
739 m_sortedItems.append(item);
740 m_items.insert(item.url(), index);
741 m_data.append(retrieveData(item));
742
743 ++index;
744 }
745
746 emit itemsInserted(KItemRangeList() << KItemRange(0, itemCount));
747 }
748
749 void KFileItemModel::removeExpandedItems()
750 {
751
752 KFileItemList expandedItems;
753
754 const int maxIndex = m_data.count() - 1;
755 for (int i = 0; i <= maxIndex; ++i) {
756 if (m_data.at(i).value("expansionLevel").toInt() > 0) {
757 const KFileItem fileItem = m_sortedItems.at(i);
758 expandedItems.append(fileItem);
759 }
760 }
761
762 // The m_rootExpansionLevel may not get reset before all items with
763 // a bigger expansionLevel have been removed.
764 Q_ASSERT(m_rootExpansionLevel >= 0);
765 removeItems(expandedItems);
766
767 m_rootExpansionLevel = -1;
768 m_expandedUrls.clear();
769 }
770
771 void KFileItemModel::resetRoles()
772 {
773 for (int i = 0; i < RolesCount; ++i) {
774 m_requestRole[i] = false;
775 }
776 }
777
778 KFileItemModel::Role KFileItemModel::roleIndex(const QByteArray& role) const
779 {
780 static QHash<QByteArray, Role> rolesHash;
781 if (rolesHash.isEmpty()) {
782 rolesHash.insert("name", NameRole);
783 rolesHash.insert("size", SizeRole);
784 rolesHash.insert("date", DateRole);
785 rolesHash.insert("permissions", PermissionsRole);
786 rolesHash.insert("owner", OwnerRole);
787 rolesHash.insert("group", GroupRole);
788 rolesHash.insert("type", TypeRole);
789 rolesHash.insert("destination", DestinationRole);
790 rolesHash.insert("path", PathRole);
791 rolesHash.insert("isDir", IsDirRole);
792 rolesHash.insert("isExpanded", IsExpandedRole);
793 rolesHash.insert("expansionLevel", ExpansionLevelRole);
794 }
795 return rolesHash.value(role, NoRole);
796 }
797
798 QHash<QByteArray, QVariant> KFileItemModel::retrieveData(const KFileItem& item) const
799 {
800 // It is important to insert only roles that are fast to retrieve. E.g.
801 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
802 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
803 QHash<QByteArray, QVariant> data;
804 data.insert("iconPixmap", QPixmap());
805
806 const bool isDir = item.isDir();
807 if (m_requestRole[IsDirRole]) {
808 data.insert("isDir", isDir);
809 }
810
811 if (m_requestRole[NameRole]) {
812 data.insert("name", item.name());
813 }
814
815 if (m_requestRole[SizeRole]) {
816 if (isDir) {
817 data.insert("size", QVariant());
818 } else {
819 data.insert("size", item.size());
820 }
821 }
822
823 if (m_requestRole[DateRole]) {
824 // Don't use KFileItem::timeString() as this is too expensive when
825 // having several thousands of items. Instead the formatting of the
826 // date-time will be done on-demand by the view when the date will be shown.
827 const KDateTime dateTime = item.time(KFileItem::ModificationTime);
828 data.insert("date", dateTime.dateTime());
829 }
830
831 if (m_requestRole[PermissionsRole]) {
832 data.insert("permissions", item.permissionsString());
833 }
834
835 if (m_requestRole[OwnerRole]) {
836 data.insert("owner", item.user());
837 }
838
839 if (m_requestRole[GroupRole]) {
840 data.insert("group", item.group());
841 }
842
843 if (m_requestRole[DestinationRole]) {
844 QString destination = item.linkDest();
845 if (destination.isEmpty()) {
846 destination = i18nc("@item:intable", "No destination");
847 }
848 data.insert("destination", destination);
849 }
850
851 if (m_requestRole[PathRole]) {
852 data.insert("path", item.localPath());
853 }
854
855 if (m_requestRole[IsExpandedRole]) {
856 data.insert("isExpanded", false);
857 }
858
859 if (m_requestRole[ExpansionLevelRole]) {
860 if (m_rootExpansionLevel < 0) {
861 KDirLister* dirLister = m_dirLister.data();
862 if (dirLister) {
863 const QString rootDir = dirLister->url().directory(KUrl::AppendTrailingSlash);
864 m_rootExpansionLevel = rootDir.count('/');
865 }
866 }
867 const QString dir = item.url().directory(KUrl::AppendTrailingSlash);
868 const int level = dir.count('/') - m_rootExpansionLevel - 1;
869 data.insert("expansionLevel", level);
870 }
871
872 if (item.isMimeTypeKnown()) {
873 data.insert("iconName", item.iconName());
874
875 if (m_requestRole[TypeRole]) {
876 data.insert("type", item.mimeComment());
877 }
878 }
879
880 return data;
881 }
882
883 bool KFileItemModel::lessThan(const KFileItem& a, const KFileItem& b) const
884 {
885 int result = 0;
886
887 if (m_rootExpansionLevel >= 0) {
888 result = expansionLevelsCompare(a, b);
889 if (result != 0) {
890 // The items have parents with different expansion levels
891 return (sortOrder() == Qt::AscendingOrder) ? result < 0 : result > 0;
892 }
893 }
894
895 if (m_sortFoldersFirst || m_sortRole == SizeRole) {
896 const bool isDirA = a.isDir();
897 const bool isDirB = b.isDir();
898 if (isDirA && !isDirB) {
899 return true;
900 } else if (!isDirA && isDirB) {
901 return false;
902 }
903 }
904
905 switch (m_sortRole) {
906 case NameRole: {
907 result = stringCompare(a.text(), b.text());
908 if (result == 0) {
909 // KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
910 result = stringCompare(a.name(m_caseSensitivity == Qt::CaseInsensitive),
911 b.name(m_caseSensitivity == Qt::CaseInsensitive));
912 }
913 break;
914 }
915
916 case DateRole: {
917 const KDateTime dateTimeA = a.time(KFileItem::ModificationTime);
918 const KDateTime dateTimeB = b.time(KFileItem::ModificationTime);
919 if (dateTimeA < dateTimeB) {
920 result = -1;
921 } else if (dateTimeA > dateTimeB) {
922 result = +1;
923 }
924 break;
925 }
926
927 case SizeRole: {
928 // TODO: Implement sorting folders by the number of items inside.
929 // This is more tricky to get right because this number is retrieved
930 // asynchronously by KFileItemModelRolesUpdater.
931 const KIO::filesize_t sizeA = a.size();
932 const KIO::filesize_t sizeB = b.size();
933 if (sizeA < sizeB) {
934 result = -1;
935 } else if (sizeA > sizeB) {
936 result = +1;
937 }
938 break;
939 }
940
941 default:
942 break;
943 }
944
945 if (result == 0) {
946 // It must be assured that the sort order is always unique even if two values have been
947 // equal. In this case a comparison of the URL is done which is unique in all cases
948 // within KDirLister.
949 result = QString::compare(a.url().url(), b.url().url(), Qt::CaseSensitive);
950 }
951
952 return (sortOrder() == Qt::AscendingOrder) ? result < 0 : result > 0;
953 }
954
955 void KFileItemModel::sort(const KFileItemList::iterator& startIterator, const KFileItemList::iterator& endIterator)
956 {
957 KFileItemList::iterator start = startIterator;
958 KFileItemList::iterator end = endIterator;
959
960 // The implementation is based on qSortHelper() from qalgorithms.h
961 // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
962 // In opposite to qSort() it allows to use a member-function for the comparison of elements.
963 while (1) {
964 int span = int(end - start);
965 if (span < 2) {
966 return;
967 }
968
969 --end;
970 KFileItemList::iterator low = start, high = end - 1;
971 KFileItemList::iterator pivot = start + span / 2;
972
973 if (lessThan(*end, *start)) {
974 qSwap(*end, *start);
975 }
976 if (span == 2) {
977 return;
978 }
979
980 if (lessThan(*pivot, *start)) {
981 qSwap(*pivot, *start);
982 }
983 if (lessThan(*end, *pivot)) {
984 qSwap(*end, *pivot);
985 }
986 if (span == 3) {
987 return;
988 }
989
990 qSwap(*pivot, *end);
991
992 while (low < high) {
993 while (low < high && lessThan(*low, *end)) {
994 ++low;
995 }
996
997 while (high > low && lessThan(*end, *high)) {
998 --high;
999 }
1000 if (low < high) {
1001 qSwap(*low, *high);
1002 ++low;
1003 --high;
1004 } else {
1005 break;
1006 }
1007 }
1008
1009 if (lessThan(*low, *end)) {
1010 ++low;
1011 }
1012
1013 qSwap(*end, *low);
1014 sort(start, low);
1015
1016 start = low + 1;
1017 ++end;
1018 }
1019 }
1020
1021 int KFileItemModel::stringCompare(const QString& a, const QString& b) const
1022 {
1023 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1024 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1025 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1026 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1027
1028 if (m_caseSensitivity == Qt::CaseInsensitive) {
1029 const int result = m_naturalSorting ? KStringHandler::naturalCompare(a, b, Qt::CaseInsensitive)
1030 : QString::compare(a, b, Qt::CaseInsensitive);
1031 if (result != 0) {
1032 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1033 // comparison, still a deterministic sort order is required. A case sensitive
1034 // comparison is done as fallback.
1035 return result;
1036 }
1037 }
1038
1039 return m_naturalSorting ? KStringHandler::naturalCompare(a, b, Qt::CaseSensitive)
1040 : QString::compare(a, b, Qt::CaseSensitive);
1041 }
1042
1043 int KFileItemModel::expansionLevelsCompare(const KFileItem& a, const KFileItem& b) const
1044 {
1045 const KUrl urlA = a.url();
1046 const KUrl urlB = b.url();
1047 if (urlA.directory() == urlB.directory()) {
1048 // Both items have the same directory as parent
1049 return 0;
1050 }
1051
1052 // Check whether one item is the parent of the other item
1053 if (urlA.isParentOf(urlB)) {
1054 return -1;
1055 } else if (urlB.isParentOf(urlA)) {
1056 return +1;
1057 }
1058
1059 // Determine the maximum common path of both items and
1060 // remember the index in 'index'
1061 const QString pathA = urlA.path();
1062 const QString pathB = urlB.path();
1063
1064 const int maxIndex = qMin(pathA.length(), pathB.length()) - 1;
1065 int index = 0;
1066 while (index <= maxIndex && pathA.at(index) == pathB.at(index)) {
1067 ++index;
1068 }
1069 if (index > maxIndex) {
1070 index = maxIndex;
1071 }
1072 while ((pathA.at(index) != QLatin1Char('/') || pathB.at(index) != QLatin1Char('/')) && index > 0) {
1073 --index;
1074 }
1075
1076 // Determine the first sub-path after the common path and
1077 // check whether it represents a directory or already a file
1078 bool isDirA = true;
1079 const QString subPathA = subPath(a, pathA, index, &isDirA);
1080 bool isDirB = true;
1081 const QString subPathB = subPath(b, pathB, index, &isDirB);
1082
1083 if (isDirA && !isDirB) {
1084 return -1;
1085 } else if (!isDirA && isDirB) {
1086 return +1;
1087 }
1088
1089 return stringCompare(subPathA, subPathB);
1090 }
1091
1092 QString KFileItemModel::subPath(const KFileItem& item,
1093 const QString& itemPath,
1094 int start,
1095 bool* isDir) const
1096 {
1097 Q_ASSERT(isDir);
1098 const int pathIndex = itemPath.indexOf('/', start + 1);
1099 *isDir = (pathIndex > 0) || item.isDir();
1100 return itemPath.mid(start, pathIndex - start);
1101 }
1102
1103 bool KFileItemModel::useMaximumUpdateInterval() const
1104 {
1105 const KDirLister* dirLister = m_dirLister.data();
1106 return dirLister && !dirLister->url().isLocalFile();
1107 }
1108
1109 #include "kfileitemmodel.moc"