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