]> cloud.milkyroute.net Git - dolphin.git/blob - src/kcategorizedview.cpp
Select elements correctly when clicking on the category for selecting.
[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@gmail.com>
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 <QApplication>
28 #include <QPainter>
29 #include <QScrollBar>
30 #include <QPaintEvent>
31
32 #include <kdebug.h>
33 #include <kstyle.h>
34
35 #include "kitemcategorizer.h"
36 #include "ksortfilterproxymodel.h"
37
38 class LessThan
39 {
40 public:
41 enum Purpose
42 {
43 GeneralPurpose = 0,
44 CategoryPurpose
45 };
46
47 inline LessThan(const KSortFilterProxyModel *proxyModel,
48 Purpose purpose)
49 : proxyModel(proxyModel)
50 , purpose(purpose)
51 {
52 }
53
54 inline bool operator()(const QModelIndex &left,
55 const QModelIndex &right) const
56 {
57 if (purpose == GeneralPurpose)
58 {
59 return proxyModel->sortOrder() == Qt::AscendingOrder ?
60 proxyModel->lessThanGeneralPurpose(left, right) :
61 !proxyModel->lessThanGeneralPurpose(left, right);
62 }
63
64 return proxyModel->sortOrder() == Qt::AscendingOrder ?
65 proxyModel->lessThanCategoryPurpose(left, right) :
66 !proxyModel->lessThanCategoryPurpose(left, right);
67 }
68
69 private:
70 const KSortFilterProxyModel *proxyModel;
71 const Purpose purpose;
72 };
73
74
75 //==============================================================================
76
77
78 KCategorizedView::Private::Private(KCategorizedView *listView)
79 : listView(listView)
80 , itemCategorizer(0)
81 , mouseButtonPressed(false)
82 , isDragging(false)
83 , dragLeftViewport(false)
84 , proxyModel(0)
85 , lastIndex(QModelIndex())
86 {
87 }
88
89 KCategorizedView::Private::~Private()
90 {
91 }
92
93 const QModelIndexList &KCategorizedView::Private::intersectionSet(const QRect &rect)
94 {
95 QModelIndex index;
96 QRect indexVisualRect;
97
98 intersectedIndexes.clear();
99
100 // Lets find out where we should start
101 int top = proxyModel->rowCount() - 1;
102 int bottom = 0;
103 int middle = (top + bottom) / 2;
104 while (bottom <= top)
105 {
106 middle = (top + bottom) / 2;
107
108 index = elementDictionary[proxyModel->index(middle, 0)];
109 indexVisualRect = visualRect(index);
110
111 if (qMax(indexVisualRect.topLeft().y(),
112 indexVisualRect.bottomRight().y()) < qMin(rect.topLeft().y(),
113 rect.bottomRight().y()))
114 {
115 bottom = middle + 1;
116 }
117 else
118 {
119 top = middle - 1;
120 }
121 }
122
123 for (int i = middle; i < proxyModel->rowCount(); i++)
124 {
125 index = elementDictionary[proxyModel->index(i, 0)];
126 indexVisualRect = visualRect(index);
127
128 if (rect.intersects(indexVisualRect))
129 intersectedIndexes.append(index);
130
131 // If we passed next item, stop searching for hits
132 if (qMax(rect.bottomRight().y(), rect.topLeft().y()) <
133 qMin(indexVisualRect.topLeft().y(),
134 indexVisualRect.bottomRight().y()))
135 break;
136 }
137
138 return intersectedIndexes;
139 }
140
141 QRect KCategorizedView::Private::visualRectInViewport(const QModelIndex &index) const
142 {
143 if (!index.isValid())
144 return QRect();
145
146 QString curCategory = elementsInfo[index].category;
147
148 QRect retRect(listView->spacing(), listView->spacing() * 2 +
149 itemCategorizer->categoryHeight(listView->viewOptions()), 0, 0);
150
151 int viewportWidth = listView->viewport()->width() - listView->spacing();
152
153 // We really need all items to be of same size. Otherwise we cannot do this
154 // (ereslibre)
155 // QSize itemSize =
156 // listView->sizeHintForIndex(proxyModel->mapFromSource(index));
157 // int itemHeight = itemSize.height();
158 // int itemWidth = itemSize.width();*/
159 int itemHeight = 107;
160 int itemWidth = 130;
161 int itemWidthPlusSeparation = listView->spacing() + itemWidth;
162 int elementsPerRow = viewportWidth / itemWidthPlusSeparation;
163 if (!elementsPerRow)
164 elementsPerRow++;
165
166 int column = elementsInfo[index].relativeOffsetToCategory % elementsPerRow;
167 int row = elementsInfo[index].relativeOffsetToCategory / elementsPerRow;
168
169 retRect.setLeft(retRect.left() + column * listView->spacing() +
170 column * itemWidth);
171
172 foreach (const QString &category, categories)
173 {
174 if (category == curCategory)
175 break;
176
177 float rows = (float) ((float) categoriesIndexes[category].count() /
178 (float) elementsPerRow);
179 int rowsInt = categoriesIndexes[category].count() / elementsPerRow;
180
181 if (rows - trunc(rows)) rowsInt++;
182
183 retRect.setTop(retRect.top() +
184 (rowsInt * listView->spacing()) +
185 (rowsInt * itemHeight) +
186 itemCategorizer->categoryHeight(listView->viewOptions()) +
187 listView->spacing() * 2);
188 }
189
190 retRect.setTop(retRect.top() + row * listView->spacing() +
191 row * itemHeight);
192
193 retRect.setWidth(itemWidth);
194 retRect.setHeight(itemHeight);
195
196 return retRect;
197 }
198
199 QRect KCategorizedView::Private::visualCategoryRectInViewport(const QString &category)
200 const
201 {
202 QRect retRect(listView->spacing(),
203 listView->spacing(),
204 listView->viewport()->width() - listView->spacing() * 2,
205 0);
206
207 if (!proxyModel->rowCount() || !categories.contains(category))
208 return QRect();
209
210 QModelIndex index = proxyModel->index(0, 0, QModelIndex());
211
212 int viewportWidth = listView->viewport()->width() - listView->spacing();
213
214 // We really need all items to be of same size. Otherwise we cannot do this
215 // (ereslibre)
216 // QSize itemSize = listView->sizeHintForIndex(index);
217 // int itemHeight = itemSize.height();
218 // int itemWidth = itemSize.width();
219 int itemHeight = 107;
220 int itemWidth = 130;
221 int itemWidthPlusSeparation = listView->spacing() + itemWidth;
222 int elementsPerRow = viewportWidth / itemWidthPlusSeparation;
223
224 if (!elementsPerRow)
225 elementsPerRow++;
226
227 foreach (const QString &itCategory, categories)
228 {
229 if (itCategory == category)
230 break;
231
232 float rows = (float) ((float) categoriesIndexes[itCategory].count() /
233 (float) elementsPerRow);
234 int rowsInt = categoriesIndexes[itCategory].count() / elementsPerRow;
235
236 if (rows - trunc(rows)) rowsInt++;
237
238 retRect.setTop(retRect.top() +
239 (rowsInt * listView->spacing()) +
240 (rowsInt * itemHeight) +
241 itemCategorizer->categoryHeight(listView->viewOptions()) +
242 listView->spacing() * 2);
243 }
244
245 retRect.setHeight(itemCategorizer->categoryHeight(listView->viewOptions()));
246
247 return retRect;
248 }
249
250 // We're sure elementsPosition doesn't contain index
251 const QRect &KCategorizedView::Private::cacheIndex(const QModelIndex &index)
252 {
253 QRect rect = visualRectInViewport(index);
254 elementsPosition[index] = rect;
255
256 return elementsPosition[index];
257 }
258
259 // We're sure categoriesPosition doesn't contain category
260 const QRect &KCategorizedView::Private::cacheCategory(const QString &category)
261 {
262 QRect rect = visualCategoryRectInViewport(category);
263 categoriesPosition[category] = rect;
264
265 return categoriesPosition[category];
266 }
267
268 const QRect &KCategorizedView::Private::cachedRectIndex(const QModelIndex &index)
269 {
270 if (elementsPosition.contains(index)) // If we have it cached
271 { // return it
272 return elementsPosition[index];
273 }
274 else // Otherwise, cache it
275 { // and return it
276 return cacheIndex(index);
277 }
278 }
279
280 const QRect &KCategorizedView::Private::cachedRectCategory(const QString &category)
281 {
282 if (categoriesPosition.contains(category)) // If we have it cached
283 { // return it
284 return categoriesPosition[category];
285 }
286 else // Otherwise, cache it and
287 { // return it
288 return cacheCategory(category);
289 }
290 }
291
292 QRect KCategorizedView::Private::visualRect(const QModelIndex &index)
293 {
294 QModelIndex mappedIndex = proxyModel->mapToSource(index);
295
296 QRect retRect = cachedRectIndex(mappedIndex);
297 int dx = -listView->horizontalOffset();
298 int dy = -listView->verticalOffset();
299 retRect.adjust(dx, dy, dx, dy);
300
301 return retRect;
302 }
303
304 QRect KCategorizedView::Private::categoryVisualRect(const QString &category)
305 {
306 QRect retRect = cachedRectCategory(category);
307 int dx = -listView->horizontalOffset();
308 int dy = -listView->verticalOffset();
309 retRect.adjust(dx, dy, dx, dy);
310
311 return retRect;
312 }
313
314 void KCategorizedView::Private::drawNewCategory(const QModelIndex &index,
315 int sortRole,
316 const QStyleOption &option,
317 QPainter *painter)
318 {
319 QStyleOption optionCopy = option;
320 const QString category = itemCategorizer->categoryForItem(index, sortRole);
321
322 if ((category == hoveredCategory) && !mouseButtonPressed)
323 {
324 optionCopy.state |= QStyle::State_MouseOver;
325 }
326
327 itemCategorizer->drawCategory(index,
328 sortRole,
329 optionCopy,
330 painter);
331 }
332
333
334 void KCategorizedView::Private::updateScrollbars()
335 {
336 int lastItemBottom = cachedRectIndex(lastIndex).bottom() +
337 listView->spacing() - listView->viewport()->height();
338
339 listView->verticalScrollBar()->setSingleStep(listView->viewport()->height() / 10);
340 listView->verticalScrollBar()->setPageStep(listView->viewport()->height());
341 listView->verticalScrollBar()->setRange(0, lastItemBottom);
342 }
343
344 void KCategorizedView::Private::drawDraggedItems(QPainter *painter)
345 {
346 QStyleOptionViewItemV3 option = listView->viewOptions();
347 option.state &= ~QStyle::State_MouseOver;
348 foreach (const QModelIndex &index, listView->selectionModel()->selectedIndexes())
349 {
350 const int dx = mousePosition.x() - initialPressPosition.x() + listView->horizontalOffset();
351 const int dy = mousePosition.y() - initialPressPosition.y() + listView->verticalOffset();
352
353 option.rect = visualRect(index);
354 option.rect.adjust(dx, dy, dx, dy);
355
356 if (option.rect.intersects(listView->viewport()->rect()))
357 {
358 listView->itemDelegate(index)->paint(painter, option, index);
359 }
360 }
361 }
362
363 void KCategorizedView::Private::drawDraggedItems()
364 {
365 QRect rectToUpdate;
366 QRect currentRect;
367 foreach (const QModelIndex &index, listView->selectionModel()->selectedIndexes())
368 {
369 int dx = mousePosition.x() - initialPressPosition.x() + listView->horizontalOffset();
370 int dy = mousePosition.y() - initialPressPosition.y() + listView->verticalOffset();
371
372 currentRect = visualRect(index);
373 currentRect.adjust(dx, dy, dx, dy);
374
375 if (currentRect.intersects(listView->viewport()->rect()))
376 {
377 rectToUpdate = rectToUpdate.united(currentRect);
378 }
379 }
380
381 listView->viewport()->update(lastDraggedItemsRect.united(rectToUpdate));
382
383 lastDraggedItemsRect = rectToUpdate;
384 }
385
386
387 //==============================================================================
388
389
390 KCategorizedView::KCategorizedView(QWidget *parent)
391 : QListView(parent)
392 , d(new Private(this))
393 {
394 }
395
396 KCategorizedView::~KCategorizedView()
397 {
398 delete d;
399 }
400
401 void KCategorizedView::setModel(QAbstractItemModel *model)
402 {
403 d->lastSelection = QItemSelection();
404 d->currentViewIndex = QModelIndex();
405 d->forcedSelectionPosition = 0;
406 d->elementsInfo.clear();
407 d->elementsPosition.clear();
408 d->elementDictionary.clear();
409 d->invertedElementDictionary.clear();
410 d->categoriesIndexes.clear();
411 d->categoriesPosition.clear();
412 d->categories.clear();
413 d->intersectedIndexes.clear();
414 d->sourceModelIndexList.clear();
415 d->hovered = QModelIndex();
416 d->mouseButtonPressed = false;
417
418 if (d->proxyModel)
419 {
420 QObject::disconnect(d->proxyModel,
421 SIGNAL(rowsRemoved(QModelIndex,int,int)),
422 this, SLOT(rowsRemoved(QModelIndex,int,int)));
423
424 QObject::disconnect(d->proxyModel,
425 SIGNAL(sortingRoleChanged()),
426 this, SLOT(slotSortingRoleChanged()));
427 }
428
429 QListView::setModel(model);
430
431 d->proxyModel = dynamic_cast<KSortFilterProxyModel*>(model);
432
433 if (d->proxyModel)
434 {
435 QObject::connect(d->proxyModel,
436 SIGNAL(rowsRemoved(QModelIndex,int,int)),
437 this, SLOT(rowsRemoved(QModelIndex,int,int)));
438
439 QObject::connect(d->proxyModel,
440 SIGNAL(sortingRoleChanged()),
441 this, SLOT(slotSortingRoleChanged()));
442 }
443 }
444
445 QRect KCategorizedView::visualRect(const QModelIndex &index) const
446 {
447 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
448 !d->itemCategorizer)
449 {
450 return QListView::visualRect(index);
451 }
452
453 if (!qobject_cast<const QSortFilterProxyModel*>(index.model()))
454 {
455 return d->visualRect(d->proxyModel->mapFromSource(index));
456 }
457
458 return d->visualRect(index);
459 }
460
461 KItemCategorizer *KCategorizedView::itemCategorizer() const
462 {
463 return d->itemCategorizer;
464 }
465
466 void KCategorizedView::setItemCategorizer(KItemCategorizer *itemCategorizer)
467 {
468 d->lastSelection = QItemSelection();
469 d->currentViewIndex = QModelIndex();
470 d->forcedSelectionPosition = 0;
471 d->elementsInfo.clear();
472 d->elementsPosition.clear();
473 d->elementDictionary.clear();
474 d->invertedElementDictionary.clear();
475 d->categoriesIndexes.clear();
476 d->categoriesPosition.clear();
477 d->categories.clear();
478 d->intersectedIndexes.clear();
479 d->sourceModelIndexList.clear();
480 d->hovered = QModelIndex();
481 d->mouseButtonPressed = false;
482
483 if (!itemCategorizer && d->proxyModel)
484 {
485 QObject::disconnect(d->proxyModel,
486 SIGNAL(rowsRemoved(QModelIndex,int,int)),
487 this, SLOT(rowsRemoved(QModelIndex,int,int)));
488
489 QObject::disconnect(d->proxyModel,
490 SIGNAL(sortingRoleChanged()),
491 this, SLOT(slotSortingRoleChanged()));
492 }
493 else if (itemCategorizer && d->proxyModel)
494 {
495 QObject::connect(d->proxyModel,
496 SIGNAL(rowsRemoved(QModelIndex,int,int)),
497 this, SLOT(rowsRemoved(QModelIndex,int,int)));
498
499 QObject::connect(d->proxyModel,
500 SIGNAL(sortingRoleChanged()),
501 this, SLOT(slotSortingRoleChanged()));
502 }
503
504 d->itemCategorizer = itemCategorizer;
505
506 if (itemCategorizer)
507 {
508 rowsInserted(QModelIndex(), 0, d->proxyModel->rowCount() - 1);
509 }
510 else
511 {
512 updateGeometries();
513 }
514 }
515
516 QModelIndex KCategorizedView::indexAt(const QPoint &point) const
517 {
518 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
519 !d->itemCategorizer)
520 {
521 return QListView::indexAt(point);
522 }
523
524 QModelIndex index;
525
526 QModelIndexList item = d->intersectionSet(QRect(point, point));
527
528 if (item.count() == 1)
529 {
530 index = item[0];
531 }
532
533 d->hovered = index;
534
535 return index;
536 }
537
538 void KCategorizedView::reset()
539 {
540 QListView::reset();
541
542 d->lastSelection = QItemSelection();
543 d->currentViewIndex = QModelIndex();
544 d->forcedSelectionPosition = 0;
545 d->elementsInfo.clear();
546 d->elementsPosition.clear();
547 d->elementDictionary.clear();
548 d->invertedElementDictionary.clear();
549 d->categoriesIndexes.clear();
550 d->categoriesPosition.clear();
551 d->categories.clear();
552 d->intersectedIndexes.clear();
553 d->sourceModelIndexList.clear();
554 d->hovered = QModelIndex();
555 d->mouseButtonPressed = false;
556 }
557
558 void KCategorizedView::paintEvent(QPaintEvent *event)
559 {
560 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
561 !d->itemCategorizer)
562 {
563 QListView::paintEvent(event);
564 return;
565 }
566
567 QStyleOptionViewItemV3 option = viewOptions();
568 option.widget = this;
569 QPainter painter(viewport());
570 QRect area = event->rect();
571 const bool focus = (hasFocus() || viewport()->hasFocus()) &&
572 currentIndex().isValid();
573 const QStyle::State state = option.state;
574 const bool enabled = (state & QStyle::State_Enabled) != 0;
575
576 painter.save();
577
578 QModelIndexList dirtyIndexes = d->intersectionSet(area);
579 foreach (const QModelIndex &index, dirtyIndexes)
580 {
581 option.state = state;
582 option.rect = d->visualRect(index);
583
584 if (selectionModel() && selectionModel()->isSelected(index))
585 {
586 option.state |= QStyle::State_Selected;
587 }
588
589 if (enabled)
590 {
591 QPalette::ColorGroup cg;
592 if ((d->proxyModel->flags(index) & Qt::ItemIsEnabled) == 0)
593 {
594 option.state &= ~QStyle::State_Enabled;
595 cg = QPalette::Disabled;
596 }
597 else
598 {
599 cg = QPalette::Normal;
600 }
601 option.palette.setCurrentColorGroup(cg);
602 }
603
604 if (focus && currentIndex() == index)
605 {
606 option.state |= QStyle::State_HasFocus;
607 if (this->state() == EditingState)
608 option.state |= QStyle::State_Editing;
609 }
610
611 if ((index == d->hovered) && !d->mouseButtonPressed)
612 option.state |= QStyle::State_MouseOver;
613 else
614 option.state &= ~QStyle::State_MouseOver;
615
616 itemDelegate(index)->paint(&painter, option, index);
617 }
618
619 // Redraw categories
620 int i = 0;
621 QStyleOptionViewItem otherOption;
622 foreach (const QString &category, d->categories)
623 {
624 otherOption = option;
625 otherOption.rect = d->categoryVisualRect(category);
626 otherOption.state &= ~QStyle::State_MouseOver;
627
628 if (otherOption.rect.intersects(area))
629 {
630 d->drawNewCategory(d->categoriesIndexes[category][0],
631 d->proxyModel->sortRole(), otherOption, &painter);
632 }
633 }
634
635 if (d->mouseButtonPressed && !d->isDragging)
636 {
637 QPoint start, end, initialPressPosition;
638
639 initialPressPosition = d->initialPressPosition;
640
641 initialPressPosition.setY(initialPressPosition.y() - verticalOffset());
642 initialPressPosition.setX(initialPressPosition.x() - horizontalOffset());
643
644 if (d->initialPressPosition.x() > d->mousePosition.x() ||
645 d->initialPressPosition.y() > d->mousePosition.y())
646 {
647 start = d->mousePosition;
648 end = initialPressPosition;
649 }
650 else
651 {
652 start = initialPressPosition;
653 end = d->mousePosition;
654 }
655
656 QStyleOptionRubberBand yetAnotherOption;
657 yetAnotherOption.initFrom(this);
658 yetAnotherOption.shape = QRubberBand::Rectangle;
659 yetAnotherOption.opaque = false;
660 yetAnotherOption.rect = QRect(start, end).intersected(viewport()->rect().adjusted(-16, -16, 16, 16));
661 painter.save();
662 style()->drawControl(QStyle::CE_RubberBand, &yetAnotherOption, &painter);
663 painter.restore();
664 }
665
666 if (d->isDragging && !d->dragLeftViewport)
667 {
668 painter.setOpacity(0.5);
669 d->drawDraggedItems(&painter);
670 }
671
672 painter.restore();
673 }
674
675 void KCategorizedView::resizeEvent(QResizeEvent *event)
676 {
677 QListView::resizeEvent(event);
678
679 // Clear the items positions cache
680 d->elementsPosition.clear();
681 d->categoriesPosition.clear();
682 d->forcedSelectionPosition = 0;
683
684 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
685 !d->itemCategorizer)
686 {
687 return;
688 }
689
690 d->updateScrollbars();
691 }
692
693 void KCategorizedView::setSelection(const QRect &rect,
694 QItemSelectionModel::SelectionFlags flags)
695 {
696 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
697 !d->itemCategorizer)
698 {
699 QListView::setSelection(rect, flags);
700 return;
701 }
702
703 if (!flags)
704 return;
705
706 selectionModel()->clear();
707
708 if (flags & QItemSelectionModel::Clear)
709 {
710 d->lastSelection = QItemSelection();
711 }
712
713 QModelIndexList dirtyIndexes = d->intersectionSet(rect);
714
715 QItemSelection selection;
716
717 if (!dirtyIndexes.count())
718 {
719 if (d->lastSelection.count())
720 {
721 selectionModel()->select(d->lastSelection, flags);
722 }
723
724 return;
725 }
726
727 if (!d->mouseButtonPressed)
728 {
729 selection = QItemSelection(dirtyIndexes[0], dirtyIndexes[0]);
730 d->currentViewIndex = dirtyIndexes[0];
731 }
732 else
733 {
734 QModelIndex first = dirtyIndexes[0];
735 QModelIndex last;
736 foreach (const QModelIndex &index, dirtyIndexes)
737 {
738 if (last.isValid() && last.row() + 1 != index.row())
739 {
740 QItemSelectionRange range(first, last);
741
742 selection << range;
743
744 first = index;
745 }
746
747 last = index;
748 }
749
750 if (last.isValid())
751 selection << QItemSelectionRange(first, last);
752 }
753
754 if (d->lastSelection.count() && !d->mouseButtonPressed)
755 {
756 selection.merge(d->lastSelection, flags);
757 }
758 else if (d->lastSelection.count())
759 {
760 selection.merge(d->lastSelection, QItemSelectionModel::Select);
761 }
762
763 selectionModel()->select(selection, flags);
764 }
765
766 void KCategorizedView::mouseMoveEvent(QMouseEvent *event)
767 {
768 QListView::mouseMoveEvent(event);
769
770 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
771 !d->itemCategorizer)
772 {
773 return;
774 }
775
776 const QString previousHoveredCategory = d->hoveredCategory;
777
778 d->mousePosition = event->pos();
779 d->hoveredCategory = QString();
780
781 // Redraw categories
782 foreach (const QString &category, d->categories)
783 {
784 if (d->categoryVisualRect(category).intersects(QRect(event->pos(), event->pos())))
785 {
786 d->hoveredCategory = category;
787 viewport()->update(d->categoryVisualRect(category));
788 }
789 else if ((category == previousHoveredCategory) &&
790 (!d->categoryVisualRect(previousHoveredCategory).intersects(QRect(event->pos(), event->pos()))))
791 {
792 viewport()->update(d->categoryVisualRect(category));
793 }
794 }
795
796 QRect rect;
797 if (d->mouseButtonPressed && !d->isDragging)
798 {
799 QPoint start, end, initialPressPosition;
800
801 initialPressPosition = d->initialPressPosition;
802
803 initialPressPosition.setY(initialPressPosition.y() - verticalOffset());
804 initialPressPosition.setX(initialPressPosition.x() - horizontalOffset());
805
806 if (d->initialPressPosition.x() > d->mousePosition.x() ||
807 d->initialPressPosition.y() > d->mousePosition.y())
808 {
809 start = d->mousePosition;
810 end = initialPressPosition;
811 }
812 else
813 {
814 start = initialPressPosition;
815 end = d->mousePosition;
816 }
817
818 rect = QRect(start, end).intersected(viewport()->rect().adjusted(-16, -16, 16, 16));
819
820 //viewport()->update(rect.united(d->lastSelectionRect));
821
822 d->lastSelectionRect = rect;
823 }
824 }
825
826 void KCategorizedView::mousePressEvent(QMouseEvent *event)
827 {
828 d->dragLeftViewport = false;
829
830 if (event->button() == Qt::LeftButton)
831 {
832 d->mouseButtonPressed = true;
833
834 d->initialPressPosition = event->pos();
835 d->initialPressPosition.setY(d->initialPressPosition.y() +
836 verticalOffset());
837 d->initialPressPosition.setX(d->initialPressPosition.x() +
838 horizontalOffset());
839 }
840
841 QListView::mousePressEvent(event);
842 }
843
844 void KCategorizedView::mouseReleaseEvent(QMouseEvent *event)
845 {
846 d->mouseButtonPressed = false;
847
848 QListView::mouseReleaseEvent(event);
849
850 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
851 !d->itemCategorizer)
852 {
853 return;
854 }
855
856 QPoint initialPressPosition = viewport()->mapFromGlobal(QCursor::pos());
857 initialPressPosition.setY(initialPressPosition.y() + verticalOffset());
858 initialPressPosition.setX(initialPressPosition.x() + horizontalOffset());
859
860 QItemSelection selection;
861
862 if (initialPressPosition == d->initialPressPosition)
863 {
864 foreach(const QString &category, d->categories)
865 {
866 if (d->categoryVisualRect(category).contains(event->pos()))
867 {
868 foreach (const QModelIndex &index, d->categoriesIndexes[category])
869 {
870 selection << QItemSelectionRange(d->proxyModel->mapFromSource(index));
871 }
872
873 selectionModel()->select(selection, QItemSelectionModel::Select);
874
875 break;
876 }
877 }
878 }
879
880 d->lastSelection = selectionModel()->selection();
881
882 if (d->hovered.isValid())
883 viewport()->update(d->visualRect(d->hovered));
884 else if (!d->hoveredCategory.isEmpty())
885 viewport()->update(d->categoryVisualRect(d->hoveredCategory));
886 }
887
888 void KCategorizedView::leaveEvent(QEvent *event)
889 {
890 d->hovered = QModelIndex();
891 d->hoveredCategory = QString();
892
893 QListView::leaveEvent(event);
894 }
895
896 void KCategorizedView::startDrag(Qt::DropActions supportedActions)
897 {
898 QListView::startDrag(supportedActions);
899
900 d->isDragging = false;
901 d->mouseButtonPressed = false;
902
903 viewport()->update(d->lastDraggedItemsRect);
904 }
905
906 void KCategorizedView::dragMoveEvent(QDragMoveEvent *event)
907 {
908 d->mousePosition = event->pos();
909
910 if (d->mouseButtonPressed)
911 {
912 d->isDragging = true;
913 }
914 else
915 {
916 d->isDragging = false;
917 }
918
919 d->dragLeftViewport = false;
920
921 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
922 !d->itemCategorizer)
923 {
924 QListView::dragMoveEvent(event);
925 return;
926 }
927
928 d->drawDraggedItems();
929 }
930
931 void KCategorizedView::dragLeaveEvent(QDragLeaveEvent *event)
932 {
933 d->dragLeftViewport = true;
934
935 QListView::dragLeaveEvent(event);
936 }
937
938 QModelIndex KCategorizedView::moveCursor(CursorAction cursorAction,
939 Qt::KeyboardModifiers modifiers)
940 {
941 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
942 !d->itemCategorizer)
943 {
944 return QListView::moveCursor(cursorAction, modifiers);
945 }
946
947 const QModelIndex current = selectionModel()->currentIndex();
948
949 int viewportWidth = viewport()->width() - spacing();
950 // We really need all items to be of same size. Otherwise we cannot do this
951 // (ereslibre)
952 // QSize itemSize = listView->sizeHintForIndex(index);
953 // int itemHeight = itemSize.height();
954 // int itemWidth = itemSize.width();
955 int itemHeight = 107;
956 int itemWidth = 130;
957 int itemWidthPlusSeparation = spacing() + itemWidth;
958 int elementsPerRow = viewportWidth / itemWidthPlusSeparation;
959
960 QString lastCategory = d->categories[0];
961 QString theCategory = d->categories[0];
962 QString afterCategory = d->categories[0];
963 bool hasToBreak = false;
964 foreach (const QString &category, d->categories)
965 {
966 if (hasToBreak)
967 {
968 afterCategory = category;
969
970 break;
971 }
972
973 if (category == d->elementsInfo[d->proxyModel->mapToSource(current)].category)
974 {
975 theCategory = category;
976
977 hasToBreak = true;
978 }
979
980 if (!hasToBreak)
981 {
982 lastCategory = category;
983 }
984 }
985
986 switch (cursorAction)
987 {
988 case QAbstractItemView::MoveUp: {
989 if (d->elementsInfo[d->proxyModel->mapToSource(current)].relativeOffsetToCategory >= elementsPerRow)
990 {
991 int indexToMove = d->invertedElementDictionary[current].row();
992 indexToMove -= qMin(((d->elementsInfo[d->proxyModel->mapToSource(current)].relativeOffsetToCategory) + d->forcedSelectionPosition), elementsPerRow - d->forcedSelectionPosition + (d->elementsInfo[d->proxyModel->mapToSource(current)].relativeOffsetToCategory % elementsPerRow));
993
994 return d->elementDictionary[d->proxyModel->index(indexToMove, 0)];
995 }
996 else
997 {
998 int lastCategoryLastRow = (d->categoriesIndexes[lastCategory].count() - 1) % elementsPerRow;
999 int indexToMove = d->invertedElementDictionary[current].row() - d->elementsInfo[d->proxyModel->mapToSource(current)].relativeOffsetToCategory;
1000
1001 if (d->forcedSelectionPosition >= lastCategoryLastRow)
1002 {
1003 indexToMove -= 1;
1004 }
1005 else
1006 {
1007 indexToMove -= qMin((lastCategoryLastRow - d->forcedSelectionPosition + 1), d->forcedSelectionPosition + elementsPerRow + 1);
1008 }
1009
1010 return d->elementDictionary[d->proxyModel->index(indexToMove, 0)];
1011 }
1012 }
1013
1014 case QAbstractItemView::MoveDown: {
1015 if (d->elementsInfo[d->proxyModel->mapToSource(current)].relativeOffsetToCategory < (d->categoriesIndexes[theCategory].count() - 1 - ((d->categoriesIndexes[theCategory].count() - 1) % elementsPerRow)))
1016 {
1017 int indexToMove = d->invertedElementDictionary[current].row();
1018 indexToMove += qMin(elementsPerRow, d->categoriesIndexes[theCategory].count() - 1 - d->elementsInfo[d->proxyModel->mapToSource(current)].relativeOffsetToCategory);
1019
1020 return d->elementDictionary[d->proxyModel->index(indexToMove, 0)];
1021 }
1022 else
1023 {
1024 int afterCategoryLastRow = qMin(elementsPerRow, d->categoriesIndexes[afterCategory].count());
1025 int indexToMove = d->invertedElementDictionary[current].row() + (d->categoriesIndexes[theCategory].count() - d->elementsInfo[d->proxyModel->mapToSource(current)].relativeOffsetToCategory);
1026
1027 if (d->forcedSelectionPosition >= afterCategoryLastRow)
1028 {
1029 indexToMove += afterCategoryLastRow - 1;
1030 }
1031 else
1032 {
1033 indexToMove += qMin(d->forcedSelectionPosition, elementsPerRow);
1034 }
1035
1036 return d->elementDictionary[d->proxyModel->index(indexToMove, 0)];
1037 }
1038 }
1039
1040 case QAbstractItemView::MoveLeft:
1041 d->forcedSelectionPosition = d->elementsInfo[d->proxyModel->mapToSource(d->elementDictionary[d->proxyModel->index(d->invertedElementDictionary[current].row() - 1, 0)])].relativeOffsetToCategory % elementsPerRow;
1042
1043 if (d->forcedSelectionPosition < 0)
1044 d->forcedSelectionPosition = (d->categoriesIndexes[theCategory].count() - 1) % elementsPerRow;
1045
1046 return d->elementDictionary[d->proxyModel->index(d->invertedElementDictionary[current].row() - 1, 0)];
1047
1048 case QAbstractItemView::MoveRight:
1049 d->forcedSelectionPosition = d->elementsInfo[d->proxyModel->mapToSource(d->elementDictionary[d->proxyModel->index(d->invertedElementDictionary[current].row() + 1, 0)])].relativeOffsetToCategory % elementsPerRow;
1050
1051 if (d->forcedSelectionPosition < 0)
1052 d->forcedSelectionPosition = (d->categoriesIndexes[theCategory].count() - 1) % elementsPerRow;
1053
1054 return d->elementDictionary[d->proxyModel->index(d->invertedElementDictionary[current].row() + 1, 0)];
1055
1056 default:
1057 break;
1058 }
1059
1060 return QListView::moveCursor(cursorAction, modifiers);
1061 }
1062
1063 void KCategorizedView::rowsInserted(const QModelIndex &parent,
1064 int start,
1065 int end)
1066 {
1067 QListView::rowsInserted(parent, start, end);
1068
1069 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
1070 !d->itemCategorizer)
1071 {
1072 d->lastSelection = QItemSelection();
1073 d->currentViewIndex = QModelIndex();
1074 d->forcedSelectionPosition = 0;
1075 d->elementsInfo.clear();
1076 d->elementsPosition.clear();
1077 d->elementDictionary.clear();
1078 d->invertedElementDictionary.clear();
1079 d->categoriesIndexes.clear();
1080 d->categoriesPosition.clear();
1081 d->categories.clear();
1082 d->intersectedIndexes.clear();
1083 d->sourceModelIndexList.clear();
1084 d->hovered = QModelIndex();
1085 d->mouseButtonPressed = false;
1086
1087 return;
1088 }
1089
1090 rowsInsertedArtifficial(parent, start, end);
1091 }
1092
1093 void KCategorizedView::rowsInsertedArtifficial(const QModelIndex &parent,
1094 int start,
1095 int end)
1096 {
1097 Q_UNUSED(parent);
1098
1099 d->lastSelection = QItemSelection();
1100 d->currentViewIndex = QModelIndex();
1101 d->forcedSelectionPosition = 0;
1102 d->elementsInfo.clear();
1103 d->elementsPosition.clear();
1104 d->elementDictionary.clear();
1105 d->invertedElementDictionary.clear();
1106 d->categoriesIndexes.clear();
1107 d->categoriesPosition.clear();
1108 d->categories.clear();
1109 d->intersectedIndexes.clear();
1110 d->sourceModelIndexList.clear();
1111 d->hovered = QModelIndex();
1112 d->mouseButtonPressed = false;
1113
1114 if (start > end || end < 0 || start < 0 || !d->proxyModel->rowCount())
1115 {
1116 return;
1117 }
1118
1119 // Add all elements mapped to the source model
1120 for (int k = 0; k < d->proxyModel->rowCount(); k++)
1121 {
1122 d->sourceModelIndexList <<
1123 d->proxyModel->mapToSource(d->proxyModel->index(k, 0));
1124 }
1125
1126 // Sort them with the general purpose lessThan method
1127 LessThan generalLessThan(d->proxyModel,
1128 LessThan::GeneralPurpose);
1129
1130 qStableSort(d->sourceModelIndexList.begin(), d->sourceModelIndexList.end(),
1131 generalLessThan);
1132
1133 // Explore categories
1134 QString prevCategory =
1135 d->itemCategorizer->categoryForItem(d->sourceModelIndexList[0],
1136 d->proxyModel->sortRole());
1137 QString lastCategory = prevCategory;
1138 QModelIndexList modelIndexList;
1139 struct Private::ElementInfo elementInfo;
1140 foreach (const QModelIndex &index, d->sourceModelIndexList)
1141 {
1142 lastCategory = d->itemCategorizer->categoryForItem(index,
1143 d->proxyModel->sortRole());
1144
1145 elementInfo.category = lastCategory;
1146
1147 if (prevCategory != lastCategory)
1148 {
1149 d->categoriesIndexes.insert(prevCategory, modelIndexList);
1150 d->categories << prevCategory;
1151 modelIndexList.clear();
1152 }
1153
1154 modelIndexList << index;
1155 prevCategory = lastCategory;
1156
1157 d->elementsInfo.insert(index, elementInfo);
1158 }
1159
1160 d->categoriesIndexes.insert(prevCategory, modelIndexList);
1161 d->categories << prevCategory;
1162
1163 // Sort items locally in their respective categories with the category
1164 // purpose lessThan
1165 LessThan categoryLessThan(d->proxyModel,
1166 LessThan::CategoryPurpose);
1167
1168 foreach (const QString &key, d->categories)
1169 {
1170 QModelIndexList &indexList = d->categoriesIndexes[key];
1171
1172 qStableSort(indexList.begin(), indexList.end(), categoryLessThan);
1173 }
1174
1175 d->lastIndex = d->categoriesIndexes[d->categories[d->categories.count() - 1]][d->categoriesIndexes[d->categories[d->categories.count() - 1]].count() - 1];
1176
1177 // Finally, fill data information of items situation. This will help when
1178 // trying to compute an item place in the viewport
1179 int i = 0; // position relative to the category beginning
1180 int j = 0; // number of elements before current
1181 foreach (const QString &key, d->categories)
1182 {
1183 foreach (const QModelIndex &index, d->categoriesIndexes[key])
1184 {
1185 struct Private::ElementInfo &elementInfo = d->elementsInfo[index];
1186
1187 elementInfo.relativeOffsetToCategory = i;
1188
1189 d->elementDictionary.insert(d->proxyModel->index(j, 0),
1190 d->proxyModel->mapFromSource(index));
1191
1192 d->invertedElementDictionary.insert(d->proxyModel->mapFromSource(index),
1193 d->proxyModel->index(j, 0));
1194
1195 i++;
1196 j++;
1197 }
1198
1199 i = 0;
1200 }
1201
1202 d->updateScrollbars();
1203 }
1204
1205 void KCategorizedView::rowsRemoved(const QModelIndex &parent,
1206 int start,
1207 int end)
1208 {
1209 if ((viewMode() == KCategorizedView::IconMode) && d->proxyModel &&
1210 d->itemCategorizer)
1211 {
1212 // Force the view to update all elements
1213 rowsInsertedArtifficial(parent, start, end);
1214 }
1215 }
1216
1217 void KCategorizedView::updateGeometries()
1218 {
1219 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
1220 !d->itemCategorizer)
1221 {
1222 QListView::updateGeometries();
1223 return;
1224 }
1225
1226 // Avoid QListView::updateGeometries(), since it will try to set another
1227 // range to our scroll bars, what we don't want (ereslibre)
1228 QAbstractItemView::updateGeometries();
1229 }
1230
1231 void KCategorizedView::slotSortingRoleChanged()
1232 {
1233 if ((viewMode() == KCategorizedView::IconMode) && d->proxyModel &&
1234 d->itemCategorizer)
1235 {
1236 // Force the view to update all elements
1237 rowsInsertedArtifficial(QModelIndex(), 0, d->proxyModel->rowCount() - 1);
1238 }
1239 }
1240
1241 #include "kcategorizedview.moc"