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