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