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