- if (!changedRoles.contains(sortRole())) {
- emit itemsChanged(KItemRangeList() << KItemRange(index, 1), changedRoles);
- return true;
- }
-
- // The sort role has been changed which might result in a changed
- // item index. In this case instead of emitting the itemsChanged()
- // signal the following is done:
- // 1. The item gets removed from the current position and the signal
- // itemsRemoved() will be emitted.
- // 2. The item gets inserted to the new position and the signal
- // itemsInserted() will be emitted.
-
- const KFileItem& changedItem = m_sortedItems.at(index);
- const bool sortOrderDecreased = (index > 0 && lessThan(changedItem, m_sortedItems.at(index - 1)));
- const bool sortOrderIncreased = !sortOrderDecreased &&
- (index < count() - 1 && lessThan(m_sortedItems.at(index + 1), changedItem));
-
- if (!sortOrderDecreased && !sortOrderIncreased) {
- // Although the value of the sort-role has been changed it did not result
- // into a changed position.
- emit itemsChanged(KItemRangeList() << KItemRange(index, 1), changedRoles);
- return true;
- }
-
- m_groups.clear();
-
- if (!m_pendingItemsToInsert.isEmpty()) {
- insertItems(m_pendingItemsToInsert);
- m_pendingItemsToInsert.clear();
- }
-
- // Do a binary search to find the new position where the item
- // should get inserted. The result will be stored in 'mid'.
- int min = sortOrderIncreased ? index + 1 : 0;
- int max = sortOrderDecreased ? index - 1 : count() - 1;
- int mid = 0;
- do {
- mid = (min + max) / 2;
- if (lessThan(m_sortedItems.at(mid), changedItem)) {
- min = mid + 1;
- } else {
- max = mid - 1;
- }
- } while (min <= max);
-
- if (sortOrderIncreased && mid == max && lessThan(m_sortedItems.at(max), changedItem)) {
- ++mid;
- }
-
- // Remove the item from the old position
- const KFileItem removedItem = changedItem;
- const QHash<QByteArray, QVariant> removedData = m_data[index];
-
- m_items.remove(changedItem.url());
- m_sortedItems.removeAt(index);
- m_data.removeAt(index);
- for (int i = 0; i < m_sortedItems.count(); ++i) {
- m_items.insert(m_sortedItems.at(i).url(), i);
- }
-
- emit itemsRemoved(KItemRangeList() << KItemRange(index, 1));
-
- // Insert the item to the new position
- if (sortOrderIncreased) {
- --mid;
- }
-
- m_sortedItems.insert(mid, removedItem);
- m_data.insert(mid, removedData);
- for (int i = 0; i < m_sortedItems.count(); ++i) {
- m_items.insert(m_sortedItems.at(i).url(), i);