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