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