]> cloud.milkyroute.net Git - dolphin.git/blob - src/kcategorizedview.cpp
This makes the categorized view amazingly fast in directories with a huge number...
[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@kde.org>
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(layoutAboutToBeChanged()),
481 this, SLOT(slotLayoutAboutToBeChanged()));
482
483 QObject::disconnect(d->proxyModel,
484 SIGNAL(layoutChanged()),
485 this, SLOT(slotLayoutChanged()));
486
487 QObject::disconnect(d->proxyModel,
488 SIGNAL(dataChanged(QModelIndex,QModelIndex)),
489 this, SLOT(slotLayoutChanged()));
490 }
491
492 QListView::setModel(model);
493
494 d->proxyModel = dynamic_cast<KCategorizedSortFilterProxyModel*>(model);
495
496 if (d->proxyModel)
497 {
498 d->modelSortRole = d->proxyModel->sortRole();
499 d->modelSortColumn = d->proxyModel->sortColumn();
500 d->modelSortOrder = d->proxyModel->sortOrder();
501
502 QObject::connect(d->proxyModel,
503 SIGNAL(layoutAboutToBeChanged()),
504 this, SLOT(slotLayoutAboutToBeChanged()));
505
506 QObject::connect(d->proxyModel,
507 SIGNAL(layoutChanged()),
508 this, SLOT(slotLayoutChanged()));
509
510 QObject::connect(d->proxyModel,
511 SIGNAL(dataChanged(QModelIndex,QModelIndex)),
512 this, SLOT(slotLayoutChanged()));
513 }
514 }
515
516 QRect KCategorizedView::visualRect(const QModelIndex &index) const
517 {
518 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
519 !d->categoryDrawer || !d->proxyModel->isCategorizedModel())
520 {
521 return QListView::visualRect(index);
522 }
523
524 if (!qobject_cast<const QSortFilterProxyModel*>(index.model()))
525 {
526 return d->visualRect(d->proxyModel->mapFromSource(index));
527 }
528
529 return d->visualRect(index);
530 }
531
532 KCategoryDrawer *KCategorizedView::categoryDrawer() const
533 {
534 return d->categoryDrawer;
535 }
536
537 void KCategorizedView::setCategoryDrawer(KCategoryDrawer *categoryDrawer)
538 {
539 d->lastSelection = QItemSelection();
540 d->currentViewIndex = QModelIndex();
541 d->forcedSelectionPosition = 0;
542 d->elementsInfo.clear();
543 d->elementsPosition.clear();
544 d->categoriesIndexes.clear();
545 d->categoriesPosition.clear();
546 d->categories.clear();
547 d->intersectedIndexes.clear();
548 d->modelIndexList.clear();
549 d->hovered = QModelIndex();
550 d->mouseButtonPressed = false;
551
552 if (!categoryDrawer && d->proxyModel)
553 {
554 QObject::disconnect(d->proxyModel,
555 SIGNAL(layoutAboutToBeChanged()),
556 this, SLOT(slotLayoutAboutToBeChanged()));
557
558 QObject::disconnect(d->proxyModel,
559 SIGNAL(layoutChanged()),
560 this, SLOT(slotLayoutChanged()));
561
562 QObject::disconnect(d->proxyModel,
563 SIGNAL(dataChanged(QModelIndex,QModelIndex)),
564 this, SLOT(slotLayoutChanged()));
565 }
566 else if (categoryDrawer && d->proxyModel)
567 {
568 QObject::connect(d->proxyModel,
569 SIGNAL(layoutAboutToBeChanged()),
570 this, SLOT(slotLayoutAboutToBeChanged()));
571
572 QObject::connect(d->proxyModel,
573 SIGNAL(layoutChanged()),
574 this, SLOT(slotLayoutChanged()));
575
576 QObject::connect(d->proxyModel,
577 SIGNAL(dataChanged(QModelIndex,QModelIndex)),
578 this, SLOT(slotLayoutChanged()));
579 }
580
581 d->categoryDrawer = categoryDrawer;
582
583 if (categoryDrawer)
584 {
585 if (d->proxyModel)
586 {
587 rowsInserted(QModelIndex(), 0, d->proxyModel->rowCount() - 1);
588 }
589 }
590 else
591 {
592 updateGeometries();
593 }
594 }
595
596 QModelIndex KCategorizedView::indexAt(const QPoint &point) const
597 {
598 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
599 !d->categoryDrawer || !d->proxyModel->isCategorizedModel())
600 {
601 return QListView::indexAt(point);
602 }
603
604 QModelIndex index;
605
606 QModelIndexList item = d->intersectionSet(QRect(point, point));
607
608 if (item.count() == 1)
609 {
610 index = item[0];
611 }
612
613 d->hovered = index;
614
615 return index;
616 }
617
618 void KCategorizedView::reset()
619 {
620 QListView::reset();
621
622 d->lastSelection = QItemSelection();
623 d->currentViewIndex = QModelIndex();
624 d->forcedSelectionPosition = 0;
625 d->elementsInfo.clear();
626 d->elementsPosition.clear();
627 d->categoriesIndexes.clear();
628 d->categoriesPosition.clear();
629 d->categories.clear();
630 d->intersectedIndexes.clear();
631 d->modelIndexList.clear();
632 d->hovered = QModelIndex();
633 d->biggestItemSize = QSize(0, 0);
634 d->mouseButtonPressed = false;
635 }
636
637 void KCategorizedView::paintEvent(QPaintEvent *event)
638 {
639 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
640 !d->categoryDrawer || !d->proxyModel->isCategorizedModel())
641 {
642 QListView::paintEvent(event);
643 return;
644 }
645
646 QStyleOptionViewItemV3 option = viewOptions();
647 option.widget = this;
648 if (wordWrap())
649 {
650 option.features |= QStyleOptionViewItemV2::WrapText;
651 }
652
653 QPainter painter(viewport());
654 QRect area = event->rect();
655 const bool focus = (hasFocus() || viewport()->hasFocus()) &&
656 currentIndex().isValid();
657 const QStyle::State state = option.state;
658 const bool enabled = (state & QStyle::State_Enabled) != 0;
659
660 painter.save();
661
662 QModelIndexList dirtyIndexes = d->intersectionSet(area);
663 foreach (const QModelIndex &index, dirtyIndexes)
664 {
665 option.state = state;
666 option.rect = visualRect(index);
667
668 if (selectionModel() && selectionModel()->isSelected(index))
669 {
670 option.state |= QStyle::State_Selected;
671 }
672
673 if (enabled)
674 {
675 QPalette::ColorGroup cg;
676 if ((d->proxyModel->flags(index) & Qt::ItemIsEnabled) == 0)
677 {
678 option.state &= ~QStyle::State_Enabled;
679 cg = QPalette::Disabled;
680 }
681 else
682 {
683 cg = QPalette::Normal;
684 }
685 option.palette.setCurrentColorGroup(cg);
686 }
687
688 if (focus && currentIndex() == index)
689 {
690 option.state |= QStyle::State_HasFocus;
691 if (this->state() == EditingState)
692 option.state |= QStyle::State_Editing;
693 }
694
695 if ((index == d->hovered) && !d->mouseButtonPressed)
696 option.state |= QStyle::State_MouseOver;
697 else
698 option.state &= ~QStyle::State_MouseOver;
699
700 itemDelegate(index)->paint(&painter, option, index);
701 }
702
703 // Redraw categories
704 QStyleOptionViewItem otherOption;
705 foreach (const QString &category, d->categories)
706 {
707 otherOption = option;
708 otherOption.rect = d->categoryVisualRect(category);
709 otherOption.state &= ~QStyle::State_MouseOver;
710
711 if (otherOption.rect.intersects(area))
712 {
713 QModelIndex indexToDraw = d->proxyModel->index(d->categoriesIndexes[category][0].row(), d->proxyModel->sortColumn());
714
715 d->drawNewCategory(indexToDraw,
716 d->proxyModel->sortRole(), otherOption, &painter);
717 }
718 }
719
720 if (d->mouseButtonPressed && !d->isDragging)
721 {
722 QPoint start, end, initialPressPosition;
723
724 initialPressPosition = d->initialPressPosition;
725
726 initialPressPosition.setY(initialPressPosition.y() - verticalOffset());
727 initialPressPosition.setX(initialPressPosition.x() - horizontalOffset());
728
729 if (d->initialPressPosition.x() > d->mousePosition.x() ||
730 d->initialPressPosition.y() > d->mousePosition.y())
731 {
732 start = d->mousePosition;
733 end = initialPressPosition;
734 }
735 else
736 {
737 start = initialPressPosition;
738 end = d->mousePosition;
739 }
740
741 QStyleOptionRubberBand yetAnotherOption;
742 yetAnotherOption.initFrom(this);
743 yetAnotherOption.shape = QRubberBand::Rectangle;
744 yetAnotherOption.opaque = false;
745 yetAnotherOption.rect = QRect(start, end).intersected(viewport()->rect().adjusted(-16, -16, 16, 16));
746 painter.save();
747 style()->drawControl(QStyle::CE_RubberBand, &yetAnotherOption, &painter);
748 painter.restore();
749 }
750
751 if (d->isDragging && !d->dragLeftViewport)
752 {
753 painter.setOpacity(0.5);
754 d->drawDraggedItems(&painter);
755 }
756
757 painter.restore();
758 }
759
760 void KCategorizedView::resizeEvent(QResizeEvent *event)
761 {
762 QListView::resizeEvent(event);
763
764 // Clear the items positions cache
765 d->elementsPosition.clear();
766 d->categoriesPosition.clear();
767 d->forcedSelectionPosition = 0;
768
769 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
770 !d->categoryDrawer || !d->proxyModel->isCategorizedModel())
771 {
772 return;
773 }
774
775 d->updateScrollbars();
776 }
777
778 void KCategorizedView::setSelection(const QRect &rect,
779 QItemSelectionModel::SelectionFlags flags)
780 {
781 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
782 !d->categoryDrawer || !d->proxyModel->isCategorizedModel())
783 {
784 QListView::setSelection(rect, flags);
785 return;
786 }
787
788 if (!flags)
789 return;
790
791 if (flags & QItemSelectionModel::Clear)
792 {
793 if (!rect.intersects(d->categoryVisualRect(d->hoveredCategory)))
794 {
795 d->lastSelection = QItemSelection();
796 }
797 }
798
799 selectionModel()->clear();
800
801 QModelIndexList dirtyIndexes = d->intersectionSet(rect);
802
803 if (!dirtyIndexes.count())
804 {
805 if (!d->lastSelection.isEmpty() &&
806 (rect.intersects(d->categoryVisualRect(d->hoveredCategory)) || d->mouseButtonPressed))
807 {
808 selectionModel()->select(d->lastSelection, flags);
809 }
810
811 return;
812 }
813
814 QItemSelection selection;
815
816 if (!d->mouseButtonPressed)
817 {
818 selection = QItemSelection(dirtyIndexes[0], dirtyIndexes[0]);
819 d->currentViewIndex = dirtyIndexes[0];
820 }
821 else
822 {
823 QModelIndex first = dirtyIndexes[0];
824 QModelIndex last;
825 foreach (const QModelIndex &index, dirtyIndexes)
826 {
827 if (last.isValid() && last.row() + 1 != index.row())
828 {
829 QItemSelectionRange range(first, last);
830
831 selection << range;
832
833 first = index;
834 }
835
836 last = index;
837 }
838
839 if (last.isValid())
840 selection << QItemSelectionRange(first, last);
841 }
842
843 if (d->lastSelection.count())
844 {
845 if ((selection.count() == 1) && (selection[0].indexes().count() == 1))
846 selection.merge(d->lastSelection, flags);
847 else
848 selection.merge(d->lastSelection, QItemSelectionModel::Select);
849 }
850
851 selectionModel()->select(selection, flags);
852 }
853
854 void KCategorizedView::mouseMoveEvent(QMouseEvent *event)
855 {
856 QListView::mouseMoveEvent(event);
857
858 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
859 !d->categoryDrawer || !d->proxyModel->isCategorizedModel())
860 {
861 return;
862 }
863
864 const QString previousHoveredCategory = d->hoveredCategory;
865
866 d->mousePosition = event->pos();
867 d->hoveredCategory = QString();
868
869 // Redraw categories
870 foreach (const QString &category, d->categories)
871 {
872 if (d->categoryVisualRect(category).intersects(QRect(event->pos(), event->pos())))
873 {
874 d->hoveredCategory = category;
875 viewport()->update(d->categoryVisualRect(category));
876 }
877 else if ((category == previousHoveredCategory) &&
878 (!d->categoryVisualRect(previousHoveredCategory).intersects(QRect(event->pos(), event->pos()))))
879 {
880 viewport()->update(d->categoryVisualRect(category));
881 }
882 }
883
884 QRect rect;
885 if (d->mouseButtonPressed && !d->isDragging)
886 {
887 QPoint start, end, initialPressPosition;
888
889 initialPressPosition = d->initialPressPosition;
890
891 initialPressPosition.setY(initialPressPosition.y() - verticalOffset());
892 initialPressPosition.setX(initialPressPosition.x() - horizontalOffset());
893
894 if (d->initialPressPosition.x() > d->mousePosition.x() ||
895 d->initialPressPosition.y() > d->mousePosition.y())
896 {
897 start = d->mousePosition;
898 end = initialPressPosition;
899 }
900 else
901 {
902 start = initialPressPosition;
903 end = d->mousePosition;
904 }
905
906 rect = QRect(start, end).intersected(viewport()->rect().adjusted(-16, -16, 16, 16));
907
908 //viewport()->update(rect.united(d->lastSelectionRect));
909
910 d->lastSelectionRect = rect;
911 }
912 }
913
914 void KCategorizedView::mousePressEvent(QMouseEvent *event)
915 {
916 d->dragLeftViewport = false;
917
918 if (event->button() == Qt::LeftButton)
919 {
920 d->mouseButtonPressed = true;
921
922 d->initialPressPosition = event->pos();
923 d->initialPressPosition.setY(d->initialPressPosition.y() +
924 verticalOffset());
925 d->initialPressPosition.setX(d->initialPressPosition.x() +
926 horizontalOffset());
927 }
928
929 QListView::mousePressEvent(event);
930
931 viewport()->update(d->categoryVisualRect(d->hoveredCategory));
932 }
933
934 void KCategorizedView::mouseReleaseEvent(QMouseEvent *event)
935 {
936 d->mouseButtonPressed = false;
937
938 QListView::mouseReleaseEvent(event);
939
940 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
941 !d->categoryDrawer || !d->proxyModel->isCategorizedModel())
942 {
943 return;
944 }
945
946 QPoint initialPressPosition = viewport()->mapFromGlobal(QCursor::pos());
947 initialPressPosition.setY(initialPressPosition.y() + verticalOffset());
948 initialPressPosition.setX(initialPressPosition.x() + horizontalOffset());
949
950 QItemSelection selection;
951 QItemSelection deselection;
952
953 if (initialPressPosition == d->initialPressPosition)
954 {
955 foreach(const QString &category, d->categories)
956 {
957 if (d->categoryVisualRect(category).contains(event->pos()))
958 {
959 foreach (const QModelIndex &index, d->categoriesIndexes[category])
960 {
961 QModelIndex selectIndex = index.model()->index(index.row(), 0);
962
963 if (!d->lastSelection.contains(selectIndex))
964 {
965 selection << QItemSelectionRange(selectIndex);
966 }
967 else
968 {
969 deselection << QItemSelectionRange(selectIndex);
970 }
971 }
972
973 selectionModel()->select(selection, QItemSelectionModel::Select);
974 selectionModel()->select(deselection, QItemSelectionModel::Deselect);
975
976 break;
977 }
978 }
979 }
980
981 d->lastSelection = selectionModel()->selection();
982
983 if (d->hovered.isValid())
984 viewport()->update(visualRect(d->hovered));
985 else if (!d->hoveredCategory.isEmpty())
986 viewport()->update(d->categoryVisualRect(d->hoveredCategory));
987 }
988
989 void KCategorizedView::leaveEvent(QEvent *event)
990 {
991 d->hovered = QModelIndex();
992 d->hoveredCategory = QString();
993
994 QListView::leaveEvent(event);
995 }
996
997 void KCategorizedView::startDrag(Qt::DropActions supportedActions)
998 {
999 // FIXME: QAbstractItemView does far better here since it sets the
1000 // pixmap of selected icons to the dragging cursor, but it sets a non
1001 // ARGB window so it is no transparent. Use QAbstractItemView when
1002 // this is fixed on Qt.
1003 // QAbstractItemView::startDrag(supportedActions);
1004 QListView::startDrag(supportedActions);
1005
1006 d->isDragging = false;
1007 d->mouseButtonPressed = false;
1008
1009 viewport()->update(d->lastDraggedItemsRect);
1010 }
1011
1012 void KCategorizedView::dragMoveEvent(QDragMoveEvent *event)
1013 {
1014 d->mousePosition = event->pos();
1015
1016 if (d->mouseButtonPressed)
1017 {
1018 d->isDragging = true;
1019 }
1020 else
1021 {
1022 d->isDragging = false;
1023 }
1024
1025 d->dragLeftViewport = false;
1026
1027 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
1028 !d->categoryDrawer || !d->proxyModel->isCategorizedModel())
1029 {
1030 QListView::dragMoveEvent(event);
1031 return;
1032 }
1033
1034 d->drawDraggedItems();
1035 }
1036
1037 void KCategorizedView::dragLeaveEvent(QDragLeaveEvent *event)
1038 {
1039 d->dragLeftViewport = true;
1040
1041 QListView::dragLeaveEvent(event);
1042 }
1043
1044 QModelIndex KCategorizedView::moveCursor(CursorAction cursorAction,
1045 Qt::KeyboardModifiers modifiers)
1046 {
1047 if ((viewMode() != KCategorizedView::IconMode) ||
1048 !d->proxyModel ||
1049 !d->categoryDrawer ||
1050 d->categories.isEmpty() ||
1051 !d->proxyModel->isCategorizedModel()
1052 )
1053 {
1054 return QListView::moveCursor(cursorAction, modifiers);
1055 }
1056
1057 const QModelIndex current = selectionModel()->currentIndex();
1058
1059 int viewportWidth = viewport()->width() - spacing();
1060 int itemWidth;
1061
1062 if (gridSize().isEmpty())
1063 {
1064 itemWidth = d->biggestItemSize.width();
1065 }
1066 else
1067 {
1068 itemWidth = gridSize().width();
1069 }
1070
1071 int itemWidthPlusSeparation = spacing() + itemWidth;
1072 int elementsPerRow = viewportWidth / itemWidthPlusSeparation;
1073
1074 QString lastCategory = d->categories.first();
1075 QString theCategory = d->categories.first();
1076 QString afterCategory = d->categories.first();
1077
1078 bool hasToBreak = false;
1079 foreach (const QString &category, d->categories)
1080 {
1081 if (hasToBreak)
1082 {
1083 afterCategory = category;
1084
1085 break;
1086 }
1087
1088 if (category == d->elementsInfo[current.row()].category)
1089 {
1090 theCategory = category;
1091
1092 hasToBreak = true;
1093 }
1094
1095 if (!hasToBreak)
1096 {
1097 lastCategory = category;
1098 }
1099 }
1100
1101 switch (cursorAction)
1102 {
1103 case QAbstractItemView::MoveUp: {
1104 if (d->elementsInfo[current.row()].relativeOffsetToCategory >= elementsPerRow)
1105 {
1106 int indexToMove = current.row();
1107 indexToMove -= qMin(((d->elementsInfo[current.row()].relativeOffsetToCategory) + d->forcedSelectionPosition), elementsPerRow - d->forcedSelectionPosition + (d->elementsInfo[current.row()].relativeOffsetToCategory % elementsPerRow));
1108
1109 return d->proxyModel->index(indexToMove, 0);
1110 }
1111 else
1112 {
1113 int lastCategoryLastRow = (d->categoriesIndexes[lastCategory].count() - 1) % elementsPerRow;
1114 int indexToMove = current.row() - d->elementsInfo[current.row()].relativeOffsetToCategory;
1115
1116 if (d->forcedSelectionPosition >= lastCategoryLastRow)
1117 {
1118 indexToMove -= 1;
1119 }
1120 else
1121 {
1122 indexToMove -= qMin((lastCategoryLastRow - d->forcedSelectionPosition + 1), d->forcedSelectionPosition + elementsPerRow + 1);
1123 }
1124
1125 return d->proxyModel->index(indexToMove, 0);
1126 }
1127 }
1128
1129 case QAbstractItemView::MoveDown: {
1130 if (d->elementsInfo[current.row()].relativeOffsetToCategory < (d->categoriesIndexes[theCategory].count() - 1 - ((d->categoriesIndexes[theCategory].count() - 1) % elementsPerRow)))
1131 {
1132 int indexToMove = current.row();
1133 indexToMove += qMin(elementsPerRow, d->categoriesIndexes[theCategory].count() - 1 - d->elementsInfo[current.row()].relativeOffsetToCategory);
1134
1135 return d->proxyModel->index(indexToMove, 0);
1136 }
1137 else
1138 {
1139 int afterCategoryLastRow = qMin(elementsPerRow, d->categoriesIndexes[afterCategory].count());
1140 int indexToMove = current.row() + (d->categoriesIndexes[theCategory].count() - d->elementsInfo[current.row()].relativeOffsetToCategory);
1141
1142 if (d->forcedSelectionPosition >= afterCategoryLastRow)
1143 {
1144 indexToMove += afterCategoryLastRow - 1;
1145 }
1146 else
1147 {
1148 indexToMove += qMin(d->forcedSelectionPosition, elementsPerRow);
1149 }
1150
1151 return d->proxyModel->index(indexToMove, 0);
1152 }
1153 }
1154
1155 case QAbstractItemView::MoveLeft:
1156 if (layoutDirection() == Qt::RightToLeft)
1157 {
1158 d->forcedSelectionPosition = d->elementsInfo[current.row() + 1].relativeOffsetToCategory % elementsPerRow;
1159
1160 if (d->forcedSelectionPosition < 0)
1161 d->forcedSelectionPosition = (d->categoriesIndexes[theCategory].count() - 1) % elementsPerRow;
1162
1163 return d->proxyModel->index(current.row() + 1, 0);
1164 }
1165
1166 d->forcedSelectionPosition = d->elementsInfo[current.row() - 1].relativeOffsetToCategory % elementsPerRow;
1167
1168 if (d->forcedSelectionPosition < 0)
1169 d->forcedSelectionPosition = (d->categoriesIndexes[theCategory].count() - 1) % elementsPerRow;
1170
1171 return d->proxyModel->index(current.row() - 1, 0);
1172
1173 case QAbstractItemView::MoveRight:
1174 if (layoutDirection() == Qt::RightToLeft)
1175 {
1176 d->forcedSelectionPosition = d->elementsInfo[current.row() - 1].relativeOffsetToCategory % elementsPerRow;
1177
1178 if (d->forcedSelectionPosition < 0)
1179 d->forcedSelectionPosition = (d->categoriesIndexes[theCategory].count() - 1) % elementsPerRow;
1180
1181 return d->proxyModel->index(current.row() - 1, 0);
1182 }
1183
1184 d->forcedSelectionPosition = d->elementsInfo[current.row() + 1].relativeOffsetToCategory % elementsPerRow;
1185
1186 if (d->forcedSelectionPosition < 0)
1187 d->forcedSelectionPosition = (d->categoriesIndexes[theCategory].count() - 1) % elementsPerRow;
1188
1189 return d->proxyModel->index(current.row() + 1, 0);
1190
1191 default:
1192 break;
1193 }
1194
1195 return QListView::moveCursor(cursorAction, modifiers);
1196 }
1197
1198 void KCategorizedView::rowsInserted(const QModelIndex &parent,
1199 int start,
1200 int end)
1201 {
1202 QListView::rowsInserted(parent, start, end);
1203
1204 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
1205 !d->categoryDrawer || !d->proxyModel->isCategorizedModel())
1206 {
1207 d->lastSelection = QItemSelection();
1208 d->currentViewIndex = QModelIndex();
1209 d->forcedSelectionPosition = 0;
1210 d->elementsInfo.clear();
1211 d->elementsPosition.clear();
1212 d->categoriesIndexes.clear();
1213 d->categoriesPosition.clear();
1214 d->categories.clear();
1215 d->intersectedIndexes.clear();
1216 d->modelIndexList.clear();
1217 d->hovered = QModelIndex();
1218 d->biggestItemSize = QSize(0, 0);
1219 d->mouseButtonPressed = false;
1220
1221 return;
1222 }
1223
1224 rowsInsertedArtifficial(parent, start, end);
1225 }
1226
1227 void KCategorizedView::rowsInsertedArtifficial(const QModelIndex &parent,
1228 int start,
1229 int end)
1230 {
1231 Q_UNUSED(parent);
1232
1233 d->lastSelection = QItemSelection();
1234 d->currentViewIndex = QModelIndex();
1235 d->forcedSelectionPosition = 0;
1236 d->elementsInfo.clear();
1237 d->elementsPosition.clear();
1238 d->categoriesIndexes.clear();
1239 d->categoriesPosition.clear();
1240 d->categories.clear();
1241 d->intersectedIndexes.clear();
1242 d->modelIndexList.clear();
1243 d->hovered = QModelIndex();
1244 d->biggestItemSize = QSize(0, 0);
1245 d->mouseButtonPressed = false;
1246
1247 if (start > end || end < 0 || start < 0 || !d->proxyModel->rowCount())
1248 {
1249 return;
1250 }
1251
1252 // Add all elements mapped to the source model
1253 for (int k = 0; k < d->proxyModel->rowCount(); k++)
1254 {
1255 d->biggestItemSize = QSize(qMax(sizeHintForIndex(d->proxyModel->index(k, 0)).width(),
1256 d->biggestItemSize.width()),
1257 qMax(sizeHintForIndex(d->proxyModel->index(k, 0)).height(),
1258 d->biggestItemSize.height()));
1259
1260 d->modelIndexList << d->proxyModel->index(k, d->proxyModel->sortColumn());
1261 }
1262
1263 // Explore categories
1264 QString prevCategory = d->proxyModel->data(d->modelIndexList[0], KCategorizedSortFilterProxyModel::CategoryRole).toString();
1265 QString lastCategory = prevCategory;
1266 QModelIndexList modelIndexList;
1267 struct Private::ElementInfo elementInfo;
1268 int offset = -1;
1269 foreach (const QModelIndex &index, d->modelIndexList)
1270 {
1271 lastCategory = d->proxyModel->data(index, KCategorizedSortFilterProxyModel::CategoryRole).toString();
1272
1273 elementInfo.category = lastCategory;
1274
1275 if (prevCategory != lastCategory)
1276 {
1277 offset = 0;
1278 d->categoriesIndexes.insert(prevCategory, modelIndexList);
1279 d->categories << prevCategory;
1280 modelIndexList.clear();
1281 }
1282 else
1283 {
1284 offset++;
1285 }
1286
1287 elementInfo.relativeOffsetToCategory = offset;
1288
1289 modelIndexList << index;
1290 prevCategory = lastCategory;
1291
1292 d->elementsInfo.insert(index.row(), elementInfo);
1293 }
1294
1295 d->categoriesIndexes.insert(prevCategory, modelIndexList);
1296 d->categories << prevCategory;
1297
1298 d->updateScrollbars();
1299 }
1300
1301 void KCategorizedView::rowsRemoved(const QModelIndex &parent,
1302 int start,
1303 int end)
1304 {
1305 if ((viewMode() == KCategorizedView::IconMode) && d->proxyModel &&
1306 d->categoryDrawer && d->proxyModel->isCategorizedModel())
1307 {
1308 // Force the view to update all elements
1309 rowsInsertedArtifficial(parent, start, end);
1310 }
1311 }
1312
1313 void KCategorizedView::updateGeometries()
1314 {
1315 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
1316 !d->categoryDrawer || !d->proxyModel->isCategorizedModel())
1317 {
1318 QListView::updateGeometries();
1319 return;
1320 }
1321
1322 // Avoid QListView::updateGeometries(), since it will try to set another
1323 // range to our scroll bars, what we don't want (ereslibre)
1324 QAbstractItemView::updateGeometries();
1325 }
1326
1327 void KCategorizedView::slotLayoutAboutToBeChanged()
1328 {
1329 if ((viewMode() == KCategorizedView::IconMode) && d->proxyModel &&
1330 d->categoryDrawer && d->proxyModel->isCategorizedModel())
1331 {
1332 d->modelSortRole = d->proxyModel->sortRole();
1333 d->modelSortColumn = d->proxyModel->sortColumn();
1334 d->modelSortOrder = d->proxyModel->sortOrder();
1335 }
1336 }
1337
1338 void KCategorizedView::slotLayoutChanged()
1339 {
1340 if ((viewMode() == KCategorizedView::IconMode) && d->proxyModel &&
1341 d->categoryDrawer && d->proxyModel->isCategorizedModel() &&
1342 ((d->modelSortRole != d->proxyModel->sortRole()) ||
1343 (d->modelSortColumn != d->proxyModel->sortColumn()) ||
1344 (d->modelSortOrder != d->proxyModel->sortOrder())))
1345 {
1346 // Force the view to update all elements
1347 rowsInsertedArtifficial(QModelIndex(), 0, d->proxyModel->rowCount() - 1);
1348 }
1349 }
1350
1351 #include "kcategorizedview.moc"