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