]> cloud.milkyroute.net Git - dolphin.git/blob - src/klistview.cpp
What is faster ? the eye or the brain ?
[dolphin.git] / src / klistview.cpp
1 /**
2 * This file is part of the KDE project
3 * Copyright (C) 2007 Rafael Fernández López <ereslibre@gmail.com>
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 "klistview.h"
22 #include "klistview_p.h"
23
24 #include <math.h> // trunc on C99 compliant systems
25 #include <kdefakes.h> // trunc for not C99 compliant systems
26
27 #include <QApplication>
28 #include <QPainter>
29 #include <QScrollBar>
30 #include <QPaintEvent>
31
32 #include <kdebug.h>
33 #include <kstyle.h>
34
35 #include "kitemcategorizer.h"
36 #include "ksortfilterproxymodel.h"
37
38 class LessThan
39 {
40 public:
41 enum Purpose
42 {
43 GeneralPurpose = 0,
44 CategoryPurpose
45 };
46
47 inline LessThan(const KSortFilterProxyModel *proxyModel,
48 Purpose purpose)
49 : proxyModel(proxyModel)
50 , purpose(purpose)
51 {
52 }
53
54 inline bool operator()(const QModelIndex &left,
55 const QModelIndex &right) const
56 {
57 if (purpose == GeneralPurpose)
58 {
59 return proxyModel->sortOrder() == Qt::AscendingOrder ?
60 proxyModel->lessThanGeneralPurpose(left, right) :
61 !proxyModel->lessThanGeneralPurpose(left, right);
62 }
63
64 return proxyModel->sortOrder() == Qt::AscendingOrder ?
65 proxyModel->lessThanCategoryPurpose(left, right) :
66 !proxyModel->lessThanCategoryPurpose(left, right);
67 }
68
69 private:
70 const KSortFilterProxyModel *proxyModel;
71 const Purpose purpose;
72 };
73
74
75 //==============================================================================
76
77
78 KListView::Private::Private(KListView *listView)
79 : listView(listView)
80 , itemCategorizer(0)
81 , mouseButtonPressed(false)
82 , isDragging(false)
83 , dragLeftViewport(false)
84 , proxyModel(0)
85 , lastIndex(QModelIndex())
86 {
87 }
88
89 KListView::Private::~Private()
90 {
91 }
92
93 const QModelIndexList &KListView::Private::intersectionSet(const QRect &rect)
94 {
95 QModelIndex index;
96 QRect indexVisualRect;
97
98 intersectedIndexes.clear();
99
100 // Lets find out where we should start
101 int top = proxyModel->rowCount() - 1;
102 int bottom = 0;
103 int middle = (top + bottom) / 2;
104 while (bottom <= top)
105 {
106 middle = (top + bottom) / 2;
107
108 index = elementDictionary[proxyModel->index(middle, 0)];
109 indexVisualRect = visualRect(index);
110
111 if (qMax(indexVisualRect.topLeft().y(),
112 indexVisualRect.bottomRight().y()) < qMin(rect.topLeft().y(),
113 rect.bottomRight().y()))
114 {
115 bottom = middle + 1;
116 }
117 else
118 {
119 top = middle - 1;
120 }
121 }
122
123 for (int i = middle; i < proxyModel->rowCount(); i++)
124 {
125 index = elementDictionary[proxyModel->index(i, 0)];
126 indexVisualRect = visualRect(index);
127
128 if (rect.intersects(indexVisualRect))
129 intersectedIndexes.append(index);
130
131 // If we passed next item, stop searching for hits
132 if (qMax(rect.bottomRight().y(), rect.topLeft().y()) <
133 qMin(indexVisualRect.topLeft().y(),
134 indexVisualRect.bottomRight().y()))
135 break;
136 }
137
138 return intersectedIndexes;
139 }
140
141 QRect KListView::Private::visualRectInViewport(const QModelIndex &index) const
142 {
143 if (!index.isValid())
144 return QRect();
145
146 QString curCategory = elementsInfo[index].category;
147
148 QRect retRect(listView->spacing(), listView->spacing() * 2 +
149 30 /* categoryHeight */, 0, 0);
150
151 int viewportWidth = listView->viewport()->width() - listView->spacing();
152
153 // We really need all items to be of same size. Otherwise we cannot do this
154 // (ereslibre)
155 // QSize itemSize =
156 // listView->sizeHintForIndex(proxyModel->mapFromSource(index));
157 // int itemHeight = itemSize.height();
158 // int itemWidth = itemSize.width();*/
159 int itemHeight = 107;
160 int itemWidth = 130;
161 int itemWidthPlusSeparation = listView->spacing() + itemWidth;
162 int elementsPerRow = viewportWidth / itemWidthPlusSeparation;
163 if (!elementsPerRow)
164 elementsPerRow++;
165
166 int column = elementsInfo[index].relativeOffsetToCategory % elementsPerRow;
167 int row = elementsInfo[index].relativeOffsetToCategory / elementsPerRow;
168
169 retRect.setLeft(retRect.left() + column * listView->spacing() +
170 column * itemWidth);
171
172 float rows;
173 int rowsInt;
174 foreach (const QString &category, categories)
175 {
176 if (category == curCategory)
177 break;
178
179 rows = (float) ((float) categoriesIndexes[category].count() /
180 (float) elementsPerRow);
181 rowsInt = categoriesIndexes[category].count() / elementsPerRow;
182
183 if (rows - trunc(rows)) rowsInt++;
184
185 retRect.setTop(retRect.top() +
186 (rowsInt * listView->spacing()) +
187 (rowsInt * itemHeight) +
188 30 /* categoryHeight */ +
189 listView->spacing() * 2);
190 }
191
192 retRect.setTop(retRect.top() + row * listView->spacing() +
193 row * itemHeight);
194
195 retRect.setWidth(itemWidth);
196 retRect.setHeight(itemHeight);
197
198 return retRect;
199 }
200
201 QRect KListView::Private::visualCategoryRectInViewport(const QString &category)
202 const
203 {
204 QRect retRect(listView->spacing(),
205 listView->spacing(),
206 listView->viewport()->width() - listView->spacing() * 2,
207 0);
208
209 if (!proxyModel->rowCount() || !categories.contains(category))
210 return QRect();
211
212 QModelIndex index = proxyModel->index(0, 0, QModelIndex());
213
214 int viewportWidth = listView->viewport()->width() - listView->spacing();
215
216 // We really need all items to be of same size. Otherwise we cannot do this
217 // (ereslibre)
218 // QSize itemSize = listView->sizeHintForIndex(index);
219 // int itemHeight = itemSize.height();
220 // int itemWidth = itemSize.width();
221 int itemHeight = 107;
222 int itemWidth = 130;
223 int itemWidthPlusSeparation = listView->spacing() + itemWidth;
224 int elementsPerRow = viewportWidth / itemWidthPlusSeparation;
225
226 if (!elementsPerRow)
227 elementsPerRow++;
228
229 float rows;
230 int rowsInt;
231 foreach (const QString &itCategory, categories)
232 {
233 if (itCategory == category)
234 break;
235
236 rows = (float) ((float) categoriesIndexes[itCategory].count() /
237 (float) elementsPerRow);
238 rowsInt = categoriesIndexes[itCategory].count() / elementsPerRow;
239
240 if (rows - trunc(rows)) rowsInt++;
241
242 retRect.setTop(retRect.top() +
243 (rowsInt * listView->spacing()) +
244 (rowsInt * itemHeight) +
245 30 /* categoryHeight */ +
246 listView->spacing() * 2);
247 }
248
249 retRect.setHeight(30 /* categoryHeight */);
250
251 return retRect;
252 }
253
254 // We're sure elementsPosition doesn't contain index
255 const QRect &KListView::Private::cacheIndex(const QModelIndex &index)
256 {
257 QRect rect = visualRectInViewport(index);
258 elementsPosition[index] = rect;
259
260 return elementsPosition[index];
261 }
262
263 // We're sure categoriesPosition doesn't contain category
264 const QRect &KListView::Private::cacheCategory(const QString &category)
265 {
266 QRect rect = visualCategoryRectInViewport(category);
267 categoriesPosition[category] = rect;
268
269 return categoriesPosition[category];
270 }
271
272 const QRect &KListView::Private::cachedRectIndex(const QModelIndex &index)
273 {
274 if (elementsPosition.contains(index)) // If we have it cached
275 { // return it
276 return elementsPosition[index];
277 }
278 else // Otherwise, cache it
279 { // and return it
280 return cacheIndex(index);
281 }
282 }
283
284 const QRect &KListView::Private::cachedRectCategory(const QString &category)
285 {
286 if (categoriesPosition.contains(category)) // If we have it cached
287 { // return it
288 return categoriesPosition[category];
289 }
290 else // Otherwise, cache it and
291 { // return it
292 return cacheCategory(category);
293 }
294 }
295
296 QRect KListView::Private::visualRect(const QModelIndex &index)
297 {
298 QModelIndex mappedIndex = proxyModel->mapToSource(index);
299
300 QRect retRect = cachedRectIndex(mappedIndex);
301 int dx = -listView->horizontalOffset();
302 int dy = -listView->verticalOffset();
303 retRect.adjust(dx, dy, dx, dy);
304
305 return retRect;
306 }
307
308 QRect KListView::Private::categoryVisualRect(const QString &category)
309 {
310 QRect retRect = cachedRectCategory(category);
311 int dx = -listView->horizontalOffset();
312 int dy = -listView->verticalOffset();
313 retRect.adjust(dx, dy, dx, dy);
314
315 return retRect;
316 }
317
318 void KListView::Private::drawNewCategory(const QString &category,
319 const QStyleOption &option,
320 QPainter *painter)
321 {
322 QColor color = option.palette.color(QPalette::Text);
323
324 painter->save();
325 painter->setRenderHint(QPainter::Antialiasing);
326
327 QStyleOptionButton opt;
328
329 opt.rect = option.rect;
330 opt.palette = option.palette;
331 opt.direction = option.direction;
332 opt.text = category;
333
334 if ((category == hoveredCategory) && !mouseButtonPressed)
335 {
336 const QPalette::ColorGroup group =
337 option.state & QStyle::State_Enabled ?
338 QPalette::Normal : QPalette::Disabled;
339
340 QLinearGradient gradient(option.rect.topLeft(),
341 option.rect.bottomRight());
342 gradient.setColorAt(0,
343 option.palette.color(group,
344 QPalette::Highlight).light());
345 gradient.setColorAt(1, Qt::transparent);
346
347 painter->fillRect(option.rect, gradient);
348 }
349
350 /*if (const KStyle *style = dynamic_cast<const KStyle*>(QApplication::style()))
351 {
352 style->drawControl(KStyle::CE_Category, &opt, painter, this);
353 }
354 else
355 {*/
356 QFont painterFont = painter->font();
357 painterFont.setWeight(QFont::Bold);
358 QFontMetrics metrics(painterFont);
359 painter->setFont(painterFont);
360
361 QPainterPath path;
362 path.addRect(option.rect.left(),
363 option.rect.bottom() - 2,
364 option.rect.width(),
365 2);
366
367 QLinearGradient gradient(option.rect.topLeft(),
368 option.rect.bottomRight());
369 gradient.setColorAt(0, color);
370 gradient.setColorAt(1, Qt::transparent);
371
372 painter->setBrush(gradient);
373 painter->fillPath(path, gradient);
374
375 painter->setPen(color);
376
377 painter->drawText(option.rect, Qt::AlignVCenter | Qt::AlignLeft,
378 metrics.elidedText(category, Qt::ElideRight, option.rect.width()));
379 //}
380 painter->restore();
381 }
382
383
384 void KListView::Private::updateScrollbars()
385 {
386 int lastItemBottom = cachedRectIndex(lastIndex).bottom() +
387 listView->spacing() - listView->viewport()->height();
388
389 listView->verticalScrollBar()->setSingleStep(listView->viewport()->height() / 10);
390 listView->verticalScrollBar()->setPageStep(listView->viewport()->height());
391 listView->verticalScrollBar()->setRange(0, lastItemBottom);
392 }
393
394 void KListView::Private::drawDraggedItems(QPainter *painter)
395 {
396 QStyleOptionViewItemV3 option = listView->viewOptions();
397 option.state &= ~QStyle::State_MouseOver;
398 int dx;
399 int dy;
400 foreach (const QModelIndex &index, listView->selectionModel()->selectedIndexes())
401 {
402 dx = mousePosition.x() - initialPressPosition.x() + listView->horizontalOffset();
403 dy = mousePosition.y() - initialPressPosition.y() + listView->verticalOffset();
404
405 option.rect = visualRect(index);
406 option.rect.adjust(dx, dy, dx, dy);
407
408 listView->itemDelegate(index)->paint(painter, option, index);
409 }
410 }
411
412
413 //==============================================================================
414
415
416 KListView::KListView(QWidget *parent)
417 : QListView(parent)
418 , d(new Private(this))
419 {
420 }
421
422 KListView::~KListView()
423 {
424 delete d;
425 }
426
427 void KListView::setModel(QAbstractItemModel *model)
428 {
429 if (d->proxyModel)
430 {
431 QObject::disconnect(d->proxyModel,
432 SIGNAL(rowsRemoved(QModelIndex,int,int)),
433 this, SLOT(rowsRemoved(QModelIndex,int,int)));
434
435 QObject::disconnect(d->proxyModel,
436 SIGNAL(sortingRoleChanged()),
437 this, SLOT(slotSortingRoleChanged()));
438 }
439
440 QListView::setModel(model);
441
442 d->proxyModel = dynamic_cast<KSortFilterProxyModel*>(model);
443
444 if (d->proxyModel)
445 {
446 QObject::connect(d->proxyModel,
447 SIGNAL(rowsRemoved(QModelIndex,int,int)),
448 this, SLOT(rowsRemoved(QModelIndex,int,int)));
449
450 QObject::connect(d->proxyModel,
451 SIGNAL(sortingRoleChanged()),
452 this, SLOT(slotSortingRoleChanged()));
453 }
454 }
455
456 QRect KListView::visualRect(const QModelIndex &index) const
457 {
458 if ((viewMode() != KListView::IconMode) || !d->proxyModel ||
459 !d->itemCategorizer)
460 {
461 return QListView::visualRect(index);
462 }
463
464 if (!qobject_cast<const QSortFilterProxyModel*>(index.model()))
465 {
466 return d->visualRect(d->proxyModel->mapFromSource(index));
467 }
468
469 return d->visualRect(index);
470 }
471
472 KItemCategorizer *KListView::itemCategorizer() const
473 {
474 return d->itemCategorizer;
475 }
476
477 void KListView::setItemCategorizer(KItemCategorizer *itemCategorizer)
478 {
479 if (!itemCategorizer && d->proxyModel)
480 {
481 QObject::disconnect(d->proxyModel,
482 SIGNAL(rowsRemoved(QModelIndex,int,int)),
483 this, SLOT(rowsRemoved(QModelIndex,int,int)));
484
485 QObject::disconnect(d->proxyModel,
486 SIGNAL(sortingRoleChanged()),
487 this, SLOT(slotSortingRoleChanged()));
488 }
489 else if (itemCategorizer && d->proxyModel)
490 {
491 QObject::connect(d->proxyModel,
492 SIGNAL(rowsRemoved(QModelIndex,int,int)),
493 this, SLOT(rowsRemoved(QModelIndex,int,int)));
494
495 QObject::connect(d->proxyModel,
496 SIGNAL(sortingRoleChanged()),
497 this, SLOT(slotSortingRoleChanged()));
498 }
499
500 d->itemCategorizer = itemCategorizer;
501
502 if (itemCategorizer)
503 {
504 rowsInserted(QModelIndex(), 0, d->proxyModel->rowCount() - 1);
505 }
506 else
507 {
508 updateGeometries();
509 }
510 }
511
512 QModelIndex KListView::indexAt(const QPoint &point) const
513 {
514 if ((viewMode() != KListView::IconMode) || !d->proxyModel ||
515 !d->itemCategorizer)
516 {
517 return QListView::indexAt(point);
518 }
519
520 QModelIndex index;
521
522 QModelIndexList item = d->intersectionSet(QRect(point, point));
523
524 if (item.count() == 1)
525 {
526 index = item[0];
527 }
528
529 d->hovered = index;
530
531 return index;
532 }
533
534 void KListView::reset()
535 {
536 QListView::reset();
537
538 if ((viewMode() != KListView::IconMode) || !d->proxyModel ||
539 !d->itemCategorizer)
540 {
541 return;
542 }
543
544 d->elementsInfo.clear();
545 d->elementsPosition.clear();
546 d->elementDictionary.clear();
547 d->categoriesIndexes.clear();
548 d->categoriesPosition.clear();
549 d->categories.clear();
550 d->intersectedIndexes.clear();
551 d->sourceModelIndexList.clear();
552 d->hovered = QModelIndex();
553 d->mouseButtonPressed = false;
554 }
555
556 void KListView::paintEvent(QPaintEvent *event)
557 {
558 if ((viewMode() != KListView::IconMode) || !d->proxyModel ||
559 !d->itemCategorizer)
560 {
561 QListView::paintEvent(event);
562 return;
563 }
564
565 QStyleOptionViewItemV3 option = viewOptions();
566 QPainter painter(viewport());
567 QRect area = event->rect();
568 const bool focus = (hasFocus() || viewport()->hasFocus()) &&
569 currentIndex().isValid();
570 const QStyle::State state = option.state;
571 const bool enabled = (state & QStyle::State_Enabled) != 0;
572
573 painter.save();
574
575 QModelIndexList dirtyIndexes = d->intersectionSet(area);
576 foreach (const QModelIndex &index, dirtyIndexes)
577 {
578 option.state = state;
579 option.rect = d->visualRect(index);
580
581 if (selectionModel() && selectionModel()->isSelected(index))
582 {
583 option.state |= QStyle::State_Selected;
584 }
585
586 if (enabled)
587 {
588 QPalette::ColorGroup cg;
589 if ((d->proxyModel->flags(index) & Qt::ItemIsEnabled) == 0)
590 {
591 option.state &= ~QStyle::State_Enabled;
592 cg = QPalette::Disabled;
593 }
594 else
595 {
596 cg = QPalette::Normal;
597 }
598 option.palette.setCurrentColorGroup(cg);
599 }
600
601 if (focus && currentIndex() == index)
602 {
603 option.state |= QStyle::State_HasFocus;
604 if (this->state() == EditingState)
605 option.state |= QStyle::State_Editing;
606 }
607
608 if ((index == d->hovered) && !d->mouseButtonPressed)
609 option.state |= QStyle::State_MouseOver;
610 else
611 option.state &= ~QStyle::State_MouseOver;
612
613 itemDelegate(index)->paint(&painter, option, index);
614 }
615
616 // Redraw categories
617 QStyleOptionViewItem otherOption;
618 foreach (const QString &category, d->categories)
619 {
620 otherOption = option;
621 otherOption.rect = d->categoryVisualRect(category);
622
623 if (otherOption.rect.intersects(area))
624 {
625 d->drawNewCategory(category, otherOption, &painter);
626 }
627 }
628
629 if (d->mouseButtonPressed && !d->isDragging)
630 {
631 QPoint start, end, initialPressPosition;
632
633 initialPressPosition = d->initialPressPosition;
634
635 initialPressPosition.setY(initialPressPosition.y() - verticalOffset());
636 initialPressPosition.setX(initialPressPosition.x() - horizontalOffset());
637
638 if (d->initialPressPosition.x() > d->mousePosition.x() ||
639 d->initialPressPosition.y() > d->mousePosition.y())
640 {
641 start = d->mousePosition;
642 end = initialPressPosition;
643 }
644 else
645 {
646 start = initialPressPosition;
647 end = d->mousePosition;
648 }
649
650 QStyleOptionRubberBand yetAnotherOption;
651 yetAnotherOption.initFrom(this);
652 yetAnotherOption.shape = QRubberBand::Rectangle;
653 yetAnotherOption.opaque = false;
654 yetAnotherOption.rect = QRect(start, end).intersected(viewport()->rect().adjusted(-16, -16, 16, 16));
655 painter.save();
656 style()->drawControl(QStyle::CE_RubberBand, &yetAnotherOption, &painter);
657 painter.restore();
658 }
659
660 if (d->isDragging && !d->dragLeftViewport)
661 {
662 painter.setOpacity(0.5);
663 d->drawDraggedItems(&painter);
664 }
665
666 painter.restore();
667 }
668
669 void KListView::resizeEvent(QResizeEvent *event)
670 {
671 QListView::resizeEvent(event);
672
673 if ((viewMode() != KListView::IconMode) || !d->proxyModel ||
674 !d->itemCategorizer)
675 {
676 return;
677 }
678
679 // Clear the items positions cache
680 d->elementsPosition.clear();
681 d->categoriesPosition.clear();
682
683 d->updateScrollbars();
684 }
685
686 void KListView::setSelection(const QRect &rect,
687 QItemSelectionModel::SelectionFlags flags)
688 {
689 if ((viewMode() != KListView::IconMode) || !d->proxyModel ||
690 !d->itemCategorizer)
691 {
692 QListView::setSelection(rect, flags);
693 return;
694 }
695
696 if (!flags)
697 return;
698
699 selectionModel()->clear();
700
701 if (flags & QItemSelectionModel::Clear)
702 {
703 d->lastSelection = QItemSelection();
704 }
705
706 QModelIndexList dirtyIndexes = d->intersectionSet(rect);
707 QItemSelection selection;
708
709 if (!dirtyIndexes.count())
710 {
711 if (d->lastSelection.count())
712 {
713 selectionModel()->select(d->lastSelection, flags);
714 }
715
716 return;
717 }
718
719 if (!d->mouseButtonPressed)
720 {
721 selection = QItemSelection(dirtyIndexes[0], dirtyIndexes[0]);
722 }
723 else
724 {
725 QModelIndex first = dirtyIndexes[0];
726 QModelIndex last;
727 foreach (const QModelIndex &index, dirtyIndexes)
728 {
729 if (last.isValid() && last.row() + 1 != index.row())
730 {
731 QItemSelectionRange range(first, last);
732
733 selection << range;
734
735 first = index;
736 }
737
738 last = index;
739 }
740
741 if (last.isValid())
742 selection << QItemSelectionRange(first, last);
743 }
744
745 if (d->lastSelection.count() && !d->mouseButtonPressed)
746 {
747 selection.merge(d->lastSelection, flags);
748 }
749 else if (d->lastSelection.count())
750 {
751 selection.merge(d->lastSelection, QItemSelectionModel::Select);
752 }
753
754 selectionModel()->select(selection, flags);
755 }
756
757 void KListView::mouseMoveEvent(QMouseEvent *event)
758 {
759 QListView::mouseMoveEvent(event);
760
761 if ((viewMode() != KListView::IconMode) || !d->proxyModel ||
762 !d->itemCategorizer)
763 {
764 return;
765 }
766
767 d->mousePosition = event->pos();
768 d->hoveredCategory = QString();
769
770 // Redraw categories
771 foreach (const QString &category, d->categories)
772 {
773 if (d->categoryVisualRect(category).intersects(QRect(event->pos(), event->pos())))
774 {
775 d->hoveredCategory = category;
776 }
777
778 viewport()->update(d->categoryVisualRect(category));
779 }
780 }
781
782 void KListView::mousePressEvent(QMouseEvent *event)
783 {
784 QListView::mousePressEvent(event);
785
786 if ((viewMode() != KListView::IconMode) || !d->proxyModel ||
787 !d->itemCategorizer)
788 {
789 return;
790 }
791
792 d->dragLeftViewport = false;
793
794 if (event->button() == Qt::LeftButton)
795 {
796 d->mouseButtonPressed = true;
797
798 d->initialPressPosition = event->pos();
799 d->initialPressPosition.setY(d->initialPressPosition.y() +
800 verticalOffset());
801 d->initialPressPosition.setX(d->initialPressPosition.x() +
802 horizontalOffset());
803 }
804 }
805
806 void KListView::mouseReleaseEvent(QMouseEvent *event)
807 {
808 QListView::mouseReleaseEvent(event);
809
810 if ((viewMode() != KListView::IconMode) || !d->proxyModel ||
811 !d->itemCategorizer)
812 {
813 return;
814 }
815
816 d->mouseButtonPressed = false;
817
818 QPoint initialPressPosition = viewport()->mapFromGlobal(QCursor::pos());
819 initialPressPosition.setY(initialPressPosition.y() + verticalOffset());
820 initialPressPosition.setX(initialPressPosition.x() + horizontalOffset());
821
822 QItemSelection selection;
823
824 if (initialPressPosition == d->initialPressPosition)
825 {
826 foreach(const QString &category, d->categories)
827 {
828 if (d->categoryVisualRect(category).contains(event->pos()))
829 {
830 QItemSelectionRange selectionRange(d->proxyModel->mapFromSource(d->categoriesIndexes[category][0]),
831 d->proxyModel->mapFromSource(d->categoriesIndexes[category][d->categoriesIndexes[category].count() - 1]));
832
833 selection << selectionRange;
834
835 selectionModel()->select(selection, QItemSelectionModel::Select);
836
837 break;
838 }
839 }
840 }
841
842 d->lastSelection = selectionModel()->selection();
843
844 if (d->hovered.isValid())
845 viewport()->update(d->visualRect(d->hovered));
846 else if (!d->hoveredCategory.isEmpty())
847 viewport()->update(d->categoryVisualRect(d->hoveredCategory));
848 }
849
850 void KListView::leaveEvent(QEvent *event)
851 {
852 QListView::leaveEvent(event);
853
854 if ((viewMode() != KListView::IconMode) || !d->proxyModel ||
855 !d->itemCategorizer)
856 {
857 return;
858 }
859
860 d->hovered = QModelIndex();
861 d->hoveredCategory = QString();
862 }
863
864 void KListView::startDrag(Qt::DropActions supportedActions)
865 {
866 QListView::startDrag(supportedActions);
867
868 d->isDragging = false;
869 d->mouseButtonPressed = false;
870 }
871
872 void KListView::dragMoveEvent(QDragMoveEvent *event)
873 {
874 if ((viewMode() != KListView::IconMode) || !d->proxyModel ||
875 !d->itemCategorizer)
876 {
877 QListView::dragMoveEvent(event);
878 return;
879 }
880
881 d->mousePosition = event->pos();
882
883 if (d->mouseButtonPressed)
884 {
885 d->isDragging = true;
886 }
887 else
888 {
889 d->isDragging = false;
890 }
891
892 d->dragLeftViewport = false;
893 }
894
895 void KListView::dragLeaveEvent(QDragLeaveEvent *event)
896 {
897 QListView::dragLeaveEvent(event);
898
899 if ((viewMode() != KListView::IconMode) || !d->proxyModel ||
900 !d->itemCategorizer)
901 {
902 return;
903 }
904
905 d->dragLeftViewport = true;
906 }
907
908 QModelIndex KListView::moveCursor(CursorAction cursorAction,
909 Qt::KeyboardModifiers modifiers)
910 {
911 if ((viewMode() != KListView::IconMode) || !d->proxyModel ||
912 !d->itemCategorizer)
913 {
914 return QListView::moveCursor(cursorAction, modifiers);
915 }
916
917 return QListView::moveCursor(cursorAction, modifiers);
918 }
919
920 void KListView::rowsInserted(const QModelIndex &parent,
921 int start,
922 int end)
923 {
924 QListView::rowsInserted(parent, start, end);
925
926 if ((viewMode() != KListView::IconMode) || !d->proxyModel ||
927 !d->itemCategorizer)
928 {
929 return;
930 }
931
932 rowsInsertedArtifficial(parent, start, end);
933 }
934
935 void KListView::rowsInsertedArtifficial(const QModelIndex &parent,
936 int start,
937 int end)
938 {
939 d->lastSelection = QItemSelection();
940 d->elementsInfo.clear();
941 d->elementsPosition.clear();
942 d->elementDictionary.clear();
943 d->categoriesIndexes.clear();
944 d->categoriesPosition.clear();
945 d->categories.clear();
946 d->intersectedIndexes.clear();
947 d->sourceModelIndexList.clear();
948 d->hovered = QModelIndex();
949 d->mouseButtonPressed = false;
950
951 if (start > end || end < 0 || start < 0 || !d->proxyModel->rowCount())
952 {
953 return;
954 }
955
956 // Add all elements mapped to the source model
957 for (int k = 0; k < d->proxyModel->rowCount(); k++)
958 {
959 d->sourceModelIndexList <<
960 d->proxyModel->mapToSource(d->proxyModel->index(k, 0));
961 }
962
963 // Sort them with the general purpose lessThan method
964 LessThan generalLessThan(d->proxyModel,
965 LessThan::GeneralPurpose);
966
967 qStableSort(d->sourceModelIndexList.begin(), d->sourceModelIndexList.end(),
968 generalLessThan);
969
970 // Explore categories
971 QString prevCategory =
972 d->itemCategorizer->categoryForItem(d->sourceModelIndexList[0],
973 d->proxyModel->sortRole());
974 QString lastCategory = prevCategory;
975 QModelIndexList modelIndexList;
976 struct Private::ElementInfo elementInfo;
977 foreach (const QModelIndex &index, d->sourceModelIndexList)
978 {
979 lastCategory = d->itemCategorizer->categoryForItem(index,
980 d->proxyModel->sortRole());
981
982 elementInfo.category = lastCategory;
983
984 if (prevCategory != lastCategory)
985 {
986 d->categoriesIndexes.insert(prevCategory, modelIndexList);
987 d->categories << prevCategory;
988 modelIndexList.clear();
989 }
990
991 modelIndexList << index;
992 prevCategory = lastCategory;
993
994 d->elementsInfo.insert(index, elementInfo);
995 }
996
997 d->categoriesIndexes.insert(prevCategory, modelIndexList);
998 d->categories << prevCategory;
999
1000 // Sort items locally in their respective categories with the category
1001 // purpose lessThan
1002 LessThan categoryLessThan(d->proxyModel,
1003 LessThan::CategoryPurpose);
1004
1005 foreach (const QString &key, d->categories)
1006 {
1007 QModelIndexList &indexList = d->categoriesIndexes[key];
1008
1009 qStableSort(indexList.begin(), indexList.end(), categoryLessThan);
1010 }
1011
1012 d->lastIndex = d->categoriesIndexes[d->categories[d->categories.count() - 1]][d->categoriesIndexes[d->categories[d->categories.count() - 1]].count() - 1];
1013
1014 // Finally, fill data information of items situation. This will help when
1015 // trying to compute an item place in the viewport
1016 int i = 0; // position relative to the category beginning
1017 int j = 0; // number of elements before current
1018 foreach (const QString &key, d->categories)
1019 {
1020 foreach (const QModelIndex &index, d->categoriesIndexes[key])
1021 {
1022 struct Private::ElementInfo &elementInfo = d->elementsInfo[index];
1023
1024 elementInfo.relativeOffsetToCategory = i;
1025
1026 d->elementDictionary.insert(d->proxyModel->index(j, 0),
1027 d->proxyModel->mapFromSource(index));
1028
1029 i++;
1030 j++;
1031 }
1032
1033 i = 0;
1034 }
1035
1036 d->updateScrollbars();
1037 }
1038
1039 void KListView::rowsRemoved(const QModelIndex &parent,
1040 int start,
1041 int end)
1042 {
1043 if ((viewMode() == KListView::IconMode) && d->proxyModel &&
1044 d->itemCategorizer)
1045 {
1046 // Force the view to update all elements
1047 rowsInsertedArtifficial(parent, start, end);
1048 }
1049 }
1050
1051 void KListView::updateGeometries()
1052 {
1053 if ((viewMode() != KListView::IconMode) || !d->proxyModel ||
1054 !d->itemCategorizer)
1055 {
1056 QListView::updateGeometries();
1057 return;
1058 }
1059
1060 // Avoid QListView::updateGeometries(), since it will try to set another
1061 // range to our scroll bars, what we don't want (ereslibre)
1062 QAbstractItemView::updateGeometries();
1063 }
1064
1065 void KListView::slotSortingRoleChanged()
1066 {
1067 if ((viewMode() == KListView::IconMode) && d->proxyModel &&
1068 d->itemCategorizer)
1069 {
1070 // Force the view to update all elements
1071 rowsInsertedArtifficial(QModelIndex(), 0, d->proxyModel->rowCount() - 1);
1072 }
1073 }
1074
1075 #include "klistview.moc"