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