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