]> cloud.milkyroute.net Git - dolphin.git/blob - src/kcategorizedview.cpp
Fixes the problem with the keyboard navigation when a selection with the right-click...
[dolphin.git] / src / kcategorizedview.cpp
1 /**
2 * This file is part of the KDE project
3 * Copyright (C) 2007 Rafael Fernández López <ereslibre@kde.org>
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Library General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Library General Public License for more details.
14 *
15 * You should have received a copy of the GNU Library General Public License
16 * along with this library; see the file COPYING.LIB. If not, write to
17 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 * Boston, MA 02110-1301, USA.
19 */
20
21 #include "kcategorizedview.h"
22 #include "kcategorizedview_p.h"
23
24 #include <math.h> // trunc on C99 compliant systems
25 #include <kdefakes.h> // trunc for not C99 compliant systems
26
27 #include <QPainter>
28 #include <QScrollBar>
29 #include <QPaintEvent>
30
31 #include <kstyle.h>
32
33 #include "kcategorydrawer.h"
34 #include "kcategorizedsortfilterproxymodel.h"
35
36 // By defining DOLPHIN_DRAGANDDROP the custom drag and drop implementation of
37 // KCategorizedView is bypassed to have a consistent drag and drop look for all
38 // views. Hopefully transparent pixmaps for drag objects will be supported in
39 // Qt 4.4, so that this workaround can be skipped.
40 #define DOLPHIN_DRAGANDDROP
41
42 KCategorizedView::Private::Private(KCategorizedView *listView)
43 : listView(listView)
44 , categoryDrawer(0)
45 , biggestItemSize(QSize(0, 0))
46 , mouseButtonPressed(false)
47 , isDragging(false)
48 , dragLeftViewport(false)
49 , proxyModel(0)
50 {
51 }
52
53 KCategorizedView::Private::~Private()
54 {
55 }
56
57 const QModelIndexList &KCategorizedView::Private::intersectionSet(const QRect &rect)
58 {
59 QModelIndex index;
60 QRect indexVisualRect;
61
62 intersectedIndexes.clear();
63
64 int itemHeight;
65
66 if (listView->gridSize().isEmpty())
67 {
68 itemHeight = biggestItemSize.height();
69 }
70 else
71 {
72 itemHeight = listView->gridSize().height();
73 }
74
75 // Lets find out where we should start
76 int top = proxyModel->rowCount() - 1;
77 int bottom = 0;
78 int middle = (top + bottom) / 2;
79 while (bottom <= top)
80 {
81 middle = (top + bottom) / 2;
82
83 index = proxyModel->index(middle, 0);
84 indexVisualRect = visualRect(index);
85 // We need the whole height (not only the visualRect). This will help us to update
86 // all needed indexes correctly (ereslibre)
87 indexVisualRect.setHeight(indexVisualRect.height() + (itemHeight - indexVisualRect.height()));
88
89 if (qMax(indexVisualRect.topLeft().y(),
90 indexVisualRect.bottomRight().y()) < qMin(rect.topLeft().y(),
91 rect.bottomRight().y()))
92 {
93 bottom = middle + 1;
94 }
95 else
96 {
97 top = middle - 1;
98 }
99 }
100
101 for (int i = middle; i < proxyModel->rowCount(); i++)
102 {
103 index = proxyModel->index(i, 0);
104 indexVisualRect = visualRect(index);
105
106 if (rect.intersects(indexVisualRect))
107 intersectedIndexes.append(index);
108
109 // If we passed next item, stop searching for hits
110 if (qMax(rect.bottomRight().y(), rect.topLeft().y()) <
111 qMin(indexVisualRect.topLeft().y(),
112 indexVisualRect.bottomRight().y()))
113 break;
114 }
115
116 return intersectedIndexes;
117 }
118
119 QRect KCategorizedView::Private::visualRectInViewport(const QModelIndex &index) const
120 {
121 if (!index.isValid())
122 return QRect();
123
124 QString curCategory = elementsInfo[index.row()].category;
125
126 QRect retRect;
127
128 if (listView->layoutDirection() == Qt::LeftToRight)
129 {
130 retRect = QRect(listView->spacing(), listView->spacing() * 2 +
131 categoryDrawer->categoryHeight(listView->viewOptions()), 0, 0);
132 }
133 else
134 {
135 retRect = QRect(listView->viewport()->width() - listView->spacing(), listView->spacing() * 2 +
136 categoryDrawer->categoryHeight(listView->viewOptions()), 0, 0);
137 }
138
139 int viewportWidth = listView->viewport()->width() - listView->spacing();
140
141 int itemHeight;
142 int itemWidth;
143
144 if (listView->gridSize().isEmpty())
145 {
146 itemHeight = biggestItemSize.height();
147 itemWidth = biggestItemSize.width();
148 }
149 else
150 {
151 itemHeight = listView->gridSize().height();
152 itemWidth = listView->gridSize().width();
153 }
154
155 int itemWidthPlusSeparation = listView->spacing() + itemWidth;
156 int elementsPerRow = viewportWidth / itemWidthPlusSeparation;
157 if (!elementsPerRow)
158 elementsPerRow++;
159
160 int column = elementsInfo[index.row()].relativeOffsetToCategory % elementsPerRow;
161 int row = elementsInfo[index.row()].relativeOffsetToCategory / elementsPerRow;
162
163 if (listView->layoutDirection() == Qt::LeftToRight)
164 {
165 retRect.setLeft(retRect.left() + column * listView->spacing() +
166 column * itemWidth);
167 }
168 else
169 {
170 retRect.setLeft(retRect.right() - column * listView->spacing() -
171 column * itemWidth - itemWidth);
172
173 retRect.setRight(retRect.right() - column * listView->spacing() -
174 column * itemWidth);
175 }
176
177 foreach (const QString &category, categories)
178 {
179 if (category == curCategory)
180 break;
181
182 float rows = (float) ((float) categoriesIndexes[category].count() /
183 (float) elementsPerRow);
184
185 int rowsInt = categoriesIndexes[category].count() / elementsPerRow;
186
187 if (rows - trunc(rows)) rowsInt++;
188
189 retRect.setTop(retRect.top() +
190 (rowsInt * itemHeight) +
191 categoryDrawer->categoryHeight(listView->viewOptions()) +
192 listView->spacing() * 2);
193
194 if (listView->gridSize().isEmpty())
195 {
196 retRect.setTop(retRect.top() +
197 (rowsInt * listView->spacing()));
198 }
199 }
200
201 if (listView->gridSize().isEmpty())
202 {
203 retRect.setTop(retRect.top() + row * listView->spacing() +
204 (row * itemHeight));
205 }
206 else
207 {
208 retRect.setTop(retRect.top() + (row * itemHeight));
209 }
210
211 retRect.setWidth(itemWidth);
212
213 QModelIndex heightIndex = proxyModel->index(index.row(), 0);
214 if (listView->gridSize().isEmpty())
215 {
216 retRect.setHeight(listView->sizeHintForIndex(heightIndex).height());
217 }
218 else
219 {
220 retRect.setHeight(qMin(listView->sizeHintForIndex(heightIndex).height(),
221 listView->gridSize().height()));
222 }
223
224 return retRect;
225 }
226
227 QRect KCategorizedView::Private::visualCategoryRectInViewport(const QString &category)
228 const
229 {
230 QRect retRect(listView->spacing(),
231 listView->spacing(),
232 listView->viewport()->width() - listView->spacing() * 2,
233 0);
234
235 if (!proxyModel->rowCount() || !categories.contains(category))
236 return QRect();
237
238 QModelIndex index = proxyModel->index(0, 0, QModelIndex());
239
240 int viewportWidth = listView->viewport()->width() - listView->spacing();
241
242 int itemHeight;
243 int itemWidth;
244
245 if (listView->gridSize().isEmpty())
246 {
247 itemHeight = biggestItemSize.height();
248 itemWidth = biggestItemSize.width();
249 }
250 else
251 {
252 itemHeight = listView->gridSize().height();
253 itemWidth = listView->gridSize().width();
254 }
255
256 int itemWidthPlusSeparation = listView->spacing() + itemWidth;
257 int elementsPerRow = viewportWidth / itemWidthPlusSeparation;
258
259 if (!elementsPerRow)
260 elementsPerRow++;
261
262 foreach (const QString &itCategory, categories)
263 {
264 if (itCategory == category)
265 break;
266
267 float rows = (float) ((float) categoriesIndexes[itCategory].count() /
268 (float) elementsPerRow);
269 int rowsInt = categoriesIndexes[itCategory].count() / elementsPerRow;
270
271 if (rows - trunc(rows)) rowsInt++;
272
273 retRect.setTop(retRect.top() +
274 (rowsInt * itemHeight) +
275 categoryDrawer->categoryHeight(listView->viewOptions()) +
276 listView->spacing() * 2);
277
278 if (listView->gridSize().isEmpty())
279 {
280 retRect.setTop(retRect.top() +
281 (rowsInt * listView->spacing()));
282 }
283 }
284
285 retRect.setHeight(categoryDrawer->categoryHeight(listView->viewOptions()));
286
287 return retRect;
288 }
289
290 // We're sure elementsPosition doesn't contain index
291 const QRect &KCategorizedView::Private::cacheIndex(const QModelIndex &index)
292 {
293 QRect rect = visualRectInViewport(index);
294 elementsPosition[index.row()] = rect;
295
296 return elementsPosition[index.row()];
297 }
298
299 // We're sure categoriesPosition doesn't contain category
300 const QRect &KCategorizedView::Private::cacheCategory(const QString &category)
301 {
302 QRect rect = visualCategoryRectInViewport(category);
303 categoriesPosition[category] = rect;
304
305 return categoriesPosition[category];
306 }
307
308 const QRect &KCategorizedView::Private::cachedRectIndex(const QModelIndex &index)
309 {
310 if (elementsPosition.contains(index.row())) // If we have it cached
311 { // return it
312 return elementsPosition[index.row()];
313 }
314 else // Otherwise, cache it
315 { // and return it
316 return cacheIndex(index);
317 }
318 }
319
320 const QRect &KCategorizedView::Private::cachedRectCategory(const QString &category)
321 {
322 if (categoriesPosition.contains(category)) // If we have it cached
323 { // return it
324 return categoriesPosition[category];
325 }
326 else // Otherwise, cache it and
327 { // return it
328 return cacheCategory(category);
329 }
330 }
331
332 QRect KCategorizedView::Private::visualRect(const QModelIndex &index)
333 {
334 QRect retRect = cachedRectIndex(index);
335 int dx = -listView->horizontalOffset();
336 int dy = -listView->verticalOffset();
337 retRect.adjust(dx, dy, dx, dy);
338
339 return retRect;
340 }
341
342 QRect KCategorizedView::Private::categoryVisualRect(const QString &category)
343 {
344 QRect retRect = cachedRectCategory(category);
345 int dx = -listView->horizontalOffset();
346 int dy = -listView->verticalOffset();
347 retRect.adjust(dx, dy, dx, dy);
348
349 return retRect;
350 }
351
352 void KCategorizedView::Private::drawNewCategory(const QModelIndex &index,
353 int sortRole,
354 const QStyleOption &option,
355 QPainter *painter)
356 {
357 if (!index.isValid())
358 {
359 return;
360 }
361
362 QStyleOption optionCopy = option;
363 const QString category = proxyModel->data(index, KCategorizedSortFilterProxyModel::CategoryDisplayRole).toString();
364
365 optionCopy.state &= ~QStyle::State_Selected;
366
367 if ((category == hoveredCategory) && !mouseButtonPressed)
368 {
369 optionCopy.state |= QStyle::State_MouseOver;
370 }
371 else if ((category == hoveredCategory) && mouseButtonPressed)
372 {
373 QPoint initialPressPosition = listView->viewport()->mapFromGlobal(QCursor::pos());
374 initialPressPosition.setY(initialPressPosition.y() + listView->verticalOffset());
375 initialPressPosition.setX(initialPressPosition.x() + listView->horizontalOffset());
376
377 if (initialPressPosition == this->initialPressPosition)
378 {
379 optionCopy.state |= QStyle::State_Selected;
380 }
381 }
382
383 categoryDrawer->drawCategory(index,
384 sortRole,
385 optionCopy,
386 painter);
387 }
388
389
390 void KCategorizedView::Private::updateScrollbars()
391 {
392 // find the last index in the last category
393 QModelIndex lastIndex = categoriesIndexes.isEmpty() ? QModelIndex() : categoriesIndexes[categories.last()].last();
394
395 int lastItemBottom = cachedRectIndex(lastIndex).top() +
396 listView->spacing() + (listView->gridSize().isEmpty() ? 0 : listView->gridSize().height()) - listView->viewport()->height();
397
398 listView->horizontalScrollBar()->setRange(0, 0);
399
400 listView->verticalScrollBar()->setSingleStep(listView->viewport()->height() / 10);
401 listView->verticalScrollBar()->setPageStep(listView->viewport()->height());
402 listView->verticalScrollBar()->setRange(0, lastItemBottom);
403 }
404
405 void KCategorizedView::Private::drawDraggedItems(QPainter *painter)
406 {
407 QStyleOptionViewItemV3 option = listView->viewOptions();
408 option.state &= ~QStyle::State_MouseOver;
409 foreach (const QModelIndex &index, listView->selectionModel()->selectedIndexes())
410 {
411 const int dx = mousePosition.x() - initialPressPosition.x() + listView->horizontalOffset();
412 const int dy = mousePosition.y() - initialPressPosition.y() + listView->verticalOffset();
413
414 option.rect = visualRect(index);
415 option.rect.adjust(dx, dy, dx, dy);
416
417 if (option.rect.intersects(listView->viewport()->rect()))
418 {
419 listView->itemDelegate(index)->paint(painter, option, index);
420 }
421 }
422 }
423
424 void KCategorizedView::Private::layoutChanged(bool forceItemReload)
425 {
426 if ((listView->viewMode() == KCategorizedView::IconMode) && proxyModel &&
427 categoryDrawer && proxyModel->isCategorizedModel() &&
428 ((forceItemReload ||
429 (modelSortRole != proxyModel->sortRole()) ||
430 (modelSortColumn != proxyModel->sortColumn()) ||
431 (modelSortOrder != proxyModel->sortOrder()) ||
432 (modelLastRowCount != proxyModel->rowCount()) ||
433 (modelCategorized != proxyModel->isCategorizedModel()))))
434 {
435 // Force the view to update all elements
436 listView->rowsInsertedArtifficial(QModelIndex(), 0, proxyModel->rowCount() - 1);
437
438 if (!forceItemReload)
439 {
440 modelSortRole = proxyModel->sortRole();
441 modelSortColumn = proxyModel->sortColumn();
442 modelSortOrder = proxyModel->sortOrder();
443 modelLastRowCount = proxyModel->rowCount();
444 modelCategorized = proxyModel->isCategorizedModel();
445 }
446 }
447 else if ((listView->viewMode() == KCategorizedView::IconMode) && proxyModel &&
448 categoryDrawer && proxyModel->isCategorizedModel())
449 {
450 updateScrollbars();
451 }
452 }
453
454 void KCategorizedView::Private::drawDraggedItems()
455 {
456 QRect rectToUpdate;
457 QRect currentRect;
458 foreach (const QModelIndex &index, listView->selectionModel()->selectedIndexes())
459 {
460 int dx = mousePosition.x() - initialPressPosition.x() + listView->horizontalOffset();
461 int dy = mousePosition.y() - initialPressPosition.y() + listView->verticalOffset();
462
463 currentRect = visualRect(index);
464 currentRect.adjust(dx, dy, dx, dy);
465
466 if (currentRect.intersects(listView->viewport()->rect()))
467 {
468 rectToUpdate = rectToUpdate.united(currentRect);
469 }
470 }
471
472 listView->viewport()->update(lastDraggedItemsRect.united(rectToUpdate));
473
474 lastDraggedItemsRect = rectToUpdate;
475 }
476
477
478 //==============================================================================
479
480
481 KCategorizedView::KCategorizedView(QWidget *parent)
482 : QListView(parent)
483 , d(new Private(this))
484 {
485 }
486
487 KCategorizedView::~KCategorizedView()
488 {
489 delete d;
490 }
491
492 void KCategorizedView::setGridSize(const QSize &size)
493 {
494 QListView::setGridSize(size);
495
496 d->layoutChanged(true);
497 }
498
499 void KCategorizedView::setModel(QAbstractItemModel *model)
500 {
501 d->lastSelection = QItemSelection();
502 d->currentViewIndex = QModelIndex();
503 d->forcedSelectionPosition = 0;
504 d->elementsInfo.clear();
505 d->elementsPosition.clear();
506 d->categoriesIndexes.clear();
507 d->categoriesPosition.clear();
508 d->categories.clear();
509 d->intersectedIndexes.clear();
510 d->modelIndexList.clear();
511 d->hovered = QModelIndex();
512 d->mouseButtonPressed = false;
513
514 if (d->proxyModel)
515 {
516 QObject::disconnect(d->proxyModel,
517 SIGNAL(layoutChanged()),
518 this, SLOT(slotLayoutChanged()));
519
520 QObject::disconnect(d->proxyModel,
521 SIGNAL(dataChanged(QModelIndex,QModelIndex)),
522 this, SLOT(slotLayoutChanged()));
523
524 QObject::disconnect(d->proxyModel,
525 SIGNAL(rowsRemoved(QModelIndex,int,int)),
526 this, SLOT(rowsRemoved(QModelIndex,int,int)));
527 }
528
529 QListView::setModel(model);
530
531 d->proxyModel = dynamic_cast<KCategorizedSortFilterProxyModel*>(model);
532
533 if (d->proxyModel)
534 {
535 d->modelSortRole = d->proxyModel->sortRole();
536 d->modelSortColumn = d->proxyModel->sortColumn();
537 d->modelSortOrder = d->proxyModel->sortOrder();
538 d->modelLastRowCount = d->proxyModel->rowCount();
539 d->modelCategorized = d->proxyModel->isCategorizedModel();
540
541 QObject::connect(d->proxyModel,
542 SIGNAL(layoutChanged()),
543 this, SLOT(slotLayoutChanged()));
544
545 QObject::connect(d->proxyModel,
546 SIGNAL(dataChanged(QModelIndex,QModelIndex)),
547 this, SLOT(slotLayoutChanged()));
548
549 QObject::connect(d->proxyModel,
550 SIGNAL(rowsRemoved(QModelIndex,int,int)),
551 this, SLOT(rowsRemoved(QModelIndex,int,int)));
552
553 if (d->proxyModel->rowCount())
554 {
555 d->layoutChanged(true);
556 }
557 }
558 else
559 {
560 d->modelCategorized = false;
561 }
562 }
563
564 QRect KCategorizedView::visualRect(const QModelIndex &index) const
565 {
566 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
567 !d->categoryDrawer || !d->proxyModel->isCategorizedModel())
568 {
569 return QListView::visualRect(index);
570 }
571
572 if (!qobject_cast<const QSortFilterProxyModel*>(index.model()))
573 {
574 return d->visualRect(d->proxyModel->mapFromSource(index));
575 }
576
577 return d->visualRect(index);
578 }
579
580 KCategoryDrawer *KCategorizedView::categoryDrawer() const
581 {
582 return d->categoryDrawer;
583 }
584
585 void KCategorizedView::setCategoryDrawer(KCategoryDrawer *categoryDrawer)
586 {
587 d->lastSelection = QItemSelection();
588 d->currentViewIndex = QModelIndex();
589 d->forcedSelectionPosition = 0;
590 d->elementsInfo.clear();
591 d->elementsPosition.clear();
592 d->categoriesIndexes.clear();
593 d->categoriesPosition.clear();
594 d->categories.clear();
595 d->intersectedIndexes.clear();
596 d->modelIndexList.clear();
597 d->hovered = QModelIndex();
598 d->mouseButtonPressed = false;
599
600 if (!categoryDrawer && d->proxyModel)
601 {
602 QObject::disconnect(d->proxyModel,
603 SIGNAL(layoutChanged()),
604 this, SLOT(slotLayoutChanged()));
605
606 QObject::disconnect(d->proxyModel,
607 SIGNAL(dataChanged(QModelIndex,QModelIndex)),
608 this, SLOT(slotLayoutChanged()));
609
610 QObject::disconnect(d->proxyModel,
611 SIGNAL(rowsRemoved(QModelIndex,int,int)),
612 this, SLOT(rowsRemoved(QModelIndex,int,int)));
613 }
614 else if (categoryDrawer && d->proxyModel)
615 {
616 QObject::connect(d->proxyModel,
617 SIGNAL(layoutChanged()),
618 this, SLOT(slotLayoutChanged()));
619
620 QObject::connect(d->proxyModel,
621 SIGNAL(dataChanged(QModelIndex,QModelIndex)),
622 this, SLOT(slotLayoutChanged()));
623
624 QObject::connect(d->proxyModel,
625 SIGNAL(rowsRemoved(QModelIndex,int,int)),
626 this, SLOT(rowsRemoved(QModelIndex,int,int)));
627 }
628
629 d->categoryDrawer = categoryDrawer;
630
631 if (categoryDrawer)
632 {
633 if (d->proxyModel)
634 {
635 if (d->proxyModel->rowCount())
636 {
637 d->layoutChanged(true);
638 }
639 }
640 }
641 else
642 {
643 updateGeometries();
644 }
645 }
646
647 QModelIndex KCategorizedView::indexAt(const QPoint &point) const
648 {
649 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
650 !d->categoryDrawer || !d->proxyModel->isCategorizedModel())
651 {
652 return QListView::indexAt(point);
653 }
654
655 QModelIndex index;
656
657 QModelIndexList item = d->intersectionSet(QRect(point, point));
658
659 if (item.count() == 1)
660 {
661 index = item[0];
662 }
663
664 d->hovered = index;
665
666 return index;
667 }
668
669 void KCategorizedView::reset()
670 {
671 QListView::reset();
672
673 d->lastSelection = QItemSelection();
674 d->currentViewIndex = QModelIndex();
675 d->forcedSelectionPosition = 0;
676 d->elementsInfo.clear();
677 d->elementsPosition.clear();
678 d->categoriesIndexes.clear();
679 d->categoriesPosition.clear();
680 d->categories.clear();
681 d->intersectedIndexes.clear();
682 d->modelIndexList.clear();
683 d->hovered = QModelIndex();
684 d->biggestItemSize = QSize(0, 0);
685 d->mouseButtonPressed = false;
686 }
687
688 void KCategorizedView::paintEvent(QPaintEvent *event)
689 {
690 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
691 !d->categoryDrawer || !d->proxyModel->isCategorizedModel())
692 {
693 QListView::paintEvent(event);
694 return;
695 }
696
697 QStyleOptionViewItemV3 option = viewOptions();
698 option.widget = this;
699 if (wordWrap())
700 {
701 option.features |= QStyleOptionViewItemV2::WrapText;
702 }
703
704 QPainter painter(viewport());
705 QRect area = event->rect();
706 const bool focus = (hasFocus() || viewport()->hasFocus()) &&
707 currentIndex().isValid();
708 const QStyle::State state = option.state;
709 const bool enabled = (state & QStyle::State_Enabled) != 0;
710
711 painter.save();
712
713 QModelIndexList dirtyIndexes = d->intersectionSet(area);
714 foreach (const QModelIndex &index, dirtyIndexes)
715 {
716 option.state = state;
717 option.rect = visualRect(index);
718
719 if (selectionModel() && selectionModel()->isSelected(index))
720 {
721 option.state |= QStyle::State_Selected;
722 }
723
724 if (enabled)
725 {
726 QPalette::ColorGroup cg;
727 if ((d->proxyModel->flags(index) & Qt::ItemIsEnabled) == 0)
728 {
729 option.state &= ~QStyle::State_Enabled;
730 cg = QPalette::Disabled;
731 }
732 else
733 {
734 cg = QPalette::Normal;
735 }
736 option.palette.setCurrentColorGroup(cg);
737 }
738
739 if (focus && currentIndex() == index)
740 {
741 option.state |= QStyle::State_HasFocus;
742 if (this->state() == EditingState)
743 option.state |= QStyle::State_Editing;
744 }
745
746 if ((index == d->hovered) && !d->mouseButtonPressed)
747 option.state |= QStyle::State_MouseOver;
748 else
749 option.state &= ~QStyle::State_MouseOver;
750
751 itemDelegate(index)->paint(&painter, option, index);
752 }
753
754 // Redraw categories
755 QStyleOptionViewItem otherOption;
756 bool intersectedInThePast = false;
757 foreach (const QString &category, d->categories)
758 {
759 otherOption = option;
760 otherOption.rect = d->categoryVisualRect(category);
761 otherOption.state &= ~QStyle::State_MouseOver;
762
763 if (otherOption.rect.intersects(area))
764 {
765 intersectedInThePast = true;
766
767 QModelIndex indexToDraw = d->proxyModel->index(d->categoriesIndexes[category][0].row(), d->proxyModel->sortColumn());
768
769 d->drawNewCategory(indexToDraw,
770 d->proxyModel->sortRole(), otherOption, &painter);
771 }
772 else if (intersectedInThePast)
773 {
774 break; // the visible area has been finished, we don't need to keep asking, the rest won't intersect
775 // this is doable because we know that categories are correctly ordered on the list
776 }
777 }
778
779 if (d->mouseButtonPressed && !d->isDragging)
780 {
781 QPoint start, end, initialPressPosition;
782
783 initialPressPosition = d->initialPressPosition;
784
785 initialPressPosition.setY(initialPressPosition.y() - verticalOffset());
786 initialPressPosition.setX(initialPressPosition.x() - horizontalOffset());
787
788 if (d->initialPressPosition.x() > d->mousePosition.x() ||
789 d->initialPressPosition.y() > d->mousePosition.y())
790 {
791 start = d->mousePosition;
792 end = initialPressPosition;
793 }
794 else
795 {
796 start = initialPressPosition;
797 end = d->mousePosition;
798 }
799
800 QStyleOptionRubberBand yetAnotherOption;
801 yetAnotherOption.initFrom(this);
802 yetAnotherOption.shape = QRubberBand::Rectangle;
803 yetAnotherOption.opaque = false;
804 yetAnotherOption.rect = QRect(start, end).intersected(viewport()->rect().adjusted(-16, -16, 16, 16));
805 painter.save();
806 style()->drawControl(QStyle::CE_RubberBand, &yetAnotherOption, &painter);
807 painter.restore();
808 }
809
810 if (d->isDragging && !d->dragLeftViewport)
811 {
812 painter.setOpacity(0.5);
813 d->drawDraggedItems(&painter);
814 }
815
816 painter.restore();
817 }
818
819 void KCategorizedView::resizeEvent(QResizeEvent *event)
820 {
821 QListView::resizeEvent(event);
822
823 // Clear the items positions cache
824 d->elementsPosition.clear();
825 d->categoriesPosition.clear();
826 d->forcedSelectionPosition = 0;
827
828 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
829 !d->categoryDrawer || !d->proxyModel->isCategorizedModel())
830 {
831 return;
832 }
833
834 d->updateScrollbars();
835 }
836
837 void KCategorizedView::setSelection(const QRect &rect,
838 QItemSelectionModel::SelectionFlags flags)
839 {
840 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
841 !d->categoryDrawer || !d->proxyModel->isCategorizedModel())
842 {
843 QListView::setSelection(rect, flags);
844 return;
845 }
846
847 if (!flags)
848 return;
849
850 if (flags & QItemSelectionModel::Clear)
851 {
852 if (!rect.intersects(d->categoryVisualRect(d->hoveredCategory)))
853 {
854 d->lastSelection = QItemSelection();
855 }
856 }
857
858 selectionModel()->clear();
859
860 QModelIndexList dirtyIndexes = d->intersectionSet(rect);
861
862 if (!dirtyIndexes.count())
863 {
864 if (!d->lastSelection.isEmpty() &&
865 (rect.intersects(d->categoryVisualRect(d->hoveredCategory)) || d->mouseButtonPressed))
866 {
867 selectionModel()->select(d->lastSelection, flags);
868 }
869
870 return;
871 }
872
873 int viewportWidth = viewport()->width() - spacing();
874 int itemWidth;
875
876 if (gridSize().isEmpty())
877 {
878 itemWidth = d->biggestItemSize.width();
879 }
880 else
881 {
882 itemWidth = gridSize().width();
883 }
884
885 int itemWidthPlusSeparation = spacing() + itemWidth;
886 int elementsPerRow = viewportWidth / itemWidthPlusSeparation;
887
888 QItemSelection selection;
889
890 if (!d->mouseButtonPressed)
891 {
892 selection = QItemSelection(dirtyIndexes[0], dirtyIndexes[0]);
893 d->currentViewIndex = dirtyIndexes[0];
894 selectionModel()->setCurrentIndex(d->currentViewIndex, flags);
895 d->forcedSelectionPosition = d->elementsInfo[d->currentViewIndex.row()].relativeOffsetToCategory % elementsPerRow;
896 }
897 else
898 {
899 QModelIndex first = dirtyIndexes[0];
900 QModelIndex last;
901 foreach (const QModelIndex &index, dirtyIndexes)
902 {
903 if (last.isValid() && last.row() + 1 != index.row())
904 {
905 QItemSelectionRange range(first, last);
906
907 selection << range;
908
909 first = index;
910 }
911
912 last = index;
913 }
914
915 if (last.isValid())
916 selection << QItemSelectionRange(first, last);
917
918 if (first == last)
919 {
920 selectionModel()->setCurrentIndex(first, QItemSelectionModel::SelectCurrent);
921 d->forcedSelectionPosition = d->elementsInfo[first.row()].relativeOffsetToCategory % elementsPerRow;
922 }
923 }
924
925 if (d->lastSelection.count())
926 {
927 if ((selection.count() == 1) && (selection[0].indexes().count() == 1))
928 selection.merge(d->lastSelection, flags);
929 else
930 selection.merge(d->lastSelection, QItemSelectionModel::Select);
931 }
932
933 selectionModel()->select(selection, flags);
934 }
935
936 void KCategorizedView::mouseMoveEvent(QMouseEvent *event)
937 {
938 QListView::mouseMoveEvent(event);
939
940 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
941 !d->categoryDrawer || !d->proxyModel->isCategorizedModel())
942 {
943 return;
944 }
945
946 const QString previousHoveredCategory = d->hoveredCategory;
947
948 d->mousePosition = event->pos();
949 d->hoveredCategory = QString();
950
951 // Redraw categories
952 foreach (const QString &category, d->categories)
953 {
954 if (d->categoryVisualRect(category).intersects(QRect(event->pos(), event->pos())))
955 {
956 d->hoveredCategory = category;
957 viewport()->update(d->categoryVisualRect(category));
958 }
959 else if ((category == previousHoveredCategory) &&
960 (!d->categoryVisualRect(previousHoveredCategory).intersects(QRect(event->pos(), event->pos()))))
961 {
962 viewport()->update(d->categoryVisualRect(category));
963 }
964 }
965
966 QRect rect;
967 if (d->mouseButtonPressed && !d->isDragging)
968 {
969 QPoint start, end, initialPressPosition;
970
971 initialPressPosition = d->initialPressPosition;
972
973 initialPressPosition.setY(initialPressPosition.y() - verticalOffset());
974 initialPressPosition.setX(initialPressPosition.x() - horizontalOffset());
975
976 if (d->initialPressPosition.x() > d->mousePosition.x() ||
977 d->initialPressPosition.y() > d->mousePosition.y())
978 {
979 start = d->mousePosition;
980 end = initialPressPosition;
981 }
982 else
983 {
984 start = initialPressPosition;
985 end = d->mousePosition;
986 }
987
988 rect = QRect(start, end).intersected(viewport()->rect().adjusted(-16, -16, 16, 16));
989
990 //viewport()->update(rect.united(d->lastSelectionRect));
991
992 d->lastSelectionRect = rect;
993 }
994 }
995
996 void KCategorizedView::mousePressEvent(QMouseEvent *event)
997 {
998 d->dragLeftViewport = false;
999
1000 if (event->button() == Qt::LeftButton)
1001 {
1002 d->mouseButtonPressed = true;
1003
1004 d->initialPressPosition = event->pos();
1005 d->initialPressPosition.setY(d->initialPressPosition.y() +
1006 verticalOffset());
1007 d->initialPressPosition.setX(d->initialPressPosition.x() +
1008 horizontalOffset());
1009 }
1010
1011 QListView::mousePressEvent(event);
1012
1013 viewport()->update(d->categoryVisualRect(d->hoveredCategory));
1014 }
1015
1016 void KCategorizedView::mouseReleaseEvent(QMouseEvent *event)
1017 {
1018 d->mouseButtonPressed = false;
1019
1020 QListView::mouseReleaseEvent(event);
1021
1022 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
1023 !d->categoryDrawer || !d->proxyModel->isCategorizedModel())
1024 {
1025 return;
1026 }
1027
1028 QPoint initialPressPosition = viewport()->mapFromGlobal(QCursor::pos());
1029 initialPressPosition.setY(initialPressPosition.y() + verticalOffset());
1030 initialPressPosition.setX(initialPressPosition.x() + horizontalOffset());
1031
1032 QItemSelection selection;
1033 QItemSelection deselection;
1034
1035 if (initialPressPosition == d->initialPressPosition)
1036 {
1037 foreach(const QString &category, d->categories)
1038 {
1039 if (d->categoryVisualRect(category).contains(event->pos()))
1040 {
1041 foreach (const QModelIndex &index, d->categoriesIndexes[category])
1042 {
1043 QModelIndex selectIndex = index.model()->index(index.row(), 0);
1044
1045 if (!d->lastSelection.contains(selectIndex))
1046 {
1047 selection << QItemSelectionRange(selectIndex);
1048 }
1049 else
1050 {
1051 deselection << QItemSelectionRange(selectIndex);
1052 }
1053 }
1054
1055 selectionModel()->select(selection, QItemSelectionModel::Select);
1056 selectionModel()->select(deselection, QItemSelectionModel::Deselect);
1057
1058 break;
1059 }
1060 }
1061 }
1062
1063 d->lastSelection = selectionModel()->selection();
1064
1065 if (d->hovered.isValid())
1066 viewport()->update(visualRect(d->hovered));
1067 else if (!d->hoveredCategory.isEmpty())
1068 viewport()->update(d->categoryVisualRect(d->hoveredCategory));
1069 }
1070
1071 void KCategorizedView::leaveEvent(QEvent *event)
1072 {
1073 d->hovered = QModelIndex();
1074 d->hoveredCategory = QString();
1075
1076 QListView::leaveEvent(event);
1077 }
1078
1079 void KCategorizedView::startDrag(Qt::DropActions supportedActions)
1080 {
1081 // FIXME: QAbstractItemView does far better here since it sets the
1082 // pixmap of selected icons to the dragging cursor, but it sets a non
1083 // ARGB window so it is no transparent. Use QAbstractItemView when
1084 // this is fixed on Qt.
1085 // QAbstractItemView::startDrag(supportedActions);
1086 #if !defined(DOLPHIN_DRAGANDDROP)
1087 QListView::startDrag(supportedActions);
1088 #endif
1089
1090 d->isDragging = false;
1091 d->mouseButtonPressed = false;
1092
1093 viewport()->update(d->lastDraggedItemsRect);
1094 }
1095
1096 void KCategorizedView::dragMoveEvent(QDragMoveEvent *event)
1097 {
1098 d->mousePosition = event->pos();
1099
1100 if (d->mouseButtonPressed)
1101 {
1102 d->isDragging = true;
1103 }
1104 else
1105 {
1106 d->isDragging = false;
1107 }
1108
1109 d->dragLeftViewport = false;
1110
1111 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
1112 !d->categoryDrawer || !d->proxyModel->isCategorizedModel())
1113 {
1114 #if defined(DOLPHIN_DRAGANDDROP)
1115 QAbstractItemView::dragMoveEvent(event);
1116 #else
1117 QListView::dragMoveEvent(event);
1118 #endif
1119 return;
1120 }
1121
1122 d->drawDraggedItems();
1123 }
1124
1125 void KCategorizedView::dragLeaveEvent(QDragLeaveEvent *event)
1126 {
1127 d->dragLeftViewport = true;
1128
1129 #if defined(DOLPHIN_DRAGANDDROP)
1130 QAbstractItemView::dragLeaveEvent(event);
1131 #else
1132 QListView::dragLeaveEvent(event);
1133 #endif
1134 }
1135
1136 void KCategorizedView::dropEvent(QDropEvent *event)
1137 {
1138 #if defined(DOLPHIN_DRAGANDDROP)
1139 QAbstractItemView::dropEvent(event);
1140 #else
1141 QListView::dropEvent(event);
1142 #endif
1143 }
1144
1145 QModelIndex KCategorizedView::moveCursor(CursorAction cursorAction,
1146 Qt::KeyboardModifiers modifiers)
1147 {
1148 if ((viewMode() != KCategorizedView::IconMode) ||
1149 !d->proxyModel ||
1150 !d->categoryDrawer ||
1151 d->categories.isEmpty() ||
1152 !d->proxyModel->isCategorizedModel()
1153 )
1154 {
1155 return QListView::moveCursor(cursorAction, modifiers);
1156 }
1157
1158 const QModelIndex current = selectionModel()->currentIndex();
1159
1160 int viewportWidth = viewport()->width() - spacing();
1161 int itemWidth;
1162
1163 if (gridSize().isEmpty())
1164 {
1165 itemWidth = d->biggestItemSize.width();
1166 }
1167 else
1168 {
1169 itemWidth = gridSize().width();
1170 }
1171
1172 int itemWidthPlusSeparation = spacing() + itemWidth;
1173 int elementsPerRow = viewportWidth / itemWidthPlusSeparation;
1174
1175 QString lastCategory = d->categories.first();
1176 QString theCategory = d->categories.first();
1177 QString afterCategory = d->categories.first();
1178
1179 bool hasToBreak = false;
1180 foreach (const QString &category, d->categories)
1181 {
1182 if (hasToBreak)
1183 {
1184 afterCategory = category;
1185
1186 break;
1187 }
1188
1189 if (category == d->elementsInfo[current.row()].category)
1190 {
1191 theCategory = category;
1192
1193 hasToBreak = true;
1194 }
1195
1196 if (!hasToBreak)
1197 {
1198 lastCategory = category;
1199 }
1200 }
1201
1202 switch (cursorAction)
1203 {
1204 case QAbstractItemView::MoveUp: {
1205 if (d->elementsInfo[current.row()].relativeOffsetToCategory >= elementsPerRow)
1206 {
1207 int indexToMove = current.row();
1208 indexToMove -= qMin(((d->elementsInfo[current.row()].relativeOffsetToCategory) + d->forcedSelectionPosition), elementsPerRow - d->forcedSelectionPosition + (d->elementsInfo[current.row()].relativeOffsetToCategory % elementsPerRow));
1209
1210 return d->proxyModel->index(indexToMove, 0);
1211 }
1212 else
1213 {
1214 int lastCategoryLastRow = (d->categoriesIndexes[lastCategory].count() - 1) % elementsPerRow;
1215 int indexToMove = current.row() - d->elementsInfo[current.row()].relativeOffsetToCategory;
1216
1217 if (d->forcedSelectionPosition >= lastCategoryLastRow)
1218 {
1219 indexToMove -= 1;
1220 }
1221 else
1222 {
1223 indexToMove -= qMin((lastCategoryLastRow - d->forcedSelectionPosition + 1), d->forcedSelectionPosition + elementsPerRow + 1);
1224 }
1225
1226 return d->proxyModel->index(indexToMove, 0);
1227 }
1228 }
1229
1230 case QAbstractItemView::MoveDown: {
1231 if (d->elementsInfo[current.row()].relativeOffsetToCategory < (d->categoriesIndexes[theCategory].count() - 1 - ((d->categoriesIndexes[theCategory].count() - 1) % elementsPerRow)))
1232 {
1233 int indexToMove = current.row();
1234 indexToMove += qMin(elementsPerRow, d->categoriesIndexes[theCategory].count() - 1 - d->elementsInfo[current.row()].relativeOffsetToCategory);
1235
1236 return d->proxyModel->index(indexToMove, 0);
1237 }
1238 else
1239 {
1240 int afterCategoryLastRow = qMin(elementsPerRow, d->categoriesIndexes[afterCategory].count());
1241 int indexToMove = current.row() + (d->categoriesIndexes[theCategory].count() - d->elementsInfo[current.row()].relativeOffsetToCategory);
1242
1243 if (d->forcedSelectionPosition >= afterCategoryLastRow)
1244 {
1245 indexToMove += afterCategoryLastRow - 1;
1246 }
1247 else
1248 {
1249 indexToMove += qMin(d->forcedSelectionPosition, elementsPerRow);
1250 }
1251
1252 return d->proxyModel->index(indexToMove, 0);
1253 }
1254 }
1255
1256 case QAbstractItemView::MoveLeft:
1257 if (layoutDirection() == Qt::RightToLeft)
1258 {
1259 d->forcedSelectionPosition = d->elementsInfo[current.row() + 1].relativeOffsetToCategory % elementsPerRow;
1260
1261 if (d->forcedSelectionPosition < 0)
1262 d->forcedSelectionPosition = (d->categoriesIndexes[theCategory].count() - 1) % elementsPerRow;
1263
1264 return d->proxyModel->index(current.row() + 1, 0);
1265 }
1266
1267 d->forcedSelectionPosition = d->elementsInfo[current.row() - 1].relativeOffsetToCategory % elementsPerRow;
1268
1269 if (d->forcedSelectionPosition < 0)
1270 d->forcedSelectionPosition = (d->categoriesIndexes[theCategory].count() - 1) % elementsPerRow;
1271
1272 return d->proxyModel->index(current.row() - 1, 0);
1273
1274 case QAbstractItemView::MoveRight:
1275 if (layoutDirection() == Qt::RightToLeft)
1276 {
1277 d->forcedSelectionPosition = d->elementsInfo[current.row() - 1].relativeOffsetToCategory % elementsPerRow;
1278
1279 if (d->forcedSelectionPosition < 0)
1280 d->forcedSelectionPosition = (d->categoriesIndexes[theCategory].count() - 1) % elementsPerRow;
1281
1282 return d->proxyModel->index(current.row() - 1, 0);
1283 }
1284
1285 d->forcedSelectionPosition = d->elementsInfo[current.row() + 1].relativeOffsetToCategory % elementsPerRow;
1286
1287 if (d->forcedSelectionPosition < 0)
1288 d->forcedSelectionPosition = (d->categoriesIndexes[theCategory].count() - 1) % elementsPerRow;
1289
1290 return d->proxyModel->index(current.row() + 1, 0);
1291
1292 default:
1293 break;
1294 }
1295
1296 return QListView::moveCursor(cursorAction, modifiers);
1297 }
1298
1299 void KCategorizedView::rowsInserted(const QModelIndex &parent,
1300 int start,
1301 int end)
1302 {
1303 QListView::rowsInserted(parent, start, end);
1304
1305 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
1306 !d->categoryDrawer || !d->proxyModel->isCategorizedModel())
1307 {
1308 d->lastSelection = QItemSelection();
1309 d->currentViewIndex = QModelIndex();
1310 d->forcedSelectionPosition = 0;
1311 d->elementsInfo.clear();
1312 d->elementsPosition.clear();
1313 d->categoriesIndexes.clear();
1314 d->categoriesPosition.clear();
1315 d->categories.clear();
1316 d->intersectedIndexes.clear();
1317 d->modelIndexList.clear();
1318 d->hovered = QModelIndex();
1319 d->biggestItemSize = QSize(0, 0);
1320 d->mouseButtonPressed = false;
1321
1322 return;
1323 }
1324
1325 rowsInsertedArtifficial(parent, start, end);
1326 }
1327
1328 void KCategorizedView::rowsInsertedArtifficial(const QModelIndex &parent,
1329 int start,
1330 int end)
1331 {
1332 Q_UNUSED(parent);
1333
1334 d->lastSelection = QItemSelection();
1335 d->currentViewIndex = QModelIndex();
1336 d->forcedSelectionPosition = 0;
1337 d->elementsInfo.clear();
1338 d->elementsPosition.clear();
1339 d->categoriesIndexes.clear();
1340 d->categoriesPosition.clear();
1341 d->categories.clear();
1342 d->intersectedIndexes.clear();
1343 d->modelIndexList.clear();
1344 d->hovered = QModelIndex();
1345 d->biggestItemSize = QSize(0, 0);
1346 d->mouseButtonPressed = false;
1347
1348 if (start > end || end < 0 || start < 0 || !d->proxyModel->rowCount())
1349 {
1350 return;
1351 }
1352
1353 // Add all elements mapped to the source model and explore categories
1354 QString prevCategory = d->proxyModel->data(d->proxyModel->index(0, d->proxyModel->sortColumn()), KCategorizedSortFilterProxyModel::CategoryDisplayRole).toString();
1355 QString lastCategory = prevCategory;
1356 QModelIndexList modelIndexList;
1357 struct Private::ElementInfo elementInfo;
1358 int offset = -1;
1359 for (int k = 0; k < d->proxyModel->rowCount(); ++k)
1360 {
1361 QModelIndex index = d->proxyModel->index(k, d->proxyModel->sortColumn());
1362 QModelIndex indexSize = d->proxyModel->index(k, 0);
1363
1364 d->biggestItemSize = QSize(qMax(sizeHintForIndex(indexSize).width(),
1365 d->biggestItemSize.width()),
1366 qMax(sizeHintForIndex(indexSize).height(),
1367 d->biggestItemSize.height()));
1368
1369 d->modelIndexList << index;
1370
1371 lastCategory = d->proxyModel->data(index, KCategorizedSortFilterProxyModel::CategoryDisplayRole).toString();
1372
1373 elementInfo.category = lastCategory;
1374
1375 if (prevCategory != lastCategory)
1376 {
1377 offset = 0;
1378 d->categoriesIndexes.insert(prevCategory, modelIndexList);
1379 d->categories << prevCategory;
1380 modelIndexList.clear();
1381 }
1382 else
1383 {
1384 offset++;
1385 }
1386
1387 elementInfo.relativeOffsetToCategory = offset;
1388
1389 modelIndexList << index;
1390 prevCategory = lastCategory;
1391
1392 d->elementsInfo.insert(index.row(), elementInfo);
1393 }
1394
1395 d->categoriesIndexes.insert(prevCategory, modelIndexList);
1396 d->categories << prevCategory;
1397
1398 d->updateScrollbars();
1399 }
1400
1401 void KCategorizedView::rowsRemoved(const QModelIndex &parent,
1402 int start,
1403 int end)
1404 {
1405 if ((viewMode() == KCategorizedView::IconMode) && d->proxyModel &&
1406 d->categoryDrawer && d->proxyModel->isCategorizedModel())
1407 {
1408 // Force the view to update all elements
1409 rowsInsertedArtifficial(QModelIndex(), 0, d->proxyModel->rowCount() - 1);
1410 }
1411 }
1412
1413 void KCategorizedView::updateGeometries()
1414 {
1415 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
1416 !d->categoryDrawer || !d->proxyModel->isCategorizedModel())
1417 {
1418 QListView::updateGeometries();
1419 return;
1420 }
1421
1422 // Avoid QListView::updateGeometries(), since it will try to set another
1423 // range to our scroll bars, what we don't want (ereslibre)
1424 QAbstractItemView::updateGeometries();
1425 }
1426
1427 void KCategorizedView::slotLayoutChanged()
1428 {
1429 d->layoutChanged();
1430 }
1431
1432 #include "kcategorizedview.moc"