]> cloud.milkyroute.net Git - dolphin.git/blobdiff - src/klistview.cpp
If no user icon present, show a generic one
[dolphin.git] / src / klistview.cpp
index 1cba47b1bd44c2c8e785beaa0f5b03bf359a3d4f..4db18e1f478d2e96de8f8118f818924d942708e7 100644 (file)
@@ -21,7 +21,8 @@
 #include "klistview.h"
 #include "klistview_p.h"
 
-#include <math.h> // trunc
+#include <math.h> // trunc on C99 compliant systems
+#include <kdefakes.h> // trunc for not C99 compliant systems
 
 #include <QApplication>
 #include <QPainter>
@@ -78,6 +79,8 @@ KListView::Private::Private(KListView *listView)
     : listView(listView)
     , itemCategorizer(0)
     , mouseButtonPressed(false)
+    , isDragging(false)
+    , dragLeftViewport(false)
     , proxyModel(0)
     , lastIndex(QModelIndex())
 {
@@ -117,7 +120,6 @@ const QModelIndexList &KListView::Private::intersectionSet(const QRect &rect)
         }
     }
 
-    int j = 0;
     for (int i = middle; i < proxyModel->rowCount(); i++)
     {
         index = elementDictionary[proxyModel->index(i, 0)];
@@ -128,10 +130,9 @@ const QModelIndexList &KListView::Private::intersectionSet(const QRect &rect)
 
         // If we passed next item, stop searching for hits
         if (qMax(rect.bottomRight().y(), rect.topLeft().y()) <
-                                                  indexVisualRect.topLeft().y())
+                                                  qMin(indexVisualRect.topLeft().y(),
+                                                       indexVisualRect.bottomRight().y()))
             break;
-
-        j++;
     }
 
     return intersectedIndexes;
@@ -145,7 +146,7 @@ QRect KListView::Private::visualRectInViewport(const QModelIndex &index) const
     QString curCategory = elementsInfo[index].category;
 
     QRect retRect(listView->spacing(), listView->spacing() * 2 +
-                       30 /* categoryHeight */, 0, 0);
+                  itemCategorizer->categoryHeight(listView->viewOptions()), 0, 0);
 
     int viewportWidth = listView->viewport()->width() - listView->spacing();
 
@@ -168,23 +169,21 @@ QRect KListView::Private::visualRectInViewport(const QModelIndex &index) const
     retRect.setLeft(retRect.left() + column * listView->spacing() +
                     column * itemWidth);
 
-    float rows;
-    int rowsInt;
     foreach (const QString &category, categories)
     {
         if (category == curCategory)
             break;
 
-        rows = (float) ((float) categoriesIndexes[category].count() /
-                        (float) elementsPerRow);
-        rowsInt = categoriesIndexes[category].count() / elementsPerRow;
+        float rows = (float) ((float) categoriesIndexes[category].count() /
+                              (float) elementsPerRow);
+        int rowsInt = categoriesIndexes[category].count() / elementsPerRow;
 
         if (rows - trunc(rows)) rowsInt++;
 
         retRect.setTop(retRect.top() +
                        (rowsInt * listView->spacing()) +
                        (rowsInt * itemHeight) +
-                       30 /* categoryHeight */ +
+                       itemCategorizer->categoryHeight(listView->viewOptions()) +
                        listView->spacing() * 2);
     }
 
@@ -225,27 +224,25 @@ QRect KListView::Private::visualCategoryRectInViewport(const QString &category)
     if (!elementsPerRow)
         elementsPerRow++;
 
-    float rows;
-    int rowsInt;
     foreach (const QString &itCategory, categories)
     {
         if (itCategory == category)
             break;
 
-        rows = (float) ((float) categoriesIndexes[itCategory].count() /
-                        (float) elementsPerRow);
-        rowsInt = categoriesIndexes[itCategory].count() / elementsPerRow;
+        float rows = (float) ((float) categoriesIndexes[itCategory].count() /
+                              (float) elementsPerRow);
+        int rowsInt = categoriesIndexes[itCategory].count() / elementsPerRow;
 
         if (rows - trunc(rows)) rowsInt++;
 
         retRect.setTop(retRect.top() +
                        (rowsInt * listView->spacing()) +
                        (rowsInt * itemHeight) +
-                       30 /* categoryHeight */ +
+                       itemCategorizer->categoryHeight(listView->viewOptions()) +
                        listView->spacing() * 2);
     }
 
-    retRect.setHeight(30 /* categoryHeight */);
+    retRect.setHeight(itemCategorizer->categoryHeight(listView->viewOptions()));
 
     return retRect;
 }
@@ -314,78 +311,76 @@ QRect KListView::Private::categoryVisualRect(const QString &category)
     return retRect;
 }
 
-void KListView::Private::drawNewCategory(const QString &category,
+void KListView::Private::drawNewCategory(const QModelIndex &index,
+                                         int sortRole,
                                          const QStyleOption &option,
                                          QPainter *painter)
 {
-    QColor color = option.palette.color(QPalette::Text);
+    QStyleOption optionCopy = option;
+    const QString category = itemCategorizer->categoryForItem(index, sortRole);
 
-    painter->save();
-    painter->setRenderHint(QPainter::Antialiasing);
+    if ((category == hoveredCategory) && !mouseButtonPressed)
+    {
+        optionCopy.state |= QStyle::State_MouseOver;
+    }
 
-    QStyleOptionButton opt;
+    itemCategorizer->drawCategory(index,
+                                  sortRole,
+                                  optionCopy,
+                                  painter);
+}
 
-    opt.rect = option.rect;
-    opt.palette = option.palette;
-    opt.direction = option.direction;
-    opt.text = category;
 
-    if (option.rect.contains(listView->viewport()->mapFromGlobal(QCursor::pos())) &&
-        !mouseButtonPressed)
-    {
-        const QPalette::ColorGroup group =
-                                          option.state & QStyle::State_Enabled ?
-                                          QPalette::Normal : QPalette::Disabled;
+void KListView::Private::updateScrollbars()
+{
+    int lastItemBottom = cachedRectIndex(lastIndex).bottom() +
+                           listView->spacing() - listView->viewport()->height();
 
-        QLinearGradient gradient(option.rect.topLeft(),
-                                 option.rect.bottomRight());
-        gradient.setColorAt(0,
-                            option.palette.color(group,
-                                                 QPalette::Highlight).light());
-        gradient.setColorAt(1, Qt::transparent);
+    listView->verticalScrollBar()->setSingleStep(listView->viewport()->height() / 10);
+    listView->verticalScrollBar()->setPageStep(listView->viewport()->height());
+    listView->verticalScrollBar()->setRange(0, lastItemBottom);
+}
 
-        painter->fillRect(option.rect, gradient);
-    }
+void KListView::Private::drawDraggedItems(QPainter *painter)
+{
+    QStyleOptionViewItemV3 option = listView->viewOptions();
+    option.state &= ~QStyle::State_MouseOver;
+    foreach (const QModelIndex &index, listView->selectionModel()->selectedIndexes())
+    {
+        const int dx = mousePosition.x() - initialPressPosition.x() + listView->horizontalOffset();
+        const int dy = mousePosition.y() - initialPressPosition.y() + listView->verticalOffset();
 
-    /*if (const KStyle *style = dynamic_cast<const KStyle*>(QApplication::style()))
+        option.rect = visualRect(index);
+        option.rect.adjust(dx, dy, dx, dy);
+
+        if (option.rect.intersects(listView->viewport()->rect()))
         {
-        style->drawControl(KStyle::CE_Category, &opt, painter, this);
+            listView->itemDelegate(index)->paint(painter, option, index);
         }
-    else
-    {*/
-        QFont painterFont = painter->font();
-        painterFont.setWeight(QFont::Bold);
-        QFontMetrics metrics(painterFont);
-        painter->setFont(painterFont);
-
-        QPainterPath path;
-        path.addRect(option.rect.left(),
-                     option.rect.bottom() - 2,
-                     option.rect.width(),
-                     2);
-
-        QLinearGradient gradient(option.rect.topLeft(),
-                                 option.rect.bottomRight());
-        gradient.setColorAt(0, color);
-        gradient.setColorAt(1, Qt::transparent);
+    }
+}
 
-        painter->setBrush(gradient);
-        painter->fillPath(path, gradient);
+void KListView::Private::drawDraggedItems()
+{
+    QRect rectToUpdate;
+    QRect currentRect;
+    foreach (const QModelIndex &index, listView->selectionModel()->selectedIndexes())
+    {
+        int dx = mousePosition.x() - initialPressPosition.x() + listView->horizontalOffset();
+        int dy = mousePosition.y() - initialPressPosition.y() + listView->verticalOffset();
 
-        painter->setPen(color);
+        currentRect = visualRect(index);
+        currentRect.adjust(dx, dy, dx, dy);
 
-        painter->drawText(option.rect, Qt::AlignVCenter | Qt::AlignLeft,
-             metrics.elidedText(category, Qt::ElideRight, option.rect.width()));
-    //}
-    painter->restore();
-}
+        if (currentRect.intersects(listView->viewport()->rect()))
+        {
+            rectToUpdate = rectToUpdate.united(currentRect);
+        }
+    }
 
+    listView->viewport()->update(lastDraggedItemsRect.united(rectToUpdate));
 
-void KListView::Private::updateScrollbars()
-{
-    int lastItemBottom = cachedRectIndex(lastIndex).bottom() +
-                           listView->spacing() - listView->viewport()->height();
-    listView->verticalScrollBar()->setRange(0, lastItemBottom);
+    lastDraggedItemsRect = rectToUpdate;
 }
 
 
@@ -405,6 +400,21 @@ KListView::~KListView()
 
 void KListView::setModel(QAbstractItemModel *model)
 {
+    d->lastSelection = QItemSelection();
+    d->currentViewIndex = QModelIndex();
+    d->forcedSelectionPosition = 0;
+    d->elementsInfo.clear();
+    d->elementsPosition.clear();
+    d->elementDictionary.clear();
+    d->invertedElementDictionary.clear();
+    d->categoriesIndexes.clear();
+    d->categoriesPosition.clear();
+    d->categories.clear();
+    d->intersectedIndexes.clear();
+    d->sourceModelIndexList.clear();
+    d->hovered = QModelIndex();
+    d->mouseButtonPressed = false;
+
     if (d->proxyModel)
     {
         QObject::disconnect(d->proxyModel,
@@ -434,7 +444,7 @@ void KListView::setModel(QAbstractItemModel *model)
 
 QRect KListView::visualRect(const QModelIndex &index) const
 {
-    if ((viewMode() == KListView::ListMode) || !d->proxyModel ||
+    if ((viewMode() != KListView::IconMode) || !d->proxyModel ||
         !d->itemCategorizer)
     {
         return QListView::visualRect(index);
@@ -455,6 +465,21 @@ KItemCategorizer *KListView::itemCategorizer() const
 
 void KListView::setItemCategorizer(KItemCategorizer *itemCategorizer)
 {
+    d->lastSelection = QItemSelection();
+    d->currentViewIndex = QModelIndex();
+    d->forcedSelectionPosition = 0;
+    d->elementsInfo.clear();
+    d->elementsPosition.clear();
+    d->elementDictionary.clear();
+    d->invertedElementDictionary.clear();
+    d->categoriesIndexes.clear();
+    d->categoriesPosition.clear();
+    d->categories.clear();
+    d->intersectedIndexes.clear();
+    d->sourceModelIndexList.clear();
+    d->hovered = QModelIndex();
+    d->mouseButtonPressed = false;
+
     if (!itemCategorizer && d->proxyModel)
     {
         QObject::disconnect(d->proxyModel,
@@ -482,11 +507,15 @@ void KListView::setItemCategorizer(KItemCategorizer *itemCategorizer)
     {
         rowsInserted(QModelIndex(), 0, d->proxyModel->rowCount() - 1);
     }
+    else
+    {
+        updateGeometries();
+    }
 }
 
 QModelIndex KListView::indexAt(const QPoint &point) const
 {
-    if ((viewMode() == KListView::ListMode) || !d->proxyModel ||
+    if ((viewMode() != KListView::IconMode) || !d->proxyModel ||
         !d->itemCategorizer)
     {
         return QListView::indexAt(point);
@@ -510,15 +539,13 @@ void KListView::reset()
 {
     QListView::reset();
 
-    if ((viewMode() == KListView::ListMode) || !d->proxyModel ||
-        !d->itemCategorizer)
-    {
-        return;
-    }
-
+    d->lastSelection = QItemSelection();
+    d->currentViewIndex = QModelIndex();
+    d->forcedSelectionPosition = 0;
     d->elementsInfo.clear();
     d->elementsPosition.clear();
     d->elementDictionary.clear();
+    d->invertedElementDictionary.clear();
     d->categoriesIndexes.clear();
     d->categoriesPosition.clear();
     d->categories.clear();
@@ -530,7 +557,7 @@ void KListView::reset()
 
 void KListView::paintEvent(QPaintEvent *event)
 {
-    if ((viewMode() == KListView::ListMode) || !d->proxyModel ||
+    if ((viewMode() != KListView::IconMode) || !d->proxyModel ||
         !d->itemCategorizer)
     {
         QListView::paintEvent(event);
@@ -589,19 +616,22 @@ void KListView::paintEvent(QPaintEvent *event)
     }
 
     // Redraw categories
+    int i = 0;
     QStyleOptionViewItem otherOption;
     foreach (const QString &category, d->categories)
     {
         otherOption = option;
         otherOption.rect = d->categoryVisualRect(category);
+        otherOption.state &= ~QStyle::State_MouseOver;
 
         if (otherOption.rect.intersects(area))
         {
-            d->drawNewCategory(category, otherOption, &painter);
+            d->drawNewCategory(d->categoriesIndexes[category][0],
+                               d->proxyModel->sortRole(), otherOption, &painter);
         }
     }
 
-    if (d->mouseButtonPressed)
+    if (d->mouseButtonPressed && !d->isDragging)
     {
         QPoint start, end, initialPressPosition;
 
@@ -632,6 +662,12 @@ void KListView::paintEvent(QPaintEvent *event)
         painter.restore();
     }
 
+    if (d->isDragging && !d->dragLeftViewport)
+    {
+        painter.setOpacity(0.5);
+        d->drawDraggedItems(&painter);
+    }
+
     painter.restore();
 }
 
@@ -639,94 +675,156 @@ void KListView::resizeEvent(QResizeEvent *event)
 {
     QListView::resizeEvent(event);
 
-    if ((viewMode() == KListView::ListMode) || !d->proxyModel ||
+    // Clear the items positions cache
+    d->elementsPosition.clear();
+    d->categoriesPosition.clear();
+    d->forcedSelectionPosition = 0;
+
+    if ((viewMode() != KListView::IconMode) || !d->proxyModel ||
         !d->itemCategorizer)
     {
         return;
     }
 
-    // Clear the items positions cache
-    d->elementsPosition.clear();
-    d->categoriesPosition.clear();
-
     d->updateScrollbars();
 }
 
 void KListView::setSelection(const QRect &rect,
                              QItemSelectionModel::SelectionFlags flags)
 {
-    if ((viewMode() == KListView::ListMode) || !d->proxyModel ||
+    if ((viewMode() != KListView::IconMode) || !d->proxyModel ||
         !d->itemCategorizer)
     {
         QListView::setSelection(rect, flags);
         return;
     }
 
-    // FIXME: I have to rethink and rewrite this method (ereslibre)
+    if (!flags)
+        return;
+
+    selectionModel()->clear();
+
+    if (flags & QItemSelectionModel::Clear)
+    {
+        d->lastSelection = QItemSelection();
+    }
 
     QModelIndexList dirtyIndexes = d->intersectionSet(rect);
-    foreach (const QModelIndex &index, dirtyIndexes)
+
+    QItemSelection selection;
+
+    if (!dirtyIndexes.count())
     {
-        if (!d->mouseButtonPressed && rect.intersects(visualRect(index)))
+        if (d->lastSelection.count())
         {
-            selectionModel()->select(index, flags);
+            selectionModel()->select(d->lastSelection, flags);
         }
-        else
-        {
-            selectionModel()->select(index, QItemSelectionModel::Select);
 
-            if (d->mouseButtonPressed)
-                d->tempSelected.append(index);
-        }
+        return;
     }
 
-    if (d->mouseButtonPressed)
+    if (!d->mouseButtonPressed)
+    {
+        selection = QItemSelection(dirtyIndexes[0], dirtyIndexes[0]);
+        d->currentViewIndex = dirtyIndexes[0];
+    }
+    else
     {
-        foreach (const QModelIndex &index, selectionModel()->selectedIndexes())
+        QModelIndex first = dirtyIndexes[0];
+        QModelIndex last;
+        foreach (const QModelIndex &index, dirtyIndexes)
         {
-            if (!rect.intersects(visualRect(index)))
+            if (last.isValid() && last.row() + 1 != index.row())
             {
-                selectionModel()->select(index, QItemSelectionModel::Deselect);
+                QItemSelectionRange range(first, last);
 
-                if (d->mouseButtonPressed)
-                {
-                    d->tempSelected.removeAll(index);
-                }
+                selection << range;
+
+                first = index;
             }
+
+            last = index;
         }
+
+        if (last.isValid())
+            selection << QItemSelectionRange(first, last);
     }
+
+    if (d->lastSelection.count() && !d->mouseButtonPressed)
+    {
+        selection.merge(d->lastSelection, flags);
+    }
+    else if (d->lastSelection.count())
+    {
+        selection.merge(d->lastSelection, QItemSelectionModel::Select);
+    }
+
+    selectionModel()->select(selection, flags);
 }
 
 void KListView::mouseMoveEvent(QMouseEvent *event)
 {
     QListView::mouseMoveEvent(event);
 
-    d->mousePosition = event->pos();
-
-    if ((viewMode() == KListView::ListMode) || !d->proxyModel ||
+    if ((viewMode() != KListView::IconMode) || !d->proxyModel ||
         !d->itemCategorizer)
     {
         return;
     }
 
-    event->accept();
-
-    viewport()->update();
-}
+    const QString previousHoveredCategory = d->hoveredCategory;
 
-void KListView::mousePressEvent(QMouseEvent *event)
-{
-    QListView::mousePressEvent(event);
+    d->mousePosition = event->pos();
+    d->hoveredCategory = QString();
 
-    d->tempSelected.clear();
+    // Redraw categories
+    foreach (const QString &category, d->categories)
+    {
+        if (d->categoryVisualRect(category).intersects(QRect(event->pos(), event->pos())))
+        {
+            d->hoveredCategory = category;
+            viewport()->update(d->categoryVisualRect(category));
+        }
+        else if ((category == previousHoveredCategory) &&
+                 (!d->categoryVisualRect(previousHoveredCategory).intersects(QRect(event->pos(), event->pos()))))
+        {
+            viewport()->update(d->categoryVisualRect(category));
+        }
+    }
 
-    if ((viewMode() == KListView::ListMode) || !d->proxyModel ||
-        !d->itemCategorizer)
+    QRect rect;
+    if (d->mouseButtonPressed && !d->isDragging)
     {
-        return;
+        QPoint start, end, initialPressPosition;
+
+        initialPressPosition = d->initialPressPosition;
+
+        initialPressPosition.setY(initialPressPosition.y() - verticalOffset());
+        initialPressPosition.setX(initialPressPosition.x() - horizontalOffset());
+
+        if (d->initialPressPosition.x() > d->mousePosition.x() ||
+            d->initialPressPosition.y() > d->mousePosition.y())
+        {
+            start = d->mousePosition;
+            end = initialPressPosition;
+        }
+        else
+        {
+            start = initialPressPosition;
+            end = d->mousePosition;
+        }
+
+        rect = QRect(start, end).intersected(viewport()->rect().adjusted(-16, -16, 16, 16));
+
+        //viewport()->update(rect.united(d->lastSelectionRect));
+
+        d->lastSelectionRect = rect;
     }
+}
 
-    event->accept();
+void KListView::mousePressEvent(QMouseEvent *event)
+{
+    d->dragLeftViewport = false;
 
     if (event->button() == Qt::LeftButton)
     {
@@ -739,75 +837,226 @@ void KListView::mousePressEvent(QMouseEvent *event)
                                                             horizontalOffset());
     }
 
-    viewport()->update();
+    QListView::mousePressEvent(event);
 }
 
 void KListView::mouseReleaseEvent(QMouseEvent *event)
 {
-    QListView::mouseReleaseEvent(event);
-
     d->mouseButtonPressed = false;
 
-    if ((viewMode() == KListView::ListMode) || !d->proxyModel ||
+    QListView::mouseReleaseEvent(event);
+
+    if ((viewMode() != KListView::IconMode) || !d->proxyModel ||
         !d->itemCategorizer)
     {
         return;
     }
 
-    event->accept();
-
-    // FIXME: I have to rethink and rewrite this method (ereslibre)
-
     QPoint initialPressPosition = viewport()->mapFromGlobal(QCursor::pos());
     initialPressPosition.setY(initialPressPosition.y() + verticalOffset());
     initialPressPosition.setX(initialPressPosition.x() + horizontalOffset());
 
+    QItemSelection selection;
+
     if (initialPressPosition == d->initialPressPosition)
     {
         foreach(const QString &category, d->categories)
         {
             if (d->categoryVisualRect(category).contains(event->pos()))
             {
-                QModelIndex index;
-                QItemSelectionModel::SelectionFlag flag;
-                foreach (const QModelIndex &mappedIndex,
-                         d->categoriesIndexes[category])
-                {
-                    index = d->proxyModel->mapFromSource(mappedIndex);
-
-                    if (selectionModel()->selectedIndexes().contains(index))
-                    {
-                        flag = QItemSelectionModel::Deselect;
-                    }
-                    else
-                    {
-                        flag = QItemSelectionModel::Select;
-                    }
-
-                    selectionModel()->select(index, flag);
-                }
+                QItemSelectionRange selectionRange(d->proxyModel->mapFromSource(d->categoriesIndexes[category][0]),
+                                                   d->proxyModel->mapFromSource(d->categoriesIndexes[category][d->categoriesIndexes[category].count() - 1]));
+
+                selection << selectionRange;
+
+                selectionModel()->select(selection, QItemSelectionModel::Select);
+
+                break;
             }
         }
     }
 
-    viewport()->update();
+    d->lastSelection = selectionModel()->selection();
+
+    if (d->hovered.isValid())
+        viewport()->update(d->visualRect(d->hovered));
+    else if (!d->hoveredCategory.isEmpty())
+        viewport()->update(d->categoryVisualRect(d->hoveredCategory));
 }
 
 void KListView::leaveEvent(QEvent *event)
 {
+    d->hovered = QModelIndex();
+    d->hoveredCategory = QString();
+
     QListView::leaveEvent(event);
+}
 
-    d->hovered = QModelIndex();
+void KListView::startDrag(Qt::DropActions supportedActions)
+{
+    QListView::startDrag(supportedActions);
+
+    d->isDragging = false;
+    d->mouseButtonPressed = false;
+
+    viewport()->update(d->lastDraggedItemsRect);
+}
+
+void KListView::dragMoveEvent(QDragMoveEvent *event)
+{
+    d->mousePosition = event->pos();
+
+    if (d->mouseButtonPressed)
+    {
+        d->isDragging = true;
+    }
+    else
+    {
+        d->isDragging = false;
+    }
 
-    if ((viewMode() == KListView::ListMode) || !d->proxyModel ||
+    d->dragLeftViewport = false;
+
+    if ((viewMode() != KListView::IconMode) || !d->proxyModel ||
         !d->itemCategorizer)
     {
+        QListView::dragMoveEvent(event);
         return;
     }
 
-    event->accept();
+    d->drawDraggedItems();
+}
+
+void KListView::dragLeaveEvent(QDragLeaveEvent *event)
+{
+    d->dragLeftViewport = true;
 
-    viewport()->update();
+    QListView::dragLeaveEvent(event);
+}
+
+QModelIndex KListView::moveCursor(CursorAction cursorAction,
+                                  Qt::KeyboardModifiers modifiers)
+{
+    if ((viewMode() != KListView::IconMode) || !d->proxyModel ||
+        !d->itemCategorizer)
+    {
+        return QListView::moveCursor(cursorAction, modifiers);
+    }
+
+    const QModelIndex current = selectionModel()->currentIndex();
+
+    int viewportWidth = viewport()->width() - spacing();
+    // We really need all items to be of same size. Otherwise we cannot do this
+    // (ereslibre)
+    // QSize itemSize = listView->sizeHintForIndex(index);
+    // int itemHeight = itemSize.height();
+    // int itemWidth = itemSize.width();
+    int itemHeight = 107;
+    int itemWidth = 130;
+    int itemWidthPlusSeparation = spacing() + itemWidth;
+    int elementsPerRow = viewportWidth / itemWidthPlusSeparation;
+
+    QString lastCategory = d->categories[0];
+    QString theCategory = d->categories[0];
+    QString afterCategory = d->categories[0];
+    bool hasToBreak = false;
+    foreach (const QString &category, d->categories)
+    {
+        if (hasToBreak)
+        {
+            afterCategory = category;
+
+            break;
+        }
+
+        if (category == d->elementsInfo[d->proxyModel->mapToSource(current)].category)
+        {
+            theCategory = category;
+
+            hasToBreak = true;
+        }
+
+        if (!hasToBreak)
+        {
+            lastCategory = category;
+        }
+    }
+
+    switch (cursorAction)
+    {
+        case QAbstractItemView::MoveUp: {
+            if (d->elementsInfo[d->proxyModel->mapToSource(current)].relativeOffsetToCategory >= elementsPerRow)
+            {
+                int indexToMove = d->invertedElementDictionary[current].row();
+                indexToMove -= qMin(((d->elementsInfo[d->proxyModel->mapToSource(current)].relativeOffsetToCategory) + d->forcedSelectionPosition), elementsPerRow - d->forcedSelectionPosition + (d->elementsInfo[d->proxyModel->mapToSource(current)].relativeOffsetToCategory % elementsPerRow));
+
+                return d->elementDictionary[d->proxyModel->index(indexToMove, 0)];
+            }
+            else
+            {
+                int lastCategoryLastRow = (d->categoriesIndexes[lastCategory].count() - 1) % elementsPerRow;
+                int indexToMove = d->invertedElementDictionary[current].row() - d->elementsInfo[d->proxyModel->mapToSource(current)].relativeOffsetToCategory;
+
+                if (d->forcedSelectionPosition >= lastCategoryLastRow)
+                {
+                    indexToMove -= 1;
+                }
+                else
+                {
+                    indexToMove -= qMin((lastCategoryLastRow - d->forcedSelectionPosition + 1), d->forcedSelectionPosition + elementsPerRow + 1);
+                }
+
+                return d->elementDictionary[d->proxyModel->index(indexToMove, 0)];
+            }
+        }
+
+        case QAbstractItemView::MoveDown: {
+            if (d->elementsInfo[d->proxyModel->mapToSource(current)].relativeOffsetToCategory < (d->categoriesIndexes[theCategory].count() - 1 - ((d->categoriesIndexes[theCategory].count() - 1) % elementsPerRow)))
+            {
+                int indexToMove = d->invertedElementDictionary[current].row();
+                indexToMove += qMin(elementsPerRow, d->categoriesIndexes[theCategory].count() - 1 - d->elementsInfo[d->proxyModel->mapToSource(current)].relativeOffsetToCategory);
+
+                return d->elementDictionary[d->proxyModel->index(indexToMove, 0)];
+            }
+            else
+            {
+                int afterCategoryLastRow = qMin(elementsPerRow, d->categoriesIndexes[afterCategory].count());
+                int indexToMove = d->invertedElementDictionary[current].row() + (d->categoriesIndexes[theCategory].count() - d->elementsInfo[d->proxyModel->mapToSource(current)].relativeOffsetToCategory);
+
+                if (d->forcedSelectionPosition >= afterCategoryLastRow)
+                {
+                    indexToMove += afterCategoryLastRow - 1;
+                }
+                else
+                {
+                    indexToMove += qMin(d->forcedSelectionPosition, elementsPerRow);
+                }
+
+                return d->elementDictionary[d->proxyModel->index(indexToMove, 0)];
+            }
+        }
+
+        case QAbstractItemView::MoveLeft:
+            d->forcedSelectionPosition = d->elementsInfo[d->proxyModel->mapToSource(d->elementDictionary[d->proxyModel->index(d->invertedElementDictionary[current].row() - 1, 0)])].relativeOffsetToCategory % elementsPerRow;
+
+            if (d->forcedSelectionPosition < 0)
+                d->forcedSelectionPosition = (d->categoriesIndexes[theCategory].count() - 1) % elementsPerRow;
+
+            return d->elementDictionary[d->proxyModel->index(d->invertedElementDictionary[current].row() - 1, 0)];
+
+        case QAbstractItemView::MoveRight:
+            d->forcedSelectionPosition = d->elementsInfo[d->proxyModel->mapToSource(d->elementDictionary[d->proxyModel->index(d->invertedElementDictionary[current].row() + 1, 0)])].relativeOffsetToCategory % elementsPerRow;
+
+            if (d->forcedSelectionPosition < 0)
+                d->forcedSelectionPosition = (d->categoriesIndexes[theCategory].count() - 1) % elementsPerRow;
+
+            return d->elementDictionary[d->proxyModel->index(d->invertedElementDictionary[current].row() + 1, 0)];
+
+        default:
+            break;
+    }
+
+    return QListView::moveCursor(cursorAction, modifiers);
 }
 
 void KListView::rowsInserted(const QModelIndex &parent,
@@ -816,9 +1065,24 @@ void KListView::rowsInserted(const QModelIndex &parent,
 {
     QListView::rowsInserted(parent, start, end);
 
-    if ((viewMode() == KListView::ListMode) || !d->proxyModel ||
+    if ((viewMode() != KListView::IconMode) || !d->proxyModel ||
         !d->itemCategorizer)
     {
+        d->lastSelection = QItemSelection();
+        d->currentViewIndex = QModelIndex();
+        d->forcedSelectionPosition = 0;
+        d->elementsInfo.clear();
+        d->elementsPosition.clear();
+        d->elementDictionary.clear();
+        d->invertedElementDictionary.clear();
+        d->categoriesIndexes.clear();
+        d->categoriesPosition.clear();
+        d->categories.clear();
+        d->intersectedIndexes.clear();
+        d->sourceModelIndexList.clear();
+        d->hovered = QModelIndex();
+        d->mouseButtonPressed = false;
+
         return;
     }
 
@@ -826,12 +1090,18 @@ void KListView::rowsInserted(const QModelIndex &parent,
 }
 
 void KListView::rowsInsertedArtifficial(const QModelIndex &parent,
-                                                int start,
-                                                int end)
+                                        int start,
+                                        int end)
 {
+    Q_UNUSED(parent);
+
+    d->lastSelection = QItemSelection();
+    d->currentViewIndex = QModelIndex();
+    d->forcedSelectionPosition = 0;
     d->elementsInfo.clear();
     d->elementsPosition.clear();
     d->elementDictionary.clear();
+    d->invertedElementDictionary.clear();
     d->categoriesIndexes.clear();
     d->categoriesPosition.clear();
     d->categories.clear();
@@ -918,6 +1188,9 @@ void KListView::rowsInsertedArtifficial(const QModelIndex &parent,
             d->elementDictionary.insert(d->proxyModel->index(j, 0),
                                         d->proxyModel->mapFromSource(index));
 
+            d->invertedElementDictionary.insert(d->proxyModel->mapFromSource(index),
+                                                d->proxyModel->index(j, 0));
+
             i++;
             j++;
         }
@@ -932,7 +1205,8 @@ void KListView::rowsRemoved(const QModelIndex &parent,
                             int start,
                             int end)
 {
-    if (d->proxyModel)
+    if ((viewMode() == KListView::IconMode) && d->proxyModel &&
+        d->itemCategorizer)
     {
         // Force the view to update all elements
         rowsInsertedArtifficial(parent, start, end);
@@ -941,7 +1215,7 @@ void KListView::rowsRemoved(const QModelIndex &parent,
 
 void KListView::updateGeometries()
 {
-    if ((viewMode() == KListView::ListMode) || !d->proxyModel ||
+    if ((viewMode() != KListView::IconMode) || !d->proxyModel ||
         !d->itemCategorizer)
     {
         QListView::updateGeometries();
@@ -955,11 +1229,11 @@ void KListView::updateGeometries()
 
 void KListView::slotSortingRoleChanged()
 {
-    if (d->proxyModel)
+    if ((viewMode() == KListView::IconMode) && d->proxyModel &&
+        d->itemCategorizer)
     {
         // Force the view to update all elements
-        rowsInsertedArtifficial(QModelIndex(), 0, d->proxyModel->rowCount() -
-                                                                             1);
+        rowsInsertedArtifficial(QModelIndex(), 0, d->proxyModel->rowCount() - 1);
     }
 }