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