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