1 /***************************************************************************
2 * Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
4 * Based on the Itemviews NG project from Trolltech Labs: *
5 * http://qt.gitorious.org/qt-labs/itemviews-ng *
7 * This program is free software; you can redistribute it and/or modify *
8 * it under the terms of the GNU General Public License as published by *
9 * the Free Software Foundation; either version 2 of the License, or *
10 * (at your option) any later version. *
12 * This program is distributed in the hope that it will be useful, *
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15 * GNU General Public License for more details. *
17 * You should have received a copy of the GNU General Public License *
18 * along with this program; if not, write to the *
19 * Free Software Foundation, Inc., *
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
21 ***************************************************************************/
23 #include "kitemlistview.h"
25 #include "kitemlistcontroller.h"
26 #include "kitemlistgroupheader.h"
27 #include "kitemlistrubberband_p.h"
28 #include "kitemlistselectionmanager.h"
29 #include "kitemlistsizehintresolver_p.h"
30 #include "kitemlistviewlayouter_p.h"
31 #include "kitemlistviewanimation_p.h"
32 #include "kitemlistwidget.h"
37 #include <QGraphicsSceneMouseEvent>
39 #include <QPropertyAnimation>
41 #include <QStyleOptionRubberBand>
45 // Time in ms until reaching the autoscroll margin triggers
46 // an initial autoscrolling
47 const int InitialAutoScrollDelay
= 700;
49 // Delay in ms for triggering the next autoscroll
50 const int RepeatingAutoScrollDelay
= 1000 / 60;
53 KItemListView::KItemListView(QGraphicsWidget
* parent
) :
54 QGraphicsWidget(parent
),
56 m_activeTransactions(0),
61 m_visibleRolesSizes(),
63 m_groupHeaderCreator(0),
67 m_sizeHintResolver(0),
72 m_oldMaximumOffset(0),
73 m_skipAutoScrollForRubberBand(false),
76 m_autoScrollIncrement(0),
79 setAcceptHoverEvents(true);
81 m_sizeHintResolver
= new KItemListSizeHintResolver(this);
83 m_layouter
= new KItemListViewLayouter(this);
84 m_layouter
->setSizeHintResolver(m_sizeHintResolver
);
86 m_animation
= new KItemListViewAnimation(this);
87 connect(m_animation
, SIGNAL(finished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)),
88 this, SLOT(slotAnimationFinished(QGraphicsWidget
*,KItemListViewAnimation::AnimationType
)));
90 m_layoutTimer
= new QTimer(this);
91 m_layoutTimer
->setInterval(300);
92 m_layoutTimer
->setSingleShot(true);
93 connect(m_layoutTimer
, SIGNAL(timeout()), this, SLOT(slotLayoutTimerFinished()));
95 m_rubberBand
= new KItemListRubberBand(this);
96 connect(m_rubberBand
, SIGNAL(activationChanged(bool)), this, SLOT(slotRubberBandActivationChanged(bool)));
99 KItemListView::~KItemListView()
101 delete m_sizeHintResolver
;
102 m_sizeHintResolver
= 0;
105 void KItemListView::setScrollOrientation(Qt::Orientation orientation
)
107 const Qt::Orientation previousOrientation
= m_layouter
->scrollOrientation();
108 if (orientation
== previousOrientation
) {
112 m_layouter
->setScrollOrientation(orientation
);
113 m_animation
->setScrollOrientation(orientation
);
114 m_sizeHintResolver
->clearCache();
116 onScrollOrientationChanged(orientation
, previousOrientation
);
119 Qt::Orientation
KItemListView::scrollOrientation() const
121 return m_layouter
->scrollOrientation();
124 void KItemListView::setItemSize(const QSizeF
& itemSize
)
126 const QSizeF previousSize
= m_itemSize
;
127 if (itemSize
== previousSize
) {
131 m_itemSize
= itemSize
;
133 if (!markVisibleRolesSizesAsDirty()) {
134 if (itemSize
.width() < previousSize
.width() || itemSize
.height() < previousSize
.height()) {
135 prepareLayoutForIncreasedItemCount(itemSize
, ItemSize
);
137 m_layouter
->setItemSize(itemSize
);
141 m_sizeHintResolver
->clearCache();
143 onItemSizeChanged(itemSize
, previousSize
);
146 QSizeF
KItemListView::itemSize() const
151 void KItemListView::setOffset(qreal offset
)
157 const qreal previousOffset
= m_layouter
->offset();
158 if (offset
== previousOffset
) {
162 m_layouter
->setOffset(offset
);
163 m_animation
->setOffset(offset
);
164 if (!m_layoutTimer
->isActive()) {
165 doLayout(NoAnimation
, 0, 0);
168 onOffsetChanged(offset
, previousOffset
);
171 qreal
KItemListView::offset() const
173 return m_layouter
->offset();
176 qreal
KItemListView::maximumOffset() const
178 return m_layouter
->maximumOffset();
181 void KItemListView::setVisibleRoles(const QHash
<QByteArray
, int>& roles
)
183 const QHash
<QByteArray
, int> previousRoles
= m_visibleRoles
;
184 m_visibleRoles
= roles
;
186 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
187 while (it
.hasNext()) {
189 KItemListWidget
* widget
= it
.value();
190 widget
->setVisibleRoles(roles
);
191 widget
->setVisibleRolesSizes(m_visibleRolesSizes
);
194 m_sizeHintResolver
->clearCache();
195 m_layouter
->markAsDirty();
196 onVisibleRolesChanged(roles
, previousRoles
);
198 markVisibleRolesSizesAsDirty();
202 QHash
<QByteArray
, int> KItemListView::visibleRoles() const
204 return m_visibleRoles
;
207 void KItemListView::setAutoScroll(bool enabled
)
209 if (enabled
&& !m_autoScrollTimer
) {
210 m_autoScrollTimer
= new QTimer(this);
211 m_autoScrollTimer
->setSingleShot(false);
212 connect(m_autoScrollTimer
, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
213 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
214 } else if (!enabled
&& m_autoScrollTimer
) {
215 delete m_autoScrollTimer
;
216 m_autoScrollTimer
= 0;
221 bool KItemListView::autoScroll() const
223 return m_autoScrollTimer
!= 0;
226 KItemListController
* KItemListView::controller() const
231 KItemModelBase
* KItemListView::model() const
236 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase
* widgetCreator
)
238 m_widgetCreator
= widgetCreator
;
241 KItemListWidgetCreatorBase
* KItemListView::widgetCreator() const
243 return m_widgetCreator
;
246 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase
* groupHeaderCreator
)
248 m_groupHeaderCreator
= groupHeaderCreator
;
251 KItemListGroupHeaderCreatorBase
* KItemListView::groupHeaderCreator() const
253 return m_groupHeaderCreator
;
256 void KItemListView::setStyleOption(const KItemListStyleOption
& option
)
258 const KItemListStyleOption previousOption
= m_styleOption
;
259 m_styleOption
= option
;
261 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
262 while (it
.hasNext()) {
264 it
.value()->setStyleOption(option
);
267 m_sizeHintResolver
->clearCache();
269 onStyleOptionChanged(option
, previousOption
);
272 const KItemListStyleOption
& KItemListView::styleOption() const
274 return m_styleOption
;
277 void KItemListView::setGeometry(const QRectF
& rect
)
279 QGraphicsWidget::setGeometry(rect
);
284 if (m_itemSize
.isEmpty()) {
285 m_layouter
->setItemSize(QSizeF());
288 if (m_model
->count() > 0) {
289 prepareLayoutForIncreasedItemCount(rect
.size(), LayouterSize
);
291 m_layouter
->setSize(rect
.size());
294 m_layoutTimer
->start();
297 int KItemListView::itemAt(const QPointF
& pos
) const
299 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
300 while (it
.hasNext()) {
303 const KItemListWidget
* widget
= it
.value();
304 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
305 if (widget
->contains(mappedPos
)) {
313 bool KItemListView::isAboveSelectionToggle(int index
, const QPointF
& pos
) const
320 bool KItemListView::isAboveExpansionToggle(int index
, const QPointF
& pos
) const
322 const KItemListWidget
* widget
= m_visibleItems
.value(index
);
324 const QRectF expansionToggleRect
= widget
->expansionToggleRect();
325 if (!expansionToggleRect
.isEmpty()) {
326 const QPointF mappedPos
= widget
->mapFromItem(this, pos
);
327 return expansionToggleRect
.contains(mappedPos
);
333 int KItemListView::firstVisibleIndex() const
335 return m_layouter
->firstVisibleIndex();
338 int KItemListView::lastVisibleIndex() const
340 return m_layouter
->lastVisibleIndex();
343 QSizeF
KItemListView::itemSizeHint(int index
) const
349 QHash
<QByteArray
, QSizeF
> KItemListView::visibleRoleSizes() const
351 return QHash
<QByteArray
, QSizeF
>();
354 QRectF
KItemListView::itemBoundingRect(int index
) const
356 return m_layouter
->itemBoundingRect(index
);
359 int KItemListView::itemsPerOffset() const
361 return m_layouter
->itemsPerOffset();
364 void KItemListView::beginTransaction()
366 ++m_activeTransactions
;
367 if (m_activeTransactions
== 1) {
368 onTransactionBegin();
372 void KItemListView::endTransaction()
374 --m_activeTransactions
;
375 if (m_activeTransactions
< 0) {
376 m_activeTransactions
= 0;
377 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
380 if (m_activeTransactions
== 0) {
386 bool KItemListView::isTransactionActive() const
388 return m_activeTransactions
> 0;
391 QPixmap
KItemListView::createDragPixmap(const QSet
<int>& indexes
) const
397 void KItemListView::paint(QPainter
* painter
, const QStyleOptionGraphicsItem
* option
, QWidget
* widget
)
399 QGraphicsWidget::paint(painter
, option
, widget
);
401 if (m_rubberBand
->isActive()) {
402 QRectF rubberBandRect
= QRectF(m_rubberBand
->startPosition(),
403 m_rubberBand
->endPosition()).normalized();
405 const QPointF topLeft
= rubberBandRect
.topLeft();
406 if (scrollOrientation() == Qt::Vertical
) {
407 rubberBandRect
.moveTo(topLeft
.x(), topLeft
.y() - offset());
409 rubberBandRect
.moveTo(topLeft
.x() - offset(), topLeft
.y());
412 QStyleOptionRubberBand opt
;
413 opt
.initFrom(widget
);
414 opt
.shape
= QRubberBand::Rectangle
;
416 opt
.rect
= rubberBandRect
.toRect();
417 style()->drawControl(QStyle::CE_RubberBand
, &opt
, painter
);
421 void KItemListView::initializeItemListWidget(KItemListWidget
* item
)
426 void KItemListView::onControllerChanged(KItemListController
* current
, KItemListController
* previous
)
432 void KItemListView::onModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
438 void KItemListView::onScrollOrientationChanged(Qt::Orientation current
, Qt::Orientation previous
)
444 void KItemListView::onItemSizeChanged(const QSizeF
& current
, const QSizeF
& previous
)
450 void KItemListView::onOffsetChanged(qreal current
, qreal previous
)
456 void KItemListView::onVisibleRolesChanged(const QHash
<QByteArray
, int>& current
, const QHash
<QByteArray
, int>& previous
)
462 void KItemListView::onStyleOptionChanged(const KItemListStyleOption
& current
, const KItemListStyleOption
& previous
)
468 void KItemListView::onTransactionBegin()
472 void KItemListView::onTransactionEnd()
476 bool KItemListView::event(QEvent
* event
)
478 // Forward all events to the controller and handle them there
479 if (m_controller
&& m_controller
->processEvent(event
, transform())) {
483 return QGraphicsWidget::event(event
);
486 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent
* event
)
488 m_mousePos
= transform().map(event
->pos());
492 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
)
494 QGraphicsWidget::mouseMoveEvent(event
);
496 m_mousePos
= transform().map(event
->pos());
497 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
498 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
502 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
)
504 event
->setAccepted(true);
508 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
)
510 QGraphicsWidget::dragMoveEvent(event
);
512 m_mousePos
= transform().map(event
->pos());
513 if (m_autoScrollTimer
&& !m_autoScrollTimer
->isActive()) {
514 m_autoScrollTimer
->start(InitialAutoScrollDelay
);
518 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
)
520 QGraphicsWidget::dragLeaveEvent(event
);
521 setAutoScroll(false);
524 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent
* event
)
526 QGraphicsWidget::dropEvent(event
);
527 setAutoScroll(false);
530 QList
<KItemListWidget
*> KItemListView::visibleItemListWidgets() const
532 return m_visibleItems
.values();
535 void KItemListView::slotItemsInserted(const KItemRangeList
& itemRanges
)
537 markVisibleRolesSizesAsDirty();
539 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
540 if (hasMultipleRanges
) {
544 int previouslyInsertedCount
= 0;
545 foreach (const KItemRange
& range
, itemRanges
) {
546 // range.index is related to the model before anything has been inserted.
547 // As in each loop the current item-range gets inserted the index must
548 // be increased by the already previously inserted items.
549 const int index
= range
.index
+ previouslyInsertedCount
;
550 const int count
= range
.count
;
551 if (index
< 0 || count
<= 0) {
552 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
555 previouslyInsertedCount
+= count
;
557 m_sizeHintResolver
->itemsInserted(index
, count
);
559 // Determine which visible items must be moved
560 QList
<int> itemsToMove
;
561 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
562 while (it
.hasNext()) {
564 const int visibleItemIndex
= it
.key();
565 if (visibleItemIndex
>= index
) {
566 itemsToMove
.append(visibleItemIndex
);
570 // Update the indexes of all KItemListWidget instances that are located
571 // after the inserted items. It is important to adjust the indexes in the order
572 // from the highest index to the lowest index to prevent overlaps when setting the new index.
574 for (int i
= itemsToMove
.count() - 1; i
>= 0; --i
) {
575 KItemListWidget
* widget
= m_visibleItems
.value(itemsToMove
[i
]);
577 setWidgetIndex(widget
, widget
->index() + count
);
580 m_layouter
->markAsDirty();
581 if (m_model
->count() == count
&& maximumOffset() > size().height()) {
582 kDebug() << "Scrollbar required, skipping layout";
583 const int scrollBarExtent
= style()->pixelMetric(QStyle::PM_ScrollBarExtent
);
584 QSizeF layouterSize
= m_layouter
->size();
585 if (scrollOrientation() == Qt::Vertical
) {
586 layouterSize
.rwidth() -= scrollBarExtent
;
588 layouterSize
.rheight() -= scrollBarExtent
;
590 m_layouter
->setSize(layouterSize
);
593 if (!hasMultipleRanges
) {
594 doLayout(Animation
, index
, count
);
600 m_controller
->selectionManager()->itemsInserted(itemRanges
);
603 if (hasMultipleRanges
) {
608 void KItemListView::slotItemsRemoved(const KItemRangeList
& itemRanges
)
610 markVisibleRolesSizesAsDirty();
612 const bool hasMultipleRanges
= (itemRanges
.count() > 1);
613 if (hasMultipleRanges
) {
617 for (int i
= itemRanges
.count() - 1; i
>= 0; --i
) {
618 const KItemRange
& range
= itemRanges
.at(i
);
619 const int index
= range
.index
;
620 const int count
= range
.count
;
621 if (index
< 0 || count
<= 0) {
622 kWarning() << "Invalid item range (index:" << index
<< ", count:" << count
<< ")";
626 m_sizeHintResolver
->itemsRemoved(index
, count
);
628 const int firstRemovedIndex
= index
;
629 const int lastRemovedIndex
= index
+ count
- 1;
630 const int lastIndex
= m_model
->count() + count
- 1;
632 // Remove all KItemListWidget instances that got deleted
633 for (int i
= firstRemovedIndex
; i
<= lastRemovedIndex
; ++i
) {
634 KItemListWidget
* widget
= m_visibleItems
.value(i
);
639 m_animation
->stop(widget
);
640 // Stopping the animation might lead to recycling the widget if
641 // it is invisible (see slotAnimationFinished()).
642 // Check again whether it is still visible:
643 if (!m_visibleItems
.contains(i
)) {
647 if (m_model
->count() == 0) {
648 // For performance reasons no animation is done when all items have
650 recycleWidget(widget
);
652 // Animate the removing of the items. Special case: When removing an item there
653 // is no valid model index available anymore. For the
654 // remove-animation the item gets removed from m_visibleItems but the widget
655 // will stay alive until the animation has been finished and will
656 // be recycled (deleted) in KItemListView::slotAnimationFinished().
657 m_visibleItems
.remove(i
);
658 widget
->setIndex(-1);
659 m_animation
->start(widget
, KItemListViewAnimation::DeleteAnimation
);
663 // Update the indexes of all KItemListWidget instances that are located
664 // after the deleted items
665 for (int i
= lastRemovedIndex
+ 1; i
<= lastIndex
; ++i
) {
666 KItemListWidget
* widget
= m_visibleItems
.value(i
);
668 const int newIndex
= i
- count
;
669 setWidgetIndex(widget
, newIndex
);
673 m_layouter
->markAsDirty();
674 if (!hasMultipleRanges
) {
675 doLayout(Animation
, index
, -count
);
681 m_controller
->selectionManager()->itemsRemoved(itemRanges
);
684 if (hasMultipleRanges
) {
689 void KItemListView::slotItemsChanged(const KItemRangeList
& itemRanges
,
690 const QSet
<QByteArray
>& roles
)
692 foreach (const KItemRange
& itemRange
, itemRanges
) {
693 const int index
= itemRange
.index
;
694 const int count
= itemRange
.count
;
696 m_sizeHintResolver
->itemsChanged(index
, count
, roles
);
698 const int lastIndex
= index
+ count
- 1;
699 for (int i
= index
; i
<= lastIndex
; ++i
) {
700 KItemListWidget
* widget
= m_visibleItems
.value(i
);
702 widget
->setData(m_model
->data(i
), roles
);
708 void KItemListView::slotCurrentChanged(int current
, int previous
)
712 KItemListWidget
* previousWidget
= m_visibleItems
.value(previous
, 0);
713 if (previousWidget
) {
714 Q_ASSERT(previousWidget
->isCurrent());
715 previousWidget
->setCurrent(false);
718 KItemListWidget
* currentWidget
= m_visibleItems
.value(current
, 0);
720 Q_ASSERT(!currentWidget
->isCurrent());
721 currentWidget
->setCurrent(true);
724 const QRectF viewGeometry
= geometry();
725 const QRectF currentBoundingRect
= itemBoundingRect(current
);
727 if (!viewGeometry
.contains(currentBoundingRect
)) {
728 // Make sure that the new current item is fully visible in the view.
729 qreal newOffset
= offset();
730 if (currentBoundingRect
.top() < viewGeometry
.top()) {
731 Q_ASSERT(scrollOrientation() == Qt::Vertical
);
732 newOffset
+= currentBoundingRect
.top() - viewGeometry
.top();
734 else if ((currentBoundingRect
.bottom() > viewGeometry
.bottom())) {
735 Q_ASSERT(scrollOrientation() == Qt::Vertical
);
736 newOffset
+= currentBoundingRect
.bottom() - viewGeometry
.bottom();
738 else if (currentBoundingRect
.left() < viewGeometry
.left()) {
739 if (scrollOrientation() == Qt::Horizontal
) {
740 newOffset
+= currentBoundingRect
.left() - viewGeometry
.left();
743 else if ((currentBoundingRect
.right() > viewGeometry
.right())) {
744 if (scrollOrientation() == Qt::Horizontal
) {
745 newOffset
+= currentBoundingRect
.right() - viewGeometry
.right();
749 if (newOffset
!= offset()) {
750 emit
scrollTo(newOffset
);
755 void KItemListView::slotSelectionChanged(const QSet
<int>& current
, const QSet
<int>& previous
)
759 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
760 while (it
.hasNext()) {
762 const int index
= it
.key();
763 KItemListWidget
* widget
= it
.value();
764 widget
->setSelected(current
.contains(index
));
768 void KItemListView::slotAnimationFinished(QGraphicsWidget
* widget
,
769 KItemListViewAnimation::AnimationType type
)
771 KItemListWidget
* itemListWidget
= qobject_cast
<KItemListWidget
*>(widget
);
772 Q_ASSERT(itemListWidget
);
775 case KItemListViewAnimation::DeleteAnimation
: {
776 // As we recycle the widget in this case it is important to assure that no
777 // other animation has been started. This is a convention in KItemListView and
778 // not a requirement defined by KItemListViewAnimation.
779 Q_ASSERT(!m_animation
->isStarted(itemListWidget
));
781 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
782 // by m_visibleWidgets and must be deleted manually after the animation has
784 KItemListGroupHeader
* header
= m_visibleGroups
.value(itemListWidget
);
786 m_groupHeaderCreator
->recycle(header
);
787 m_visibleGroups
.remove(itemListWidget
);
789 m_widgetCreator
->recycle(itemListWidget
);
793 case KItemListViewAnimation::CreateAnimation
:
794 case KItemListViewAnimation::MovingAnimation
:
795 case KItemListViewAnimation::ResizeAnimation
: {
796 const int index
= itemListWidget
->index();
797 const bool invisible
= (index
< m_layouter
->firstVisibleIndex()) ||
798 (index
> m_layouter
->lastVisibleIndex());
799 if (invisible
&& !m_animation
->isStarted(itemListWidget
)) {
800 recycleWidget(itemListWidget
);
809 void KItemListView::slotLayoutTimerFinished()
811 m_layouter
->setSize(geometry().size());
812 doLayout(Animation
, 0, 0);
815 void KItemListView::slotRubberBandPosChanged()
820 void KItemListView::slotRubberBandActivationChanged(bool active
)
823 connect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
824 connect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
825 m_skipAutoScrollForRubberBand
= true;
827 disconnect(m_rubberBand
, SIGNAL(startPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
828 disconnect(m_rubberBand
, SIGNAL(endPositionChanged(QPointF
,QPointF
)), this, SLOT(slotRubberBandPosChanged()));
829 m_skipAutoScrollForRubberBand
= false;
835 void KItemListView::triggerAutoScrolling()
837 if (!m_autoScrollTimer
) {
843 if (scrollOrientation() == Qt::Vertical
) {
844 pos
= m_mousePos
.y();
845 visibleSize
= size().height();
847 pos
= m_mousePos
.x();
848 visibleSize
= size().width();
851 if (m_autoScrollTimer
->interval() == InitialAutoScrollDelay
) {
852 m_autoScrollIncrement
= 0;
855 m_autoScrollIncrement
= calculateAutoScrollingIncrement(pos
, visibleSize
, m_autoScrollIncrement
);
856 if (m_autoScrollIncrement
== 0) {
857 // The mouse position is not above an autoscroll margin (the autoscroll timer
858 // will be restarted in mouseMoveEvent())
859 m_autoScrollTimer
->stop();
863 if (m_rubberBand
->isActive() && m_skipAutoScrollForRubberBand
) {
864 // If a rubberband selection is ongoing the autoscrolling may only get triggered
865 // if the direction of the rubberband is similar to the autoscroll direction. This
866 // prevents that starting to create a rubberband within the autoscroll margins starts
869 const qreal minDiff
= 4; // Ignore any autoscrolling if the rubberband is very small
870 const qreal diff
= (scrollOrientation() == Qt::Vertical
)
871 ? m_rubberBand
->endPosition().y() - m_rubberBand
->startPosition().y()
872 : m_rubberBand
->endPosition().x() - m_rubberBand
->startPosition().x();
873 if (qAbs(diff
) < minDiff
|| (m_autoScrollIncrement
< 0 && diff
> 0) || (m_autoScrollIncrement
> 0 && diff
< 0)) {
874 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
875 // been moved up although the autoscroll direction might be down)
876 m_autoScrollTimer
->stop();
881 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
882 // the autoscrolling may not get skipped anymore until a new rubberband is created
883 m_skipAutoScrollForRubberBand
= false;
885 setOffset(offset() + m_autoScrollIncrement
);
887 // Trigger the autoscroll timer which will periodically call
888 // triggerAutoScrolling()
889 m_autoScrollTimer
->start(RepeatingAutoScrollDelay
);
892 void KItemListView::setController(KItemListController
* controller
)
894 if (m_controller
!= controller
) {
895 KItemListController
* previous
= m_controller
;
897 KItemListSelectionManager
* selectionManager
= previous
->selectionManager();
898 disconnect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
899 disconnect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
902 m_controller
= controller
;
905 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
906 connect(selectionManager
, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
907 connect(selectionManager
, SIGNAL(selectionChanged(QSet
<int>,QSet
<int>)), this, SLOT(slotSelectionChanged(QSet
<int>,QSet
<int>)));
910 onControllerChanged(controller
, previous
);
914 void KItemListView::setModel(KItemModelBase
* model
)
916 if (m_model
== model
) {
920 KItemModelBase
* previous
= m_model
;
923 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
924 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
925 disconnect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
926 this, SLOT(slotItemsInserted(KItemRangeList
)));
927 disconnect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
928 this, SLOT(slotItemsRemoved(KItemRangeList
)));
932 m_layouter
->setModel(model
);
933 m_grouped
= !model
->groupRole().isEmpty();
936 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
937 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
938 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
939 this, SLOT(slotItemsInserted(KItemRangeList
)));
940 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
941 this, SLOT(slotItemsRemoved(KItemRangeList
)));
944 onModelChanged(model
, previous
);
947 KItemListRubberBand
* KItemListView::rubberBand() const
952 void KItemListView::updateLayout()
954 doLayout(Animation
, 0, 0);
958 void KItemListView::doLayout(LayoutAnimationHint hint
, int changedIndex
, int changedCount
)
960 if (m_layoutTimer
->isActive()) {
961 kDebug() << "Stopping layout timer, synchronous layout requested";
962 m_layoutTimer
->stop();
965 if (m_model
->count() < 0 || m_activeTransactions
> 0) {
969 applyDynamicItemSize();
971 const int firstVisibleIndex
= m_layouter
->firstVisibleIndex();
972 const int lastVisibleIndex
= m_layouter
->lastVisibleIndex();
973 if (firstVisibleIndex
< 0) {
978 // Do a sanity check of the offset-property: When properties of the itemlist-view have been changed
979 // it might be possible that the maximum offset got changed too. Assure that the full visible range
980 // is still shown if the maximum offset got decreased.
981 const qreal visibleOffsetRange
= (scrollOrientation() == Qt::Horizontal
) ? size().width() : size().height();
982 const qreal maxOffsetToShowFullRange
= maximumOffset() - visibleOffsetRange
;
983 if (offset() > maxOffsetToShowFullRange
) {
984 m_layouter
->setOffset(qMax(qreal(0), maxOffsetToShowFullRange
));
987 // Determine all items that are completely invisible and might be
988 // reused for items that just got (at least partly) visible.
989 // Items that do e.g. an animated moving of their position are not
990 // marked as invisible: This assures that a scrolling inside the view
991 // can be done without breaking an animation.
992 QList
<int> reusableItems
;
993 QHashIterator
<int, KItemListWidget
*> it(m_visibleItems
);
994 while (it
.hasNext()) {
996 KItemListWidget
* widget
= it
.value();
997 const int index
= widget
->index();
998 const bool invisible
= (index
< firstVisibleIndex
) || (index
> lastVisibleIndex
);
999 if (invisible
&& !m_animation
->isStarted(widget
)) {
1000 widget
->setVisible(false);
1001 reusableItems
.append(index
);
1005 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1006 // instances from invisible items are reused. If no reusable items are
1007 // found then new KItemListWidget instances get created.
1008 const bool animate
= (hint
== Animation
);
1009 for (int i
= firstVisibleIndex
; i
<= lastVisibleIndex
; ++i
) {
1010 bool applyNewPos
= true;
1011 bool wasHidden
= false;
1013 const QRectF itemBounds
= m_layouter
->itemBoundingRect(i
);
1014 const QPointF newPos
= itemBounds
.topLeft();
1015 KItemListWidget
* widget
= m_visibleItems
.value(i
);
1018 if (!reusableItems
.isEmpty()) {
1019 // Reuse a KItemListWidget instance from an invisible item
1020 const int oldIndex
= reusableItems
.takeLast();
1021 widget
= m_visibleItems
.value(oldIndex
);
1022 setWidgetIndex(widget
, i
);
1024 // No reusable KItemListWidget instance is available, create a new one
1025 widget
= createWidget(i
);
1027 widget
->resize(itemBounds
.size());
1029 if (animate
&& changedCount
< 0) {
1030 // Items have been deleted, move the created item to the
1031 // imaginary old position.
1032 const QRectF itemBoundingRect
= m_layouter
->itemBoundingRect(i
- changedCount
);
1033 if (itemBoundingRect
.isEmpty()) {
1034 const QPointF invisibleOldPos
= (scrollOrientation() == Qt::Vertical
)
1035 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1036 widget
->setPos(invisibleOldPos
);
1038 widget
->setPos(itemBoundingRect
.topLeft());
1040 applyNewPos
= false;
1042 } else if (m_animation
->isStarted(widget
, KItemListViewAnimation::MovingAnimation
)) {
1043 applyNewPos
= false;
1047 const bool itemsRemoved
= (changedCount
< 0);
1048 const bool itemsInserted
= (changedCount
> 0);
1050 if (itemsRemoved
&& (i
>= changedIndex
+ changedCount
+ 1)) {
1051 // The item is located after the removed items. Animate the moving of the position.
1052 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1053 applyNewPos
= false;
1054 } else if (itemsInserted
&& i
>= changedIndex
) {
1055 // The item is located after the first inserted item
1056 if (i
<= changedIndex
+ changedCount
- 1) {
1057 // The item is an inserted item. Animate the appearing of the item.
1058 // For performance reasons no animation is done when changedCount is equal
1059 // to all available items.
1060 if (changedCount
< m_model
->count()) {
1061 m_animation
->start(widget
, KItemListViewAnimation::CreateAnimation
);
1063 } else if (!m_animation
->isStarted(widget
, KItemListViewAnimation::CreateAnimation
)) {
1064 // The item was already there before, so animate the moving of the position.
1065 // No moving animation is done if the item is animated by a create animation: This
1066 // prevents a "move animation mess" when inserting several ranges in parallel.
1067 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1068 applyNewPos
= false;
1070 } else if (!itemsRemoved
&& !itemsInserted
&& !wasHidden
) {
1071 // The size of the view might have been changed. Animate the moving of the position.
1072 m_animation
->start(widget
, KItemListViewAnimation::MovingAnimation
, newPos
);
1073 applyNewPos
= false;
1078 widget
->setPos(newPos
);
1081 Q_ASSERT(widget
->index() == i
);
1082 widget
->setVisible(true);
1084 if (widget
->size() != itemBounds
.size()) {
1085 m_animation
->start(widget
, KItemListViewAnimation::ResizeAnimation
, itemBounds
.size());
1089 // Delete invisible KItemListWidget instances that have not been reused
1090 foreach (int index
, reusableItems
) {
1091 recycleWidget(m_visibleItems
.value(index
));
1094 emitOffsetChanges();
1097 void KItemListView::emitOffsetChanges()
1099 const qreal newOffset
= m_layouter
->offset();
1100 if (m_oldOffset
!= newOffset
) {
1101 emit
offsetChanged(newOffset
, m_oldOffset
);
1102 m_oldOffset
= newOffset
;
1105 const qreal newMaximumOffset
= m_layouter
->maximumOffset();
1106 if (m_oldMaximumOffset
!= newMaximumOffset
) {
1107 emit
maximumOffsetChanged(newMaximumOffset
, m_oldMaximumOffset
);
1108 m_oldMaximumOffset
= newMaximumOffset
;
1112 KItemListWidget
* KItemListView::createWidget(int index
)
1114 KItemListWidget
* widget
= m_widgetCreator
->create(this);
1115 updateWidgetProperties(widget
, index
);
1116 m_visibleItems
.insert(index
, widget
);
1119 if (m_layouter
->isFirstGroupItem(index
)) {
1120 KItemListGroupHeader
* header
= m_groupHeaderCreator
->create(widget
);
1121 header
->setPos(0, -50);
1122 header
->resize(50, 50);
1123 m_visibleGroups
.insert(widget
, header
);
1127 initializeItemListWidget(widget
);
1131 void KItemListView::recycleWidget(KItemListWidget
* widget
)
1134 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1136 m_groupHeaderCreator
->recycle(header
);
1137 m_visibleGroups
.remove(widget
);
1141 m_visibleItems
.remove(widget
->index());
1142 m_widgetCreator
->recycle(widget
);
1145 void KItemListView::setWidgetIndex(KItemListWidget
* widget
, int index
)
1148 bool createHeader
= m_layouter
->isFirstGroupItem(index
);
1149 KItemListGroupHeader
* header
= m_visibleGroups
.value(widget
);
1152 createHeader
= false;
1154 m_groupHeaderCreator
->recycle(header
);
1155 m_visibleGroups
.remove(widget
);
1160 KItemListGroupHeader
* header
= m_groupHeaderCreator
->create(widget
);
1161 header
->setPos(0, -50);
1162 header
->resize(50, 50);
1163 m_visibleGroups
.insert(widget
, header
);
1167 const int oldIndex
= widget
->index();
1168 m_visibleItems
.remove(oldIndex
);
1169 updateWidgetProperties(widget
, index
);
1170 m_visibleItems
.insert(index
, widget
);
1172 initializeItemListWidget(widget
);
1175 void KItemListView::prepareLayoutForIncreasedItemCount(const QSizeF
& size
, SizeType sizeType
)
1177 // Calculate the first visible index and last visible index for the current size
1178 const int currentFirst
= m_layouter
->firstVisibleIndex();
1179 const int currentLast
= m_layouter
->lastVisibleIndex();
1181 const QSizeF currentSize
= (sizeType
== LayouterSize
) ? m_layouter
->size() : m_layouter
->itemSize();
1183 // Calculate the first visible index and last visible index for the new size
1184 setLayouterSize(size
, sizeType
);
1185 const int newFirst
= m_layouter
->firstVisibleIndex();
1186 const int newLast
= m_layouter
->lastVisibleIndex();
1188 if ((currentFirst
!= newFirst
) || (currentLast
!= newLast
)) {
1189 // At least one index has been changed. Assure that widgets for all possible
1190 // visible items get created so that a move-animation can be started later.
1191 const int maxVisibleItems
= m_layouter
->maximumVisibleItems();
1192 int minFirst
= qMin(newFirst
, currentFirst
);
1193 const int maxLast
= qMax(newLast
, currentLast
);
1195 if (maxLast
- minFirst
+ 1 < maxVisibleItems
) {
1196 // Increasing the size might result in a smaller KItemListView::offset().
1197 // Decrease the first visible index in a way that at least the maximum
1198 // visible items are shown.
1199 minFirst
= qMax(0, maxLast
- maxVisibleItems
+ 1);
1202 if (maxLast
- minFirst
> maxVisibleItems
+ maxVisibleItems
/ 2) {
1203 // The creating of widgets is quite expensive. Assure that never more
1204 // than 50 % of the maximum visible items get created for the animations.
1208 setLayouterSize(currentSize
, sizeType
);
1209 for (int i
= minFirst
; i
<= maxLast
; ++i
) {
1210 if (!m_visibleItems
.contains(i
)) {
1211 KItemListWidget
* widget
= createWidget(i
);
1212 const QPointF pos
= m_layouter
->itemBoundingRect(i
).topLeft();
1213 widget
->setPos(pos
);
1216 setLayouterSize(size
, sizeType
);
1220 void KItemListView::setLayouterSize(const QSizeF
& size
, SizeType sizeType
)
1223 case LayouterSize
: m_layouter
->setSize(size
); break;
1224 case ItemSize
: m_layouter
->setItemSize(size
); break;
1229 bool KItemListView::markVisibleRolesSizesAsDirty()
1231 const bool dirty
= m_itemSize
.isEmpty();
1233 m_visibleRolesSizes
.clear();
1234 m_layouter
->setItemSize(QSizeF());
1239 void KItemListView::applyDynamicItemSize()
1241 if (!m_itemSize
.isEmpty()) {
1245 if (m_visibleRolesSizes
.isEmpty()) {
1246 m_visibleRolesSizes
= visibleRoleSizes();
1247 foreach (KItemListWidget
* widget
, visibleItemListWidgets()) {
1248 widget
->setVisibleRolesSizes(m_visibleRolesSizes
);
1252 if (m_layouter
->itemSize().isEmpty()) {
1253 qreal requiredWidth
= 0;
1254 qreal requiredHeight
= 0;
1256 QHashIterator
<QByteArray
, QSizeF
> it(m_visibleRolesSizes
);
1257 while (it
.hasNext()) {
1259 const QSizeF
& visibleRoleSize
= it
.value();
1260 requiredWidth
+= visibleRoleSize
.width();
1261 requiredHeight
+= visibleRoleSize
.height();
1264 QSizeF dynamicItemSize
= m_itemSize
;
1265 if (dynamicItemSize
.width() <= 0) {
1266 dynamicItemSize
.setWidth(qMax(requiredWidth
, size().width()));
1268 if (dynamicItemSize
.height() <= 0) {
1269 dynamicItemSize
.setHeight(qMax(requiredHeight
, size().height()));
1272 m_layouter
->setItemSize(dynamicItemSize
);
1276 void KItemListView::updateWidgetProperties(KItemListWidget
* widget
, int index
)
1278 widget
->setVisibleRoles(m_visibleRoles
);
1279 widget
->setVisibleRolesSizes(m_visibleRolesSizes
);
1280 widget
->setStyleOption(m_styleOption
);
1282 const KItemListSelectionManager
* selectionManager
= m_controller
->selectionManager();
1283 widget
->setCurrent(index
== selectionManager
->currentItem());
1285 if (selectionManager
->hasSelection()) {
1286 const QSet
<int> selectedItems
= selectionManager
->selectedItems();
1287 widget
->setSelected(selectedItems
.contains(index
));
1289 widget
->setSelected(false);
1292 widget
->setHovered(false);
1294 widget
->setIndex(index
);
1295 widget
->setData(m_model
->data(index
));
1298 int KItemListView::calculateAutoScrollingIncrement(int pos
, int range
, int oldInc
)
1302 const int minSpeed
= 4;
1303 const int maxSpeed
= 128;
1304 const int speedLimiter
= 96;
1305 const int autoScrollBorder
= 64;
1307 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
1308 // This assures that the autoscrolling speed grows gradually.
1309 const int incLimiter
= 1;
1311 if (pos
< autoScrollBorder
) {
1312 inc
= -minSpeed
+ qAbs(pos
- autoScrollBorder
) * (pos
- autoScrollBorder
) / speedLimiter
;
1313 inc
= qMax(inc
, -maxSpeed
);
1314 inc
= qMax(inc
, oldInc
- incLimiter
);
1315 } else if (pos
> range
- autoScrollBorder
) {
1316 inc
= minSpeed
+ qAbs(pos
- range
+ autoScrollBorder
) * (pos
- range
+ autoScrollBorder
) / speedLimiter
;
1317 inc
= qMin(inc
, maxSpeed
);
1318 inc
= qMin(inc
, oldInc
+ incLimiter
);
1325 KItemListCreatorBase::~KItemListCreatorBase()
1327 qDeleteAll(m_recycleableWidgets
);
1328 qDeleteAll(m_createdWidgets
);
1331 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget
* widget
)
1333 m_createdWidgets
.insert(widget
);
1336 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget
* widget
)
1338 Q_ASSERT(m_createdWidgets
.contains(widget
));
1339 m_createdWidgets
.remove(widget
);
1341 if (m_recycleableWidgets
.count() < 100) {
1342 m_recycleableWidgets
.append(widget
);
1343 widget
->setVisible(false);
1349 QGraphicsWidget
* KItemListCreatorBase::popRecycleableWidget()
1351 if (m_recycleableWidgets
.isEmpty()) {
1355 QGraphicsWidget
* widget
= m_recycleableWidgets
.takeLast();
1356 m_createdWidgets
.insert(widget
);
1360 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
1364 void KItemListWidgetCreatorBase::recycle(KItemListWidget
* widget
)
1366 widget
->setOpacity(1.0);
1367 pushRecycleableWidget(widget
);
1370 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
1374 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader
* header
)
1376 header
->setOpacity(1.0);
1377 pushRecycleableWidget(header
);
1380 #include "kitemlistview.moc"