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