]> cloud.milkyroute.net Git - dolphin.git/blob - src/kcategorizedview.cpp
Fix palette problem as workaround. This is needed if the categorization is enabled
[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.palette = palette(); // viewOptions() doesn't seem to return the correct palette
699 // if the app was already running and the color scheme was changed
700 // (ereslibre)
701 option.widget = this;
702 if (wordWrap())
703 {
704 option.features |= QStyleOptionViewItemV2::WrapText;
705 }
706
707 QPainter painter(viewport());
708 QRect area = event->rect();
709 const bool focus = (hasFocus() || viewport()->hasFocus()) &&
710 currentIndex().isValid();
711 const QStyle::State state = option.state;
712 const bool enabled = (state & QStyle::State_Enabled) != 0;
713
714 painter.save();
715
716 QModelIndexList dirtyIndexes = d->intersectionSet(area);
717 foreach (const QModelIndex &index, dirtyIndexes)
718 {
719 option.state = state;
720 option.rect = visualRect(index);
721
722 if (selectionModel() && selectionModel()->isSelected(index))
723 {
724 option.state |= QStyle::State_Selected;
725 }
726
727 if (enabled)
728 {
729 QPalette::ColorGroup cg;
730 if ((d->proxyModel->flags(index) & Qt::ItemIsEnabled) == 0)
731 {
732 option.state &= ~QStyle::State_Enabled;
733 cg = QPalette::Disabled;
734 }
735 else
736 {
737 cg = QPalette::Normal;
738 }
739 option.palette.setCurrentColorGroup(cg);
740 }
741
742 if (focus && currentIndex() == index)
743 {
744 option.state |= QStyle::State_HasFocus;
745 if (this->state() == EditingState)
746 option.state |= QStyle::State_Editing;
747 }
748
749 if ((index == d->hovered) && !d->mouseButtonPressed)
750 option.state |= QStyle::State_MouseOver;
751 else
752 option.state &= ~QStyle::State_MouseOver;
753
754 itemDelegate(index)->paint(&painter, option, index);
755 }
756
757 // Redraw categories
758 QStyleOptionViewItem otherOption;
759 bool intersectedInThePast = false;
760 foreach (const QString &category, d->categories)
761 {
762 otherOption = option;
763 otherOption.rect = d->categoryVisualRect(category);
764 otherOption.state &= ~QStyle::State_MouseOver;
765
766 if (otherOption.rect.intersects(area))
767 {
768 intersectedInThePast = true;
769
770 QModelIndex indexToDraw = d->proxyModel->index(d->categoriesIndexes[category][0].row(), d->proxyModel->sortColumn());
771
772 d->drawNewCategory(indexToDraw,
773 d->proxyModel->sortRole(), otherOption, &painter);
774 }
775 else if (intersectedInThePast)
776 {
777 break; // the visible area has been finished, we don't need to keep asking, the rest won't intersect
778 // this is doable because we know that categories are correctly ordered on the list
779 }
780 }
781
782 if (d->mouseButtonPressed && !d->isDragging)
783 {
784 QPoint start, end, initialPressPosition;
785
786 initialPressPosition = d->initialPressPosition;
787
788 initialPressPosition.setY(initialPressPosition.y() - verticalOffset());
789 initialPressPosition.setX(initialPressPosition.x() - horizontalOffset());
790
791 if (d->initialPressPosition.x() > d->mousePosition.x() ||
792 d->initialPressPosition.y() > d->mousePosition.y())
793 {
794 start = d->mousePosition;
795 end = initialPressPosition;
796 }
797 else
798 {
799 start = initialPressPosition;
800 end = d->mousePosition;
801 }
802
803 QStyleOptionRubberBand yetAnotherOption;
804 yetAnotherOption.initFrom(this);
805 yetAnotherOption.shape = QRubberBand::Rectangle;
806 yetAnotherOption.opaque = false;
807 yetAnotherOption.rect = QRect(start, end).intersected(viewport()->rect().adjusted(-16, -16, 16, 16));
808 painter.save();
809 style()->drawControl(QStyle::CE_RubberBand, &yetAnotherOption, &painter);
810 painter.restore();
811 }
812
813 if (d->isDragging && !d->dragLeftViewport)
814 {
815 painter.setOpacity(0.5);
816 d->drawDraggedItems(&painter);
817 }
818
819 painter.restore();
820 }
821
822 void KCategorizedView::resizeEvent(QResizeEvent *event)
823 {
824 QListView::resizeEvent(event);
825
826 // Clear the items positions cache
827 d->elementsPosition.clear();
828 d->categoriesPosition.clear();
829 d->forcedSelectionPosition = 0;
830
831 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
832 !d->categoryDrawer || !d->proxyModel->isCategorizedModel())
833 {
834 return;
835 }
836
837 d->updateScrollbars();
838 }
839
840 void KCategorizedView::setSelection(const QRect &rect,
841 QItemSelectionModel::SelectionFlags flags)
842 {
843 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
844 !d->categoryDrawer || !d->proxyModel->isCategorizedModel())
845 {
846 QListView::setSelection(rect, flags);
847 return;
848 }
849
850 if (!flags)
851 return;
852
853 if (flags & QItemSelectionModel::Clear)
854 {
855 if (!rect.intersects(d->categoryVisualRect(d->hoveredCategory)))
856 {
857 d->lastSelection = QItemSelection();
858 }
859 }
860
861 selectionModel()->clear();
862
863 QModelIndexList dirtyIndexes = d->intersectionSet(rect);
864
865 if (!dirtyIndexes.count())
866 {
867 if (!d->lastSelection.isEmpty() &&
868 (rect.intersects(d->categoryVisualRect(d->hoveredCategory)) || d->mouseButtonPressed))
869 {
870 selectionModel()->select(d->lastSelection, flags);
871 }
872
873 return;
874 }
875
876 QItemSelection selection;
877
878 if (!d->mouseButtonPressed)
879 {
880 selection = QItemSelection(dirtyIndexes[0], dirtyIndexes[0]);
881 d->currentViewIndex = dirtyIndexes[0];
882 }
883 else
884 {
885 QModelIndex first = dirtyIndexes[0];
886 QModelIndex last;
887 foreach (const QModelIndex &index, dirtyIndexes)
888 {
889 if (last.isValid() && last.row() + 1 != index.row())
890 {
891 QItemSelectionRange range(first, last);
892
893 selection << range;
894
895 first = index;
896 }
897
898 last = index;
899 }
900
901 if (last.isValid())
902 selection << QItemSelectionRange(first, last);
903 }
904
905 if (d->lastSelection.count())
906 {
907 if ((selection.count() == 1) && (selection[0].indexes().count() == 1))
908 selection.merge(d->lastSelection, flags);
909 else
910 selection.merge(d->lastSelection, QItemSelectionModel::Select);
911 }
912
913 selectionModel()->select(selection, flags);
914 }
915
916 void KCategorizedView::mouseMoveEvent(QMouseEvent *event)
917 {
918 QListView::mouseMoveEvent(event);
919
920 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
921 !d->categoryDrawer || !d->proxyModel->isCategorizedModel())
922 {
923 return;
924 }
925
926 const QString previousHoveredCategory = d->hoveredCategory;
927
928 d->mousePosition = event->pos();
929 d->hoveredCategory = QString();
930
931 // Redraw categories
932 foreach (const QString &category, d->categories)
933 {
934 if (d->categoryVisualRect(category).intersects(QRect(event->pos(), event->pos())))
935 {
936 d->hoveredCategory = category;
937 viewport()->update(d->categoryVisualRect(category));
938 }
939 else if ((category == previousHoveredCategory) &&
940 (!d->categoryVisualRect(previousHoveredCategory).intersects(QRect(event->pos(), event->pos()))))
941 {
942 viewport()->update(d->categoryVisualRect(category));
943 }
944 }
945
946 QRect rect;
947 if (d->mouseButtonPressed && !d->isDragging)
948 {
949 QPoint start, end, initialPressPosition;
950
951 initialPressPosition = d->initialPressPosition;
952
953 initialPressPosition.setY(initialPressPosition.y() - verticalOffset());
954 initialPressPosition.setX(initialPressPosition.x() - horizontalOffset());
955
956 if (d->initialPressPosition.x() > d->mousePosition.x() ||
957 d->initialPressPosition.y() > d->mousePosition.y())
958 {
959 start = d->mousePosition;
960 end = initialPressPosition;
961 }
962 else
963 {
964 start = initialPressPosition;
965 end = d->mousePosition;
966 }
967
968 rect = QRect(start, end).intersected(viewport()->rect().adjusted(-16, -16, 16, 16));
969
970 //viewport()->update(rect.united(d->lastSelectionRect));
971
972 d->lastSelectionRect = rect;
973 }
974 }
975
976 void KCategorizedView::mousePressEvent(QMouseEvent *event)
977 {
978 d->dragLeftViewport = false;
979
980 if (event->button() == Qt::LeftButton)
981 {
982 d->mouseButtonPressed = true;
983
984 d->initialPressPosition = event->pos();
985 d->initialPressPosition.setY(d->initialPressPosition.y() +
986 verticalOffset());
987 d->initialPressPosition.setX(d->initialPressPosition.x() +
988 horizontalOffset());
989 }
990
991 QListView::mousePressEvent(event);
992
993 viewport()->update(d->categoryVisualRect(d->hoveredCategory));
994 }
995
996 void KCategorizedView::mouseReleaseEvent(QMouseEvent *event)
997 {
998 d->mouseButtonPressed = false;
999
1000 QListView::mouseReleaseEvent(event);
1001
1002 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
1003 !d->categoryDrawer || !d->proxyModel->isCategorizedModel())
1004 {
1005 return;
1006 }
1007
1008 QPoint initialPressPosition = viewport()->mapFromGlobal(QCursor::pos());
1009 initialPressPosition.setY(initialPressPosition.y() + verticalOffset());
1010 initialPressPosition.setX(initialPressPosition.x() + horizontalOffset());
1011
1012 QItemSelection selection;
1013 QItemSelection deselection;
1014
1015 if (initialPressPosition == d->initialPressPosition)
1016 {
1017 foreach(const QString &category, d->categories)
1018 {
1019 if (d->categoryVisualRect(category).contains(event->pos()))
1020 {
1021 foreach (const QModelIndex &index, d->categoriesIndexes[category])
1022 {
1023 QModelIndex selectIndex = index.model()->index(index.row(), 0);
1024
1025 if (!d->lastSelection.contains(selectIndex))
1026 {
1027 selection << QItemSelectionRange(selectIndex);
1028 }
1029 else
1030 {
1031 deselection << QItemSelectionRange(selectIndex);
1032 }
1033 }
1034
1035 selectionModel()->select(selection, QItemSelectionModel::Select);
1036 selectionModel()->select(deselection, QItemSelectionModel::Deselect);
1037
1038 break;
1039 }
1040 }
1041 }
1042
1043 d->lastSelection = selectionModel()->selection();
1044
1045 if (d->hovered.isValid())
1046 viewport()->update(visualRect(d->hovered));
1047 else if (!d->hoveredCategory.isEmpty())
1048 viewport()->update(d->categoryVisualRect(d->hoveredCategory));
1049 }
1050
1051 void KCategorizedView::leaveEvent(QEvent *event)
1052 {
1053 d->hovered = QModelIndex();
1054 d->hoveredCategory = QString();
1055
1056 QListView::leaveEvent(event);
1057 }
1058
1059 void KCategorizedView::startDrag(Qt::DropActions supportedActions)
1060 {
1061 // FIXME: QAbstractItemView does far better here since it sets the
1062 // pixmap of selected icons to the dragging cursor, but it sets a non
1063 // ARGB window so it is no transparent. Use QAbstractItemView when
1064 // this is fixed on Qt.
1065 // QAbstractItemView::startDrag(supportedActions);
1066 #if !defined(DOLPHIN_DRAGANDDROP)
1067 QListView::startDrag(supportedActions);
1068 #endif
1069
1070 d->isDragging = false;
1071 d->mouseButtonPressed = false;
1072
1073 viewport()->update(d->lastDraggedItemsRect);
1074 }
1075
1076 void KCategorizedView::dragMoveEvent(QDragMoveEvent *event)
1077 {
1078 d->mousePosition = event->pos();
1079
1080 if (d->mouseButtonPressed)
1081 {
1082 d->isDragging = true;
1083 }
1084 else
1085 {
1086 d->isDragging = false;
1087 }
1088
1089 d->dragLeftViewport = false;
1090
1091 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
1092 !d->categoryDrawer || !d->proxyModel->isCategorizedModel())
1093 {
1094 #if defined(DOLPHIN_DRAGANDDROP)
1095 QAbstractItemView::dragMoveEvent(event);
1096 #else
1097 QListView::dragMoveEvent(event);
1098 #endif
1099 return;
1100 }
1101
1102 d->drawDraggedItems();
1103 }
1104
1105 void KCategorizedView::dragLeaveEvent(QDragLeaveEvent *event)
1106 {
1107 d->dragLeftViewport = true;
1108
1109 #if defined(DOLPHIN_DRAGANDDROP)
1110 QAbstractItemView::dragLeaveEvent(event);
1111 #else
1112 QListView::dragLeaveEvent(event);
1113 #endif
1114 }
1115
1116 void KCategorizedView::dropEvent(QDropEvent *event)
1117 {
1118 #if defined(DOLPHIN_DRAGANDDROP)
1119 QAbstractItemView::dropEvent(event);
1120 #else
1121 QListView::dropEvent(event);
1122 #endif
1123 }
1124
1125 QModelIndex KCategorizedView::moveCursor(CursorAction cursorAction,
1126 Qt::KeyboardModifiers modifiers)
1127 {
1128 if ((viewMode() != KCategorizedView::IconMode) ||
1129 !d->proxyModel ||
1130 !d->categoryDrawer ||
1131 d->categories.isEmpty() ||
1132 !d->proxyModel->isCategorizedModel()
1133 )
1134 {
1135 return QListView::moveCursor(cursorAction, modifiers);
1136 }
1137
1138 const QModelIndex current = selectionModel()->currentIndex();
1139
1140 int viewportWidth = viewport()->width() - spacing();
1141 int itemWidth;
1142
1143 if (gridSize().isEmpty())
1144 {
1145 itemWidth = d->biggestItemSize.width();
1146 }
1147 else
1148 {
1149 itemWidth = gridSize().width();
1150 }
1151
1152 int itemWidthPlusSeparation = spacing() + itemWidth;
1153 int elementsPerRow = viewportWidth / itemWidthPlusSeparation;
1154
1155 QString lastCategory = d->categories.first();
1156 QString theCategory = d->categories.first();
1157 QString afterCategory = d->categories.first();
1158
1159 bool hasToBreak = false;
1160 foreach (const QString &category, d->categories)
1161 {
1162 if (hasToBreak)
1163 {
1164 afterCategory = category;
1165
1166 break;
1167 }
1168
1169 if (category == d->elementsInfo[current.row()].category)
1170 {
1171 theCategory = category;
1172
1173 hasToBreak = true;
1174 }
1175
1176 if (!hasToBreak)
1177 {
1178 lastCategory = category;
1179 }
1180 }
1181
1182 switch (cursorAction)
1183 {
1184 case QAbstractItemView::MoveUp: {
1185 if (d->elementsInfo[current.row()].relativeOffsetToCategory >= elementsPerRow)
1186 {
1187 int indexToMove = current.row();
1188 indexToMove -= qMin(((d->elementsInfo[current.row()].relativeOffsetToCategory) + d->forcedSelectionPosition), elementsPerRow - d->forcedSelectionPosition + (d->elementsInfo[current.row()].relativeOffsetToCategory % elementsPerRow));
1189
1190 return d->proxyModel->index(indexToMove, 0);
1191 }
1192 else
1193 {
1194 int lastCategoryLastRow = (d->categoriesIndexes[lastCategory].count() - 1) % elementsPerRow;
1195 int indexToMove = current.row() - d->elementsInfo[current.row()].relativeOffsetToCategory;
1196
1197 if (d->forcedSelectionPosition >= lastCategoryLastRow)
1198 {
1199 indexToMove -= 1;
1200 }
1201 else
1202 {
1203 indexToMove -= qMin((lastCategoryLastRow - d->forcedSelectionPosition + 1), d->forcedSelectionPosition + elementsPerRow + 1);
1204 }
1205
1206 return d->proxyModel->index(indexToMove, 0);
1207 }
1208 }
1209
1210 case QAbstractItemView::MoveDown: {
1211 if (d->elementsInfo[current.row()].relativeOffsetToCategory < (d->categoriesIndexes[theCategory].count() - 1 - ((d->categoriesIndexes[theCategory].count() - 1) % elementsPerRow)))
1212 {
1213 int indexToMove = current.row();
1214 indexToMove += qMin(elementsPerRow, d->categoriesIndexes[theCategory].count() - 1 - d->elementsInfo[current.row()].relativeOffsetToCategory);
1215
1216 return d->proxyModel->index(indexToMove, 0);
1217 }
1218 else
1219 {
1220 int afterCategoryLastRow = qMin(elementsPerRow, d->categoriesIndexes[afterCategory].count());
1221 int indexToMove = current.row() + (d->categoriesIndexes[theCategory].count() - d->elementsInfo[current.row()].relativeOffsetToCategory);
1222
1223 if (d->forcedSelectionPosition >= afterCategoryLastRow)
1224 {
1225 indexToMove += afterCategoryLastRow - 1;
1226 }
1227 else
1228 {
1229 indexToMove += qMin(d->forcedSelectionPosition, elementsPerRow);
1230 }
1231
1232 return d->proxyModel->index(indexToMove, 0);
1233 }
1234 }
1235
1236 case QAbstractItemView::MoveLeft:
1237 if (layoutDirection() == Qt::RightToLeft)
1238 {
1239 d->forcedSelectionPosition = d->elementsInfo[current.row() + 1].relativeOffsetToCategory % elementsPerRow;
1240
1241 if (d->forcedSelectionPosition < 0)
1242 d->forcedSelectionPosition = (d->categoriesIndexes[theCategory].count() - 1) % elementsPerRow;
1243
1244 return d->proxyModel->index(current.row() + 1, 0);
1245 }
1246
1247 d->forcedSelectionPosition = d->elementsInfo[current.row() - 1].relativeOffsetToCategory % elementsPerRow;
1248
1249 if (d->forcedSelectionPosition < 0)
1250 d->forcedSelectionPosition = (d->categoriesIndexes[theCategory].count() - 1) % elementsPerRow;
1251
1252 return d->proxyModel->index(current.row() - 1, 0);
1253
1254 case QAbstractItemView::MoveRight:
1255 if (layoutDirection() == Qt::RightToLeft)
1256 {
1257 d->forcedSelectionPosition = d->elementsInfo[current.row() - 1].relativeOffsetToCategory % elementsPerRow;
1258
1259 if (d->forcedSelectionPosition < 0)
1260 d->forcedSelectionPosition = (d->categoriesIndexes[theCategory].count() - 1) % elementsPerRow;
1261
1262 return d->proxyModel->index(current.row() - 1, 0);
1263 }
1264
1265 d->forcedSelectionPosition = d->elementsInfo[current.row() + 1].relativeOffsetToCategory % elementsPerRow;
1266
1267 if (d->forcedSelectionPosition < 0)
1268 d->forcedSelectionPosition = (d->categoriesIndexes[theCategory].count() - 1) % elementsPerRow;
1269
1270 return d->proxyModel->index(current.row() + 1, 0);
1271
1272 default:
1273 break;
1274 }
1275
1276 return QListView::moveCursor(cursorAction, modifiers);
1277 }
1278
1279 void KCategorizedView::rowsInserted(const QModelIndex &parent,
1280 int start,
1281 int end)
1282 {
1283 QListView::rowsInserted(parent, start, end);
1284
1285 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
1286 !d->categoryDrawer || !d->proxyModel->isCategorizedModel())
1287 {
1288 d->lastSelection = QItemSelection();
1289 d->currentViewIndex = QModelIndex();
1290 d->forcedSelectionPosition = 0;
1291 d->elementsInfo.clear();
1292 d->elementsPosition.clear();
1293 d->categoriesIndexes.clear();
1294 d->categoriesPosition.clear();
1295 d->categories.clear();
1296 d->intersectedIndexes.clear();
1297 d->modelIndexList.clear();
1298 d->hovered = QModelIndex();
1299 d->biggestItemSize = QSize(0, 0);
1300 d->mouseButtonPressed = false;
1301
1302 return;
1303 }
1304
1305 rowsInsertedArtifficial(parent, start, end);
1306 }
1307
1308 void KCategorizedView::rowsInsertedArtifficial(const QModelIndex &parent,
1309 int start,
1310 int end)
1311 {
1312 Q_UNUSED(parent);
1313
1314 d->lastSelection = QItemSelection();
1315 d->currentViewIndex = QModelIndex();
1316 d->forcedSelectionPosition = 0;
1317 d->elementsInfo.clear();
1318 d->elementsPosition.clear();
1319 d->categoriesIndexes.clear();
1320 d->categoriesPosition.clear();
1321 d->categories.clear();
1322 d->intersectedIndexes.clear();
1323 d->modelIndexList.clear();
1324 d->hovered = QModelIndex();
1325 d->biggestItemSize = QSize(0, 0);
1326 d->mouseButtonPressed = false;
1327
1328 if (start > end || end < 0 || start < 0 || !d->proxyModel->rowCount())
1329 {
1330 return;
1331 }
1332
1333 // Add all elements mapped to the source model and explore categories
1334 QString prevCategory = d->proxyModel->data(d->proxyModel->index(0, d->proxyModel->sortColumn()), KCategorizedSortFilterProxyModel::CategoryDisplayRole).toString();
1335 QString lastCategory = prevCategory;
1336 QModelIndexList modelIndexList;
1337 struct Private::ElementInfo elementInfo;
1338 int offset = -1;
1339 for (int k = 0; k < d->proxyModel->rowCount(); ++k)
1340 {
1341 QModelIndex index = d->proxyModel->index(k, d->proxyModel->sortColumn());
1342 QModelIndex indexSize = d->proxyModel->index(k, 0);
1343
1344 d->biggestItemSize = QSize(qMax(sizeHintForIndex(indexSize).width(),
1345 d->biggestItemSize.width()),
1346 qMax(sizeHintForIndex(indexSize).height(),
1347 d->biggestItemSize.height()));
1348
1349 d->modelIndexList << index;
1350
1351 lastCategory = d->proxyModel->data(index, KCategorizedSortFilterProxyModel::CategoryDisplayRole).toString();
1352
1353 elementInfo.category = lastCategory;
1354
1355 if (prevCategory != lastCategory)
1356 {
1357 offset = 0;
1358 d->categoriesIndexes.insert(prevCategory, modelIndexList);
1359 d->categories << prevCategory;
1360 modelIndexList.clear();
1361 }
1362 else
1363 {
1364 offset++;
1365 }
1366
1367 elementInfo.relativeOffsetToCategory = offset;
1368
1369 modelIndexList << index;
1370 prevCategory = lastCategory;
1371
1372 d->elementsInfo.insert(index.row(), elementInfo);
1373 }
1374
1375 d->categoriesIndexes.insert(prevCategory, modelIndexList);
1376 d->categories << prevCategory;
1377
1378 d->updateScrollbars();
1379 }
1380
1381 void KCategorizedView::rowsRemoved(const QModelIndex &parent,
1382 int start,
1383 int end)
1384 {
1385 if ((viewMode() == KCategorizedView::IconMode) && d->proxyModel &&
1386 d->categoryDrawer && d->proxyModel->isCategorizedModel())
1387 {
1388 // Force the view to update all elements
1389 rowsInsertedArtifficial(QModelIndex(), 0, d->proxyModel->rowCount() - 1);
1390 }
1391 }
1392
1393 void KCategorizedView::updateGeometries()
1394 {
1395 if ((viewMode() != KCategorizedView::IconMode) || !d->proxyModel ||
1396 !d->categoryDrawer || !d->proxyModel->isCategorizedModel())
1397 {
1398 QListView::updateGeometries();
1399 return;
1400 }
1401
1402 // Avoid QListView::updateGeometries(), since it will try to set another
1403 // range to our scroll bars, what we don't want (ereslibre)
1404 QAbstractItemView::updateGeometries();
1405 }
1406
1407 void KCategorizedView::slotLayoutChanged()
1408 {
1409 d->layoutChanged();
1410 }
1411
1412 #include "kcategorizedview.moc"