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