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