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