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