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