]> cloud.milkyroute.net Git - dolphin.git/blob - src/kcategorizedview.cpp
remove unused variables
[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->biggestItemSize = QSize(0, 0);
546 d->mouseButtonPressed = false;
547 }
548
549 void KCategorizedView::paintEvent(QPaintEvent *event)
550 {
551 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
552 !d->itemCategorizer)
553 {
554 QListView::paintEvent(event);
555 return;
556 }
557
558 QStyleOptionViewItemV3 option = viewOptions();
559 option.widget = this;
560 QPainter painter(viewport());
561 QRect area = event->rect();
562 const bool focus = (hasFocus() || viewport()->hasFocus()) &&
563 currentIndex().isValid();
564 const QStyle::State state = option.state;
565 const bool enabled = (state & QStyle::State_Enabled) != 0;
566
567 painter.save();
568
569 QModelIndexList dirtyIndexes = d->intersectionSet(area);
570 foreach (const QModelIndex &index, dirtyIndexes)
571 {
572 option.state = state;
573 option.rect = d->visualRect(index);
574
575 if (selectionModel() && selectionModel()->isSelected(index))
576 {
577 option.state |= QStyle::State_Selected;
578 }
579
580 if (enabled)
581 {
582 QPalette::ColorGroup cg;
583 if ((d->proxyModel->flags(index) & Qt::ItemIsEnabled) == 0)
584 {
585 option.state &= ~QStyle::State_Enabled;
586 cg = QPalette::Disabled;
587 }
588 else
589 {
590 cg = QPalette::Normal;
591 }
592 option.palette.setCurrentColorGroup(cg);
593 }
594
595 if (focus && currentIndex() == index)
596 {
597 option.state |= QStyle::State_HasFocus;
598 if (this->state() == EditingState)
599 option.state |= QStyle::State_Editing;
600 }
601
602 if ((index == d->hovered) && !d->mouseButtonPressed)
603 option.state |= QStyle::State_MouseOver;
604 else
605 option.state &= ~QStyle::State_MouseOver;
606
607 itemDelegate(index)->paint(&painter, option, index);
608 }
609
610 // Redraw categories
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 itemWidth = d->biggestItemSize.width();
941 int itemWidthPlusSeparation = spacing() + itemWidth;
942 int elementsPerRow = viewportWidth / itemWidthPlusSeparation;
943
944 QString lastCategory = d->categories[0];
945 QString theCategory = d->categories[0];
946 QString afterCategory = d->categories[0];
947 bool hasToBreak = false;
948 foreach (const QString &category, d->categories)
949 {
950 if (hasToBreak)
951 {
952 afterCategory = category;
953
954 break;
955 }
956
957 if (category == d->elementsInfo[d->proxyModel->mapToSource(current)].category)
958 {
959 theCategory = category;
960
961 hasToBreak = true;
962 }
963
964 if (!hasToBreak)
965 {
966 lastCategory = category;
967 }
968 }
969
970 switch (cursorAction)
971 {
972 case QAbstractItemView::MoveUp: {
973 if (d->elementsInfo[d->proxyModel->mapToSource(current)].relativeOffsetToCategory >= elementsPerRow)
974 {
975 int indexToMove = d->invertedElementDictionary[current].row();
976 indexToMove -= qMin(((d->elementsInfo[d->proxyModel->mapToSource(current)].relativeOffsetToCategory) + d->forcedSelectionPosition), elementsPerRow - d->forcedSelectionPosition + (d->elementsInfo[d->proxyModel->mapToSource(current)].relativeOffsetToCategory % elementsPerRow));
977
978 return d->elementDictionary[d->proxyModel->index(indexToMove, 0)];
979 }
980 else
981 {
982 int lastCategoryLastRow = (d->categoriesIndexes[lastCategory].count() - 1) % elementsPerRow;
983 int indexToMove = d->invertedElementDictionary[current].row() - d->elementsInfo[d->proxyModel->mapToSource(current)].relativeOffsetToCategory;
984
985 if (d->forcedSelectionPosition >= lastCategoryLastRow)
986 {
987 indexToMove -= 1;
988 }
989 else
990 {
991 indexToMove -= qMin((lastCategoryLastRow - d->forcedSelectionPosition + 1), d->forcedSelectionPosition + elementsPerRow + 1);
992 }
993
994 return d->elementDictionary[d->proxyModel->index(indexToMove, 0)];
995 }
996 }
997
998 case QAbstractItemView::MoveDown: {
999 if (d->elementsInfo[d->proxyModel->mapToSource(current)].relativeOffsetToCategory < (d->categoriesIndexes[theCategory].count() - 1 - ((d->categoriesIndexes[theCategory].count() - 1) % elementsPerRow)))
1000 {
1001 int indexToMove = d->invertedElementDictionary[current].row();
1002 indexToMove += qMin(elementsPerRow, d->categoriesIndexes[theCategory].count() - 1 - d->elementsInfo[d->proxyModel->mapToSource(current)].relativeOffsetToCategory);
1003
1004 return d->elementDictionary[d->proxyModel->index(indexToMove, 0)];
1005 }
1006 else
1007 {
1008 int afterCategoryLastRow = qMin(elementsPerRow, d->categoriesIndexes[afterCategory].count());
1009 int indexToMove = d->invertedElementDictionary[current].row() + (d->categoriesIndexes[theCategory].count() - d->elementsInfo[d->proxyModel->mapToSource(current)].relativeOffsetToCategory);
1010
1011 if (d->forcedSelectionPosition >= afterCategoryLastRow)
1012 {
1013 indexToMove += afterCategoryLastRow - 1;
1014 }
1015 else
1016 {
1017 indexToMove += qMin(d->forcedSelectionPosition, elementsPerRow);
1018 }
1019
1020 return d->elementDictionary[d->proxyModel->index(indexToMove, 0)];
1021 }
1022 }
1023
1024 case QAbstractItemView::MoveLeft:
1025 d->forcedSelectionPosition = d->elementsInfo[d->proxyModel->mapToSource(d->elementDictionary[d->proxyModel->index(d->invertedElementDictionary[current].row() - 1, 0)])].relativeOffsetToCategory % elementsPerRow;
1026
1027 if (d->forcedSelectionPosition < 0)
1028 d->forcedSelectionPosition = (d->categoriesIndexes[theCategory].count() - 1) % elementsPerRow;
1029
1030 return d->elementDictionary[d->proxyModel->index(d->invertedElementDictionary[current].row() - 1, 0)];
1031
1032 case QAbstractItemView::MoveRight:
1033 d->forcedSelectionPosition = d->elementsInfo[d->proxyModel->mapToSource(d->elementDictionary[d->proxyModel->index(d->invertedElementDictionary[current].row() + 1, 0)])].relativeOffsetToCategory % elementsPerRow;
1034
1035 if (d->forcedSelectionPosition < 0)
1036 d->forcedSelectionPosition = (d->categoriesIndexes[theCategory].count() - 1) % elementsPerRow;
1037
1038 return d->elementDictionary[d->proxyModel->index(d->invertedElementDictionary[current].row() + 1, 0)];
1039
1040 default:
1041 break;
1042 }
1043
1044 return QListView::moveCursor(cursorAction, modifiers);
1045 }
1046
1047 void KCategorizedView::rowsInserted(const QModelIndex &parent,
1048 int start,
1049 int end)
1050 {
1051 QListView::rowsInserted(parent, start, end);
1052
1053 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
1054 !d->itemCategorizer)
1055 {
1056 d->lastSelection = QItemSelection();
1057 d->currentViewIndex = QModelIndex();
1058 d->forcedSelectionPosition = 0;
1059 d->elementsInfo.clear();
1060 d->elementsPosition.clear();
1061 d->elementDictionary.clear();
1062 d->invertedElementDictionary.clear();
1063 d->categoriesIndexes.clear();
1064 d->categoriesPosition.clear();
1065 d->categories.clear();
1066 d->intersectedIndexes.clear();
1067 d->sourceModelIndexList.clear();
1068 d->hovered = QModelIndex();
1069 d->biggestItemSize = QSize(0, 0);
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->biggestItemSize = QSize(0, 0);
1098 d->mouseButtonPressed = false;
1099
1100 if (start > end || end < 0 || start < 0 || !d->proxyModel->rowCount())
1101 {
1102 return;
1103 }
1104
1105 // Add all elements mapped to the source model
1106 for (int k = 0; k < d->proxyModel->rowCount(); k++)
1107 {
1108 d->biggestItemSize = QSize(qMax(sizeHintForIndex(d->proxyModel->index(k, 0)).width(),
1109 d->biggestItemSize.width()),
1110 qMax(sizeHintForIndex(d->proxyModel->index(k, 0)).height(),
1111 d->biggestItemSize.height()));
1112
1113 d->sourceModelIndexList <<
1114 d->proxyModel->mapToSource(d->proxyModel->index(k, 0));
1115 }
1116
1117 // Sort them with the general purpose lessThan method
1118 LessThan generalLessThan(d->proxyModel,
1119 LessThan::GeneralPurpose);
1120
1121 qStableSort(d->sourceModelIndexList.begin(), d->sourceModelIndexList.end(),
1122 generalLessThan);
1123
1124 // Explore categories
1125 QString prevCategory =
1126 d->itemCategorizer->categoryForItem(d->sourceModelIndexList[0],
1127 d->proxyModel->sortRole());
1128 QString lastCategory = prevCategory;
1129 QModelIndexList modelIndexList;
1130 struct Private::ElementInfo elementInfo;
1131 foreach (const QModelIndex &index, d->sourceModelIndexList)
1132 {
1133 lastCategory = d->itemCategorizer->categoryForItem(index,
1134 d->proxyModel->sortRole());
1135
1136 elementInfo.category = lastCategory;
1137
1138 if (prevCategory != lastCategory)
1139 {
1140 d->categoriesIndexes.insert(prevCategory, modelIndexList);
1141 d->categories << prevCategory;
1142 modelIndexList.clear();
1143 }
1144
1145 modelIndexList << index;
1146 prevCategory = lastCategory;
1147
1148 d->elementsInfo.insert(index, elementInfo);
1149 }
1150
1151 d->categoriesIndexes.insert(prevCategory, modelIndexList);
1152 d->categories << prevCategory;
1153
1154 // Sort items locally in their respective categories with the category
1155 // purpose lessThan
1156 LessThan categoryLessThan(d->proxyModel,
1157 LessThan::CategoryPurpose);
1158
1159 foreach (const QString &key, d->categories)
1160 {
1161 QModelIndexList &indexList = d->categoriesIndexes[key];
1162
1163 qStableSort(indexList.begin(), indexList.end(), categoryLessThan);
1164 }
1165
1166 d->lastIndex = d->categoriesIndexes[d->categories[d->categories.count() - 1]][d->categoriesIndexes[d->categories[d->categories.count() - 1]].count() - 1];
1167
1168 // Finally, fill data information of items situation. This will help when
1169 // trying to compute an item place in the viewport
1170 int i = 0; // position relative to the category beginning
1171 int j = 0; // number of elements before current
1172 foreach (const QString &key, d->categories)
1173 {
1174 foreach (const QModelIndex &index, d->categoriesIndexes[key])
1175 {
1176 struct Private::ElementInfo &elementInfo = d->elementsInfo[index];
1177
1178 elementInfo.relativeOffsetToCategory = i;
1179
1180 d->elementDictionary.insert(d->proxyModel->index(j, 0),
1181 d->proxyModel->mapFromSource(index));
1182
1183 d->invertedElementDictionary.insert(d->proxyModel->mapFromSource(index),
1184 d->proxyModel->index(j, 0));
1185
1186 i++;
1187 j++;
1188 }
1189
1190 i = 0;
1191 }
1192
1193 d->updateScrollbars();
1194 }
1195
1196 void KCategorizedView::rowsRemoved(const QModelIndex &parent,
1197 int start,
1198 int end)
1199 {
1200 if ((viewMode() == KCategorizedView::IconMode) && d->proxyModel &&
1201 d->itemCategorizer)
1202 {
1203 // Force the view to update all elements
1204 rowsInsertedArtifficial(parent, start, end);
1205 }
1206 }
1207
1208 void KCategorizedView::updateGeometries()
1209 {
1210 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
1211 !d->itemCategorizer)
1212 {
1213 QListView::updateGeometries();
1214 return;
1215 }
1216
1217 // Avoid QListView::updateGeometries(), since it will try to set another
1218 // range to our scroll bars, what we don't want (ereslibre)
1219 QAbstractItemView::updateGeometries();
1220 }
1221
1222 void KCategorizedView::slotSortingRoleChanged()
1223 {
1224 if ((viewMode() == KCategorizedView::IconMode) && d->proxyModel &&
1225 d->itemCategorizer)
1226 {
1227 // Force the view to update all elements
1228 rowsInsertedArtifficial(QModelIndex(), 0, d->proxyModel->rowCount() - 1);
1229 }
1230 }
1231
1232 #include "kcategorizedview.moc"