]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kfileitemmodel.cpp
Prepare view-engine for non-KFileItem usecase
[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 path = item.localPath();
1213 }
1214
1215 const int index = path.lastIndexOf(item.text());
1216 path = path.mid(0, index - 1);
1217 data.insert("path", path);
1218 }
1219
1220 if (m_requestRole[IsExpandedRole]) {
1221 data.insert("isExpanded", false);
1222 }
1223
1224 if (m_requestRole[IsExpandableRole]) {
1225 data.insert("isExpandable", item.isDir() && item.url() == item.targetUrl());
1226 }
1227
1228 if (m_requestRole[ExpandedParentsCountRole]) {
1229 if (m_expandedParentsCountRoot == UninitializedExpandedParentsCountRoot) {
1230 const KUrl rootUrl = m_dirLister->url();
1231 const QString protocol = rootUrl.protocol();
1232 const bool forceExpandedParentsCountRoot = (protocol == QLatin1String("trash") ||
1233 protocol == QLatin1String("nepomuk") ||
1234 protocol == QLatin1String("remote") ||
1235 protocol.contains(QLatin1String("search")));
1236 if (forceExpandedParentsCountRoot) {
1237 m_expandedParentsCountRoot = ForceExpandedParentsCountRoot;
1238 } else {
1239 const QString rootDir = rootUrl.path(KUrl::AddTrailingSlash);
1240 m_expandedParentsCountRoot = rootDir.count('/');
1241 }
1242 }
1243
1244 if (m_expandedParentsCountRoot == ForceExpandedParentsCountRoot) {
1245 data.insert("expandedParentsCount", -1);
1246 } else {
1247 const QString dir = item.url().directory(KUrl::AppendTrailingSlash);
1248 const int level = dir.count('/') - m_expandedParentsCountRoot;
1249 data.insert("expandedParentsCount", level);
1250 }
1251 }
1252
1253 if (item.isMimeTypeKnown()) {
1254 data.insert("iconName", item.iconName());
1255
1256 if (m_requestRole[TypeRole]) {
1257 data.insert("type", item.mimeComment());
1258 }
1259 }
1260
1261 return data;
1262 }
1263
1264 bool KFileItemModel::lessThan(const ItemData* a, const ItemData* b) const
1265 {
1266 int result = 0;
1267
1268 if (m_expandedParentsCountRoot >= 0) {
1269 result = expandedParentsCountCompare(a, b);
1270 if (result != 0) {
1271 // The items have parents with different expansion levels
1272 return (sortOrder() == Qt::AscendingOrder) ? result < 0 : result > 0;
1273 }
1274 }
1275
1276 if (m_sortDirsFirst || m_sortRole == SizeRole) {
1277 const bool isDirA = a->item.isDir();
1278 const bool isDirB = b->item.isDir();
1279 if (isDirA && !isDirB) {
1280 return true;
1281 } else if (!isDirA && isDirB) {
1282 return false;
1283 }
1284 }
1285
1286 result = sortRoleCompare(a, b);
1287
1288 return (sortOrder() == Qt::AscendingOrder) ? result < 0 : result > 0;
1289 }
1290
1291 int KFileItemModel::sortRoleCompare(const ItemData* a, const ItemData* b) const
1292 {
1293 const KFileItem& itemA = a->item;
1294 const KFileItem& itemB = b->item;
1295
1296 int result = 0;
1297
1298 switch (m_sortRole) {
1299 case NameRole:
1300 // The name role is handled as default fallback after the switch
1301 break;
1302
1303 case SizeRole: {
1304 if (itemA.isDir()) {
1305 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1306 Q_ASSERT(itemB.isDir());
1307
1308 const QVariant valueA = a->values.value("size");
1309 const QVariant valueB = b->values.value("size");
1310 if (valueA.isNull() && valueB.isNull()) {
1311 result = 0;
1312 } else if (valueA.isNull()) {
1313 result = -1;
1314 } else if (valueB.isNull()) {
1315 result = +1;
1316 } else {
1317 result = valueA.toInt() - valueB.toInt();
1318 }
1319 } else {
1320 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1321 Q_ASSERT(!itemB.isDir());
1322 const KIO::filesize_t sizeA = itemA.size();
1323 const KIO::filesize_t sizeB = itemB.size();
1324 if (sizeA > sizeB) {
1325 result = +1;
1326 } else if (sizeA < sizeB) {
1327 result = -1;
1328 } else {
1329 result = 0;
1330 }
1331 }
1332 break;
1333 }
1334
1335 case DateRole: {
1336 const KDateTime dateTimeA = itemA.time(KFileItem::ModificationTime);
1337 const KDateTime dateTimeB = itemB.time(KFileItem::ModificationTime);
1338 if (dateTimeA < dateTimeB) {
1339 result = -1;
1340 } else if (dateTimeA > dateTimeB) {
1341 result = +1;
1342 }
1343 break;
1344 }
1345
1346 case RatingRole: {
1347 result = a->values.value("rating").toInt() - b->values.value("rating").toInt();
1348 break;
1349 }
1350
1351 case ImageSizeRole: {
1352 // Alway use a natural comparing to interpret the numbers of a string like
1353 // "1600 x 1200" for having a correct sorting.
1354 result = KStringHandler::naturalCompare(a->values.value("imageSize").toString(),
1355 b->values.value("imageSize").toString(),
1356 Qt::CaseSensitive);
1357 break;
1358 }
1359
1360 case PermissionsRole:
1361 case OwnerRole:
1362 case GroupRole:
1363 case TypeRole:
1364 case DestinationRole:
1365 case PathRole:
1366 case CommentRole:
1367 case TagsRole: {
1368 const QByteArray role = roleForType(m_sortRole);
1369 result = QString::compare(a->values.value(role).toString(),
1370 b->values.value(role).toString());
1371 break;
1372 }
1373
1374 default:
1375 break;
1376 }
1377
1378 if (result != 0) {
1379 // The current sort role was sufficient to define an order
1380 return result;
1381 }
1382
1383 // Fallback #1: Compare the text of the items
1384 result = stringCompare(itemA.text(), itemB.text());
1385 if (result != 0) {
1386 return result;
1387 }
1388
1389 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1390 result = stringCompare(itemA.name(m_caseSensitivity == Qt::CaseInsensitive),
1391 itemB.name(m_caseSensitivity == Qt::CaseInsensitive));
1392 if (result != 0) {
1393 return result;
1394 }
1395
1396 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1397 // equal. In this case a comparison of the URL is done which is unique in all cases
1398 // within KDirLister.
1399 return QString::compare(itemA.url().url(), itemB.url().url(), Qt::CaseSensitive);
1400 }
1401
1402 int KFileItemModel::stringCompare(const QString& a, const QString& b) const
1403 {
1404 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1405 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1406 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1407 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1408
1409 if (m_caseSensitivity == Qt::CaseInsensitive) {
1410 const int result = m_naturalSorting ? KStringHandler::naturalCompare(a, b, Qt::CaseInsensitive)
1411 : QString::compare(a, b, Qt::CaseInsensitive);
1412 if (result != 0) {
1413 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1414 // comparison, still a deterministic sort order is required. A case sensitive
1415 // comparison is done as fallback.
1416 return result;
1417 }
1418 }
1419
1420 return m_naturalSorting ? KStringHandler::naturalCompare(a, b, Qt::CaseSensitive)
1421 : QString::compare(a, b, Qt::CaseSensitive);
1422 }
1423
1424 int KFileItemModel::expandedParentsCountCompare(const ItemData* a, const ItemData* b) const
1425 {
1426 const KUrl urlA = a->item.url();
1427 const KUrl urlB = b->item.url();
1428 if (urlA.directory() == urlB.directory()) {
1429 // Both items have the same directory as parent
1430 return 0;
1431 }
1432
1433 // Check whether one item is the parent of the other item
1434 if (urlA.isParentOf(urlB)) {
1435 return (sortOrder() == Qt::AscendingOrder) ? -1 : +1;
1436 } else if (urlB.isParentOf(urlA)) {
1437 return (sortOrder() == Qt::AscendingOrder) ? +1 : -1;
1438 }
1439
1440 // Determine the maximum common path of both items and
1441 // remember the index in 'index'
1442 const QString pathA = urlA.path();
1443 const QString pathB = urlB.path();
1444
1445 const int maxIndex = qMin(pathA.length(), pathB.length()) - 1;
1446 int index = 0;
1447 while (index <= maxIndex && pathA.at(index) == pathB.at(index)) {
1448 ++index;
1449 }
1450 if (index > maxIndex) {
1451 index = maxIndex;
1452 }
1453 while ((pathA.at(index) != QLatin1Char('/') || pathB.at(index) != QLatin1Char('/')) && index > 0) {
1454 --index;
1455 }
1456
1457 // Determine the first sub-path after the common path and
1458 // check whether it represents a directory or already a file
1459 bool isDirA = true;
1460 const QString subPathA = subPath(a->item, pathA, index, &isDirA);
1461 bool isDirB = true;
1462 const QString subPathB = subPath(b->item, pathB, index, &isDirB);
1463
1464 if (m_sortDirsFirst || m_sortRole == SizeRole) {
1465 if (isDirA && !isDirB) {
1466 return (sortOrder() == Qt::AscendingOrder) ? -1 : +1;
1467 } else if (!isDirA && isDirB) {
1468 return (sortOrder() == Qt::AscendingOrder) ? +1 : -1;
1469 }
1470 }
1471
1472 // Compare the items of the parents that represent the first
1473 // different path after the common path.
1474 const QString parentPathA = pathA.left(index) + subPathA;
1475 const QString parentPathB = pathB.left(index) + subPathB;
1476
1477 const ItemData* parentA = a;
1478 while (parentA && parentA->item.url().path() != parentPathA) {
1479 parentA = parentA->parent;
1480 }
1481
1482 const ItemData* parentB = b;
1483 while (parentB && parentB->item.url().path() != parentPathB) {
1484 parentB = parentB->parent;
1485 }
1486
1487 if (parentA && parentB) {
1488 return sortRoleCompare(parentA, parentB);
1489 }
1490
1491 kWarning() << "Child items without parent detected:" << a->item.url() << b->item.url();
1492 return QString::compare(urlA.url(), urlB.url(), Qt::CaseSensitive);
1493 }
1494
1495 QString KFileItemModel::subPath(const KFileItem& item,
1496 const QString& itemPath,
1497 int start,
1498 bool* isDir) const
1499 {
1500 Q_ASSERT(isDir);
1501 const int pathIndex = itemPath.indexOf('/', start + 1);
1502 *isDir = (pathIndex > 0) || item.isDir();
1503 return itemPath.mid(start, pathIndex - start);
1504 }
1505
1506 bool KFileItemModel::useMaximumUpdateInterval() const
1507 {
1508 return !m_dirLister->url().isLocalFile();
1509 }
1510
1511 QList<QPair<int, QVariant> > KFileItemModel::nameRoleGroups() const
1512 {
1513 Q_ASSERT(!m_itemData.isEmpty());
1514
1515 const int maxIndex = count() - 1;
1516 QList<QPair<int, QVariant> > groups;
1517
1518 QString groupValue;
1519 QChar firstChar;
1520 bool isLetter = false;
1521 for (int i = 0; i <= maxIndex; ++i) {
1522 if (isChildItem(i)) {
1523 continue;
1524 }
1525
1526 const QString name = m_itemData.at(i)->values.value("text").toString();
1527
1528 // Use the first character of the name as group indication
1529 QChar newFirstChar = name.at(0).toUpper();
1530 if (newFirstChar == QLatin1Char('~') && name.length() > 1) {
1531 newFirstChar = name.at(1).toUpper();
1532 }
1533
1534 if (firstChar != newFirstChar) {
1535 QString newGroupValue;
1536 if (newFirstChar >= QLatin1Char('A') && newFirstChar <= QLatin1Char('Z')) {
1537 // Apply group 'A' - 'Z'
1538 newGroupValue = newFirstChar;
1539 isLetter = true;
1540 } else if (newFirstChar >= QLatin1Char('0') && newFirstChar <= QLatin1Char('9')) {
1541 // Apply group '0 - 9' for any name that starts with a digit
1542 newGroupValue = i18nc("@title:group Groups that start with a digit", "0 - 9");
1543 isLetter = false;
1544 } else {
1545 if (isLetter) {
1546 // If the current group is 'A' - 'Z' check whether a locale character
1547 // fits into the existing group.
1548 // TODO: This does not work in the case if e.g. the group 'O' starts with
1549 // an umlaut 'O' -> provide unit-test to document this known issue
1550 const QChar prevChar(firstChar.unicode() - ushort(1));
1551 const QChar nextChar(firstChar.unicode() + ushort(1));
1552 const QString currChar(newFirstChar);
1553 const bool partOfCurrentGroup = currChar.localeAwareCompare(prevChar) > 0 &&
1554 currChar.localeAwareCompare(nextChar) < 0;
1555 if (partOfCurrentGroup) {
1556 continue;
1557 }
1558 }
1559 newGroupValue = i18nc("@title:group", "Others");
1560 isLetter = false;
1561 }
1562
1563 if (newGroupValue != groupValue) {
1564 groupValue = newGroupValue;
1565 groups.append(QPair<int, QVariant>(i, newGroupValue));
1566 }
1567
1568 firstChar = newFirstChar;
1569 }
1570 }
1571 return groups;
1572 }
1573
1574 QList<QPair<int, QVariant> > KFileItemModel::sizeRoleGroups() const
1575 {
1576 Q_ASSERT(!m_itemData.isEmpty());
1577
1578 const int maxIndex = count() - 1;
1579 QList<QPair<int, QVariant> > groups;
1580
1581 QString groupValue;
1582 for (int i = 0; i <= maxIndex; ++i) {
1583 if (isChildItem(i)) {
1584 continue;
1585 }
1586
1587 const KFileItem& item = m_itemData.at(i)->item;
1588 const KIO::filesize_t fileSize = !item.isNull() ? item.size() : ~0U;
1589 QString newGroupValue;
1590 if (!item.isNull() && item.isDir()) {
1591 newGroupValue = i18nc("@title:group Size", "Folders");
1592 } else if (fileSize < 5 * 1024 * 1024) {
1593 newGroupValue = i18nc("@title:group Size", "Small");
1594 } else if (fileSize < 10 * 1024 * 1024) {
1595 newGroupValue = i18nc("@title:group Size", "Medium");
1596 } else {
1597 newGroupValue = i18nc("@title:group Size", "Big");
1598 }
1599
1600 if (newGroupValue != groupValue) {
1601 groupValue = newGroupValue;
1602 groups.append(QPair<int, QVariant>(i, newGroupValue));
1603 }
1604 }
1605
1606 return groups;
1607 }
1608
1609 QList<QPair<int, QVariant> > KFileItemModel::dateRoleGroups() const
1610 {
1611 Q_ASSERT(!m_itemData.isEmpty());
1612
1613 const int maxIndex = count() - 1;
1614 QList<QPair<int, QVariant> > groups;
1615
1616 const QDate currentDate = KDateTime::currentLocalDateTime().date();
1617
1618 int yearForCurrentWeek = 0;
1619 int currentWeek = currentDate.weekNumber(&yearForCurrentWeek);
1620 if (yearForCurrentWeek == currentDate.year() + 1) {
1621 currentWeek = 53;
1622 }
1623
1624 QDate previousModifiedDate;
1625 QString groupValue;
1626 for (int i = 0; i <= maxIndex; ++i) {
1627 if (isChildItem(i)) {
1628 continue;
1629 }
1630
1631 const KDateTime modifiedTime = m_itemData.at(i)->item.time(KFileItem::ModificationTime);
1632 const QDate modifiedDate = modifiedTime.date();
1633 if (modifiedDate == previousModifiedDate) {
1634 // The current item is in the same group as the previous item
1635 continue;
1636 }
1637 previousModifiedDate = modifiedDate;
1638
1639 const int daysDistance = modifiedDate.daysTo(currentDate);
1640
1641 int yearForModifiedWeek = 0;
1642 int modifiedWeek = modifiedDate.weekNumber(&yearForModifiedWeek);
1643 if (yearForModifiedWeek == modifiedDate.year() + 1) {
1644 modifiedWeek = 53;
1645 }
1646
1647 QString newGroupValue;
1648 if (currentDate.year() == modifiedDate.year() && currentDate.month() == modifiedDate.month()) {
1649 if (modifiedWeek > currentWeek) {
1650 // Usecase: modified date = 2010-01-01, current date = 2010-01-22
1651 // modified week = 53, current week = 3
1652 modifiedWeek = 0;
1653 }
1654 switch (currentWeek - modifiedWeek) {
1655 case 0:
1656 switch (daysDistance) {
1657 case 0: newGroupValue = i18nc("@title:group Date", "Today"); break;
1658 case 1: newGroupValue = i18nc("@title:group Date", "Yesterday"); break;
1659 default: newGroupValue = modifiedTime.toString(i18nc("@title:group The week day name: %A", "%A"));
1660 }
1661 break;
1662 case 1:
1663 newGroupValue = i18nc("@title:group Date", "Last Week");
1664 break;
1665 case 2:
1666 newGroupValue = i18nc("@title:group Date", "Two Weeks Ago");
1667 break;
1668 case 3:
1669 newGroupValue = i18nc("@title:group Date", "Three Weeks Ago");
1670 break;
1671 case 4:
1672 case 5:
1673 newGroupValue = i18nc("@title:group Date", "Earlier this Month");
1674 break;
1675 default:
1676 Q_ASSERT(false);
1677 }
1678 } else {
1679 const QDate lastMonthDate = currentDate.addMonths(-1);
1680 if (lastMonthDate.year() == modifiedDate.year() && lastMonthDate.month() == modifiedDate.month()) {
1681 if (daysDistance == 1) {
1682 newGroupValue = modifiedTime.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Yesterday (%B, %Y)"));
1683 } else if (daysDistance <= 7) {
1684 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)"));
1685 } else if (daysDistance <= 7 * 2) {
1686 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)"));
1687 } else if (daysDistance <= 7 * 3) {
1688 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)"));
1689 } else if (daysDistance <= 7 * 4) {
1690 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)"));
1691 } else {
1692 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"));
1693 }
1694 } else {
1695 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"));
1696 }
1697 }
1698
1699 if (newGroupValue != groupValue) {
1700 groupValue = newGroupValue;
1701 groups.append(QPair<int, QVariant>(i, newGroupValue));
1702 }
1703 }
1704
1705 return groups;
1706 }
1707
1708 QList<QPair<int, QVariant> > KFileItemModel::permissionRoleGroups() const
1709 {
1710 Q_ASSERT(!m_itemData.isEmpty());
1711
1712 const int maxIndex = count() - 1;
1713 QList<QPair<int, QVariant> > groups;
1714
1715 QString permissionsString;
1716 QString groupValue;
1717 for (int i = 0; i <= maxIndex; ++i) {
1718 if (isChildItem(i)) {
1719 continue;
1720 }
1721
1722 const ItemData* itemData = m_itemData.at(i);
1723 const QString newPermissionsString = itemData->values.value("permissions").toString();
1724 if (newPermissionsString == permissionsString) {
1725 continue;
1726 }
1727 permissionsString = newPermissionsString;
1728
1729 const QFileInfo info(itemData->item.url().pathOrUrl());
1730
1731 // Set user string
1732 QString user;
1733 if (info.permission(QFile::ReadUser)) {
1734 user = i18nc("@item:intext Access permission, concatenated", "Read, ");
1735 }
1736 if (info.permission(QFile::WriteUser)) {
1737 user += i18nc("@item:intext Access permission, concatenated", "Write, ");
1738 }
1739 if (info.permission(QFile::ExeUser)) {
1740 user += i18nc("@item:intext Access permission, concatenated", "Execute, ");
1741 }
1742 user = user.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user.mid(0, user.count() - 2);
1743
1744 // Set group string
1745 QString group;
1746 if (info.permission(QFile::ReadGroup)) {
1747 group = i18nc("@item:intext Access permission, concatenated", "Read, ");
1748 }
1749 if (info.permission(QFile::WriteGroup)) {
1750 group += i18nc("@item:intext Access permission, concatenated", "Write, ");
1751 }
1752 if (info.permission(QFile::ExeGroup)) {
1753 group += i18nc("@item:intext Access permission, concatenated", "Execute, ");
1754 }
1755 group = group.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group.mid(0, group.count() - 2);
1756
1757 // Set others string
1758 QString others;
1759 if (info.permission(QFile::ReadOther)) {
1760 others = i18nc("@item:intext Access permission, concatenated", "Read, ");
1761 }
1762 if (info.permission(QFile::WriteOther)) {
1763 others += i18nc("@item:intext Access permission, concatenated", "Write, ");
1764 }
1765 if (info.permission(QFile::ExeOther)) {
1766 others += i18nc("@item:intext Access permission, concatenated", "Execute, ");
1767 }
1768 others = others.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others.mid(0, others.count() - 2);
1769
1770 const QString newGroupValue = i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user, group, others);
1771 if (newGroupValue != groupValue) {
1772 groupValue = newGroupValue;
1773 groups.append(QPair<int, QVariant>(i, newGroupValue));
1774 }
1775 }
1776
1777 return groups;
1778 }
1779
1780 QList<QPair<int, QVariant> > KFileItemModel::ratingRoleGroups() const
1781 {
1782 Q_ASSERT(!m_itemData.isEmpty());
1783
1784 const int maxIndex = count() - 1;
1785 QList<QPair<int, QVariant> > groups;
1786
1787 int groupValue = -1;
1788 for (int i = 0; i <= maxIndex; ++i) {
1789 if (isChildItem(i)) {
1790 continue;
1791 }
1792 const int newGroupValue = m_itemData.at(i)->values.value("rating", 0).toInt();
1793 if (newGroupValue != groupValue) {
1794 groupValue = newGroupValue;
1795 groups.append(QPair<int, QVariant>(i, newGroupValue));
1796 }
1797 }
1798
1799 return groups;
1800 }
1801
1802 QList<QPair<int, QVariant> > KFileItemModel::genericStringRoleGroups(const QByteArray& role) const
1803 {
1804 Q_ASSERT(!m_itemData.isEmpty());
1805
1806 const int maxIndex = count() - 1;
1807 QList<QPair<int, QVariant> > groups;
1808
1809 bool isFirstGroupValue = true;
1810 QString groupValue;
1811 for (int i = 0; i <= maxIndex; ++i) {
1812 if (isChildItem(i)) {
1813 continue;
1814 }
1815 const QString newGroupValue = m_itemData.at(i)->values.value(role).toString();
1816 if (newGroupValue != groupValue || isFirstGroupValue) {
1817 groupValue = newGroupValue;
1818 groups.append(QPair<int, QVariant>(i, newGroupValue));
1819 isFirstGroupValue = false;
1820 }
1821 }
1822
1823 return groups;
1824 }
1825
1826 KFileItemList KFileItemModel::childItems(const KFileItem& item) const
1827 {
1828 KFileItemList items;
1829
1830 int index = m_items.value(item.url(), -1);
1831 if (index >= 0) {
1832 const int parentLevel = m_itemData.at(index)->values.value("expandedParentsCount").toInt();
1833 ++index;
1834 while (index < m_itemData.count() && m_itemData.at(index)->values.value("expandedParentsCount").toInt() > parentLevel) {
1835 items.append(m_itemData.at(index)->item);
1836 ++index;
1837 }
1838 }
1839
1840 return items;
1841 }
1842
1843 void KFileItemModel::emitSortProgress(int resolvedCount)
1844 {
1845 // Be tolerant against a resolvedCount with a wrong range.
1846 // Although there should not be a case where KFileItemModelRolesUpdater
1847 // (= caller) provides a wrong range, it is important to emit
1848 // a useful progress information even if there is an unexpected
1849 // implementation issue.
1850
1851 const int itemCount = count();
1852 if (resolvedCount >= itemCount) {
1853 m_sortingProgressPercent = -1;
1854 if (m_resortAllItemsTimer->isActive()) {
1855 m_resortAllItemsTimer->stop();
1856 resortAllItems();
1857 }
1858
1859 emit directorySortingProgress(100);
1860 } else if (itemCount > 0) {
1861 resolvedCount = qBound(0, resolvedCount, itemCount);
1862
1863 const int progress = resolvedCount * 100 / itemCount;
1864 if (m_sortingProgressPercent != progress) {
1865 m_sortingProgressPercent = progress;
1866 emit directorySortingProgress(progress);
1867 }
1868 }
1869 }
1870
1871 const KFileItemModel::RoleInfoMap* KFileItemModel::rolesInfoMap(int& count)
1872 {
1873 static const RoleInfoMap rolesInfoMap[] = {
1874 // | role | roleType | role translation | group translation | requires Nepomuk | requires indexer
1875 { 0, NoRole, 0, 0, 0, 0, false, false },
1876 { "text", NameRole, I18N_NOOP2_NOSTRIP("@label", "Name"), 0, 0, false, false },
1877 { "size", SizeRole, I18N_NOOP2_NOSTRIP("@label", "Size"), 0, 0, false, false },
1878 { "date", DateRole, I18N_NOOP2_NOSTRIP("@label", "Date"), 0, 0, false, false },
1879 { "type", TypeRole, I18N_NOOP2_NOSTRIP("@label", "Type"), 0, 0, false, false },
1880 { "rating", RatingRole, I18N_NOOP2_NOSTRIP("@label", "Rating"), 0, 0, true, false },
1881 { "tags", TagsRole, I18N_NOOP2_NOSTRIP("@label", "Tags"), 0, 0, true, false },
1882 { "comment", CommentRole, I18N_NOOP2_NOSTRIP("@label", "Comment"), 0, 0, true, false },
1883 { "wordCount", WordCountRole, I18N_NOOP2_NOSTRIP("@label", "Word Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
1884 { "lineCount", LineCountRole, I18N_NOOP2_NOSTRIP("@label", "Line Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
1885 { "imageSize", ImageSizeRole, I18N_NOOP2_NOSTRIP("@label", "Image Size"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
1886 { "orientation", OrientationRole, I18N_NOOP2_NOSTRIP("@label", "Orientation"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
1887 { "artist", ArtistRole, I18N_NOOP2_NOSTRIP("@label", "Artist"), I18N_NOOP2_NOSTRIP("@label", "Music"), true, true },
1888 { "album", AlbumRole, I18N_NOOP2_NOSTRIP("@label", "Album"), I18N_NOOP2_NOSTRIP("@label", "Music"), true, true },
1889 { "duration", DurationRole, I18N_NOOP2_NOSTRIP("@label", "Duration"), I18N_NOOP2_NOSTRIP("@label", "Music"), true, true },
1890 { "track", TrackRole, I18N_NOOP2_NOSTRIP("@label", "Track"), I18N_NOOP2_NOSTRIP("@label", "Music"), true, true },
1891 { "path", PathRole, I18N_NOOP2_NOSTRIP("@label", "Path"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1892 { "destination", DestinationRole, I18N_NOOP2_NOSTRIP("@label", "Link Destination"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1893 { "copiedFrom", CopiedFromRole, I18N_NOOP2_NOSTRIP("@label", "Copied From"), I18N_NOOP2_NOSTRIP("@label", "Other"), true, false },
1894 { "permissions", PermissionsRole, I18N_NOOP2_NOSTRIP("@label", "Permissions"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1895 { "owner", OwnerRole, I18N_NOOP2_NOSTRIP("@label", "Owner"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1896 { "group", GroupRole, I18N_NOOP2_NOSTRIP("@label", "User Group"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1897 };
1898
1899 count = sizeof(rolesInfoMap) / sizeof(RoleInfoMap);
1900 return rolesInfoMap;
1901 }
1902
1903 void KFileItemModel::determineMimeTypes(const KFileItemList& items, int timeout)
1904 {
1905 QElapsedTimer timer;
1906 timer.start();
1907 foreach (KFileItem item, items) {
1908 item.determineMimeType();
1909 if (timer.elapsed() > timeout) {
1910 // Don't block the user interface, let the remaining items
1911 // be resolved asynchronously.
1912 return;
1913 }
1914 }
1915 }
1916
1917 #include "kfileitemmodel.moc"