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