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