]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kitemlistview.cpp
Animation optimizations
[dolphin.git] / src / kitemviews / kitemlistview.cpp
1 /***************************************************************************
2 * Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
3 * *
4 * Based on the Itemviews NG project from Trolltech Labs: *
5 * http://qt.gitorious.org/qt-labs/itemviews-ng *
6 * *
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. *
11 * *
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. *
16 * *
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 ***************************************************************************/
22
23 #include "kitemlistview.h"
24
25 #include "kitemlistcontroller.h"
26 #include "kitemlistheader_p.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"
33
34 #include <KDebug>
35
36 #include <QCursor>
37 #include <QGraphicsSceneMouseEvent>
38 #include <QPainter>
39 #include <QPropertyAnimation>
40 #include <QStyle>
41 #include <QStyleOptionRubberBand>
42 #include <QTimer>
43
44 namespace {
45 // Time in ms until reaching the autoscroll margin triggers
46 // an initial autoscrolling
47 const int InitialAutoScrollDelay = 700;
48
49 // Delay in ms for triggering the next autoscroll
50 const int RepeatingAutoScrollDelay = 1000 / 60;
51 }
52
53 KItemListView::KItemListView(QGraphicsWidget* parent) :
54 QGraphicsWidget(parent),
55 m_enabledSelectionToggles(false),
56 m_grouped(false),
57 m_activeTransactions(0),
58 m_itemSize(),
59 m_controller(0),
60 m_model(0),
61 m_visibleRoles(),
62 m_visibleRolesSizes(),
63 m_stretchedVisibleRolesSizes(),
64 m_widgetCreator(0),
65 m_groupHeaderCreator(0),
66 m_styleOption(),
67 m_visibleItems(),
68 m_visibleGroups(),
69 m_sizeHintResolver(0),
70 m_layouter(0),
71 m_animation(0),
72 m_layoutTimer(0),
73 m_oldScrollOffset(0),
74 m_oldMaximumScrollOffset(0),
75 m_oldItemOffset(0),
76 m_oldMaximumItemOffset(0),
77 m_skipAutoScrollForRubberBand(false),
78 m_rubberBand(0),
79 m_mousePos(),
80 m_autoScrollIncrement(0),
81 m_autoScrollTimer(0),
82 m_header(0),
83 m_useHeaderWidths(false)
84 {
85 setAcceptHoverEvents(true);
86
87 m_sizeHintResolver = new KItemListSizeHintResolver(this);
88
89 m_layouter = new KItemListViewLayouter(this);
90 m_layouter->setSizeHintResolver(m_sizeHintResolver);
91
92 m_animation = new KItemListViewAnimation(this);
93 connect(m_animation, SIGNAL(finished(QGraphicsWidget*,KItemListViewAnimation::AnimationType)),
94 this, SLOT(slotAnimationFinished(QGraphicsWidget*,KItemListViewAnimation::AnimationType)));
95
96 m_layoutTimer = new QTimer(this);
97 m_layoutTimer->setInterval(300);
98 m_layoutTimer->setSingleShot(true);
99 connect(m_layoutTimer, SIGNAL(timeout()), this, SLOT(slotLayoutTimerFinished()));
100
101 m_rubberBand = new KItemListRubberBand(this);
102 connect(m_rubberBand, SIGNAL(activationChanged(bool)), this, SLOT(slotRubberBandActivationChanged(bool)));
103 }
104
105 KItemListView::~KItemListView()
106 {
107 delete m_sizeHintResolver;
108 m_sizeHintResolver = 0;
109 }
110
111 void KItemListView::setScrollOrientation(Qt::Orientation orientation)
112 {
113 const Qt::Orientation previousOrientation = m_layouter->scrollOrientation();
114 if (orientation == previousOrientation) {
115 return;
116 }
117
118 m_layouter->setScrollOrientation(orientation);
119 m_animation->setScrollOrientation(orientation);
120 m_sizeHintResolver->clearCache();
121
122 if (m_grouped) {
123 QMutableHashIterator<KItemListWidget*, KItemListGroupHeader*> it (m_visibleGroups);
124 while (it.hasNext()) {
125 it.next();
126 it.value()->setScrollOrientation(orientation);
127 }
128 }
129
130 doLayout(Animation);
131
132 onScrollOrientationChanged(orientation, previousOrientation);
133 emit scrollOrientationChanged(orientation, previousOrientation);
134 }
135
136 Qt::Orientation KItemListView::scrollOrientation() const
137 {
138 return m_layouter->scrollOrientation();
139 }
140
141 void KItemListView::setItemSize(const QSizeF& itemSize)
142 {
143 const QSizeF previousSize = m_itemSize;
144 if (itemSize == previousSize) {
145 return;
146 }
147
148 m_itemSize = itemSize;
149
150 if (itemSize.isEmpty()) {
151 updateVisibleRolesSizes();
152 } else {
153 m_layouter->setItemSize(itemSize);
154 }
155
156 m_sizeHintResolver->clearCache();
157 doLayout(Animation);
158 onItemSizeChanged(itemSize, previousSize);
159 }
160
161 QSizeF KItemListView::itemSize() const
162 {
163 return m_itemSize;
164 }
165
166 void KItemListView::setScrollOffset(qreal offset)
167 {
168 if (offset < 0) {
169 offset = 0;
170 }
171
172 const qreal previousOffset = m_layouter->scrollOffset();
173 if (offset == previousOffset) {
174 return;
175 }
176
177 m_layouter->setScrollOffset(offset);
178 m_animation->setScrollOffset(offset);
179
180 // Don't check whether the m_layoutTimer is active: Changing the
181 // scroll offset must always trigger a synchronous layout, otherwise
182 // the smooth-scrolling might get jerky.
183 doLayout(NoAnimation);
184 onScrollOffsetChanged(offset, previousOffset);
185 }
186
187 qreal KItemListView::scrollOffset() const
188 {
189 return m_layouter->scrollOffset();
190 }
191
192 qreal KItemListView::maximumScrollOffset() const
193 {
194 return m_layouter->maximumScrollOffset();
195 }
196
197 void KItemListView::setItemOffset(qreal offset)
198 {
199 if (m_layouter->itemOffset() == offset) {
200 return;
201 }
202
203 m_layouter->setItemOffset(offset);
204 if (m_header) {
205 m_header->setPos(-offset, 0);
206 }
207
208 // Don't check whether the m_layoutTimer is active: Changing the
209 // item offset must always trigger a synchronous layout, otherwise
210 // the smooth-scrolling might get jerky.
211 doLayout(NoAnimation);
212 }
213
214 qreal KItemListView::itemOffset() const
215 {
216 return m_layouter->itemOffset();
217 }
218
219 qreal KItemListView::maximumItemOffset() const
220 {
221 return m_layouter->maximumItemOffset();
222 }
223
224 void KItemListView::setVisibleRoles(const QList<QByteArray>& roles)
225 {
226 const QList<QByteArray> previousRoles = m_visibleRoles;
227 m_visibleRoles = roles;
228
229 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
230 while (it.hasNext()) {
231 it.next();
232 KItemListWidget* widget = it.value();
233 widget->setVisibleRoles(roles);
234 widget->setVisibleRolesSizes(m_stretchedVisibleRolesSizes);
235 }
236
237 m_sizeHintResolver->clearCache();
238 m_layouter->markAsDirty();
239
240 if (m_header) {
241 m_header->setVisibleRoles(roles);
242 m_header->setVisibleRolesWidths(headerRolesWidths());
243 m_useHeaderWidths = false;
244 }
245
246 updateVisibleRolesSizes();
247 doLayout(Animation);
248
249 onVisibleRolesChanged(roles, previousRoles);
250 }
251
252 QList<QByteArray> KItemListView::visibleRoles() const
253 {
254 return m_visibleRoles;
255 }
256
257 void KItemListView::setAutoScroll(bool enabled)
258 {
259 if (enabled && !m_autoScrollTimer) {
260 m_autoScrollTimer = new QTimer(this);
261 m_autoScrollTimer->setSingleShot(false);
262 connect(m_autoScrollTimer, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
263 m_autoScrollTimer->start(InitialAutoScrollDelay);
264 } else if (!enabled && m_autoScrollTimer) {
265 delete m_autoScrollTimer;
266 m_autoScrollTimer = 0;
267 }
268
269 }
270
271 bool KItemListView::autoScroll() const
272 {
273 return m_autoScrollTimer != 0;
274 }
275
276 void KItemListView::setEnabledSelectionToggles(bool enabled)
277 {
278 if (m_enabledSelectionToggles != enabled) {
279 m_enabledSelectionToggles = enabled;
280
281 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
282 while (it.hasNext()) {
283 it.next();
284 it.value()->setEnabledSelectionToggle(enabled);
285 }
286 }
287 }
288
289 bool KItemListView::enabledSelectionToggles() const
290 {
291 return m_enabledSelectionToggles;
292 }
293
294 KItemListController* KItemListView::controller() const
295 {
296 return m_controller;
297 }
298
299 KItemModelBase* KItemListView::model() const
300 {
301 return m_model;
302 }
303
304 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase* widgetCreator)
305 {
306 m_widgetCreator = widgetCreator;
307 }
308
309 KItemListWidgetCreatorBase* KItemListView::widgetCreator() const
310 {
311 return m_widgetCreator;
312 }
313
314 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase* groupHeaderCreator)
315 {
316 m_groupHeaderCreator = groupHeaderCreator;
317 }
318
319 KItemListGroupHeaderCreatorBase* KItemListView::groupHeaderCreator() const
320 {
321 return m_groupHeaderCreator;
322 }
323
324 void KItemListView::setStyleOption(const KItemListStyleOption& option)
325 {
326 const KItemListStyleOption previousOption = m_styleOption;
327 m_styleOption = option;
328
329 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
330 while (it.hasNext()) {
331 it.next();
332 it.value()->setStyleOption(option);
333 }
334
335 m_sizeHintResolver->clearCache();
336 doLayout(Animation);
337 onStyleOptionChanged(option, previousOption);
338 }
339
340 const KItemListStyleOption& KItemListView::styleOption() const
341 {
342 return m_styleOption;
343 }
344
345 void KItemListView::setGeometry(const QRectF& rect)
346 {
347 QGraphicsWidget::setGeometry(rect);
348
349 if (!m_model) {
350 return;
351 }
352
353 const QSizeF newSize = rect.size();
354 if (m_itemSize.isEmpty()) {
355 // The item size is dynamic:
356 // Changing the geometry does not require to do an expensive
357 // update of the visible-roles sizes, only the stretched sizes
358 // need to be adjusted to the new size.
359 updateStretchedVisibleRolesSizes();
360
361 if (m_useHeaderWidths) {
362 QSizeF dynamicItemSize = m_layouter->itemSize();
363
364 if (m_itemSize.width() < 0) {
365 const qreal requiredWidth = visibleRolesSizesWidthSum();
366 if (newSize.width() > requiredWidth) {
367 dynamicItemSize.setWidth(newSize.width());
368 }
369 const qreal headerWidth = qMax(newSize.width(), requiredWidth);
370 m_header->resize(headerWidth, m_header->size().height());
371 }
372
373 if (m_itemSize.height() < 0) {
374 const qreal requiredHeight = visibleRolesSizesHeightSum();
375 if (newSize.height() > requiredHeight) {
376 dynamicItemSize.setHeight(newSize.height());
377 }
378 // TODO: KItemListHeader is not prepared for vertical alignment
379 }
380
381 m_layouter->setItemSize(dynamicItemSize);
382 }
383
384 // Triggering a synchronous layout is fine from a performance point of view,
385 // as with dynamic item sizes no moving animation must be done.
386 m_layouter->setSize(newSize);
387 doLayout(Animation);
388 } else {
389 // The item size is not dynamic and most probably the geometry change results
390 // in animated position changes of the items. Trigger an asynchronous relayout
391 // with m_layoutTimer to prevent performance bottlenecks.
392 m_layouter->setSize(newSize);
393 if (!m_layoutTimer->isActive()) {
394 m_layoutTimer->start();
395 }
396 }
397 }
398
399 int KItemListView::itemAt(const QPointF& pos) const
400 {
401 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
402 while (it.hasNext()) {
403 it.next();
404
405 const KItemListWidget* widget = it.value();
406 const QPointF mappedPos = widget->mapFromItem(this, pos);
407 if (widget->contains(mappedPos)) {
408 return it.key();
409 }
410 }
411
412 return -1;
413 }
414
415 bool KItemListView::isAboveSelectionToggle(int index, const QPointF& pos) const
416 {
417 if (!m_enabledSelectionToggles) {
418 return false;
419 }
420
421 const KItemListWidget* widget = m_visibleItems.value(index);
422 if (widget) {
423 const QRectF selectionToggleRect = widget->selectionToggleRect();
424 if (!selectionToggleRect.isEmpty()) {
425 const QPointF mappedPos = widget->mapFromItem(this, pos);
426 return selectionToggleRect.contains(mappedPos);
427 }
428 }
429 return false;
430 }
431
432 bool KItemListView::isAboveExpansionToggle(int index, const QPointF& pos) const
433 {
434 const KItemListWidget* widget = m_visibleItems.value(index);
435 if (widget) {
436 const QRectF expansionToggleRect = widget->expansionToggleRect();
437 if (!expansionToggleRect.isEmpty()) {
438 const QPointF mappedPos = widget->mapFromItem(this, pos);
439 return expansionToggleRect.contains(mappedPos);
440 }
441 }
442 return false;
443 }
444
445 int KItemListView::firstVisibleIndex() const
446 {
447 return m_layouter->firstVisibleIndex();
448 }
449
450 int KItemListView::lastVisibleIndex() const
451 {
452 return m_layouter->lastVisibleIndex();
453 }
454
455 QSizeF KItemListView::itemSizeHint(int index) const
456 {
457 Q_UNUSED(index);
458 return itemSize();
459 }
460
461 QHash<QByteArray, QSizeF> KItemListView::visibleRolesSizes(const KItemRangeList& itemRanges) const
462 {
463 Q_UNUSED(itemRanges);
464 return QHash<QByteArray, QSizeF>();
465 }
466
467 bool KItemListView::supportsItemExpanding() const
468 {
469 return false;
470 }
471
472 QRectF KItemListView::itemRect(int index) const
473 {
474 return m_layouter->itemRect(index);
475 }
476
477 QRectF KItemListView::itemContextRect(int index) const
478 {
479 QRectF contextRect;
480
481 const KItemListWidget* widget = m_visibleItems.value(index);
482 if (widget) {
483 contextRect = widget->iconRect() | widget->textRect();
484 contextRect.translate(itemRect(index).topLeft());
485 }
486
487 return contextRect;
488 }
489
490 void KItemListView::scrollToItem(int index)
491 {
492 QRectF viewGeometry = geometry();
493 if (m_header) {
494 const qreal headerHeight = m_header->size().height();
495 viewGeometry.adjust(0, headerHeight, 0, 0);
496 }
497 const QRectF currentRect = itemRect(index);
498
499 if (!viewGeometry.contains(currentRect)) {
500 qreal newOffset = scrollOffset();
501 if (scrollOrientation() == Qt::Vertical) {
502 if (currentRect.top() < viewGeometry.top()) {
503 newOffset += currentRect.top() - viewGeometry.top();
504 } else if (currentRect.bottom() > viewGeometry.bottom()) {
505 newOffset += currentRect.bottom() - viewGeometry.bottom();
506 }
507 } else {
508 if (currentRect.left() < viewGeometry.left()) {
509 newOffset += currentRect.left() - viewGeometry.left();
510 } else if (currentRect.right() > viewGeometry.right()) {
511 newOffset += currentRect.right() - viewGeometry.right();
512 }
513 }
514
515 if (newOffset != scrollOffset()) {
516 emit scrollTo(newOffset);
517 }
518 }
519 }
520
521 void KItemListView::beginTransaction()
522 {
523 ++m_activeTransactions;
524 if (m_activeTransactions == 1) {
525 onTransactionBegin();
526 }
527 }
528
529 void KItemListView::endTransaction()
530 {
531 --m_activeTransactions;
532 if (m_activeTransactions < 0) {
533 m_activeTransactions = 0;
534 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
535 }
536
537 if (m_activeTransactions == 0) {
538 onTransactionEnd();
539 doLayout(Animation);
540 }
541 }
542
543 bool KItemListView::isTransactionActive() const
544 {
545 return m_activeTransactions > 0;
546 }
547
548
549 void KItemListView::setHeaderShown(bool show)
550 {
551
552 if (show && !m_header) {
553 m_header = new KItemListHeader(this);
554 m_header->setPos(0, 0);
555 m_header->setModel(m_model);
556 m_header->setVisibleRoles(m_visibleRoles);
557 m_header->setVisibleRolesWidths(headerRolesWidths());
558 m_header->setZValue(1);
559
560 connect(m_header, SIGNAL(visibleRoleWidthChanged(QByteArray,qreal,qreal)),
561 this, SLOT(slotVisibleRoleWidthChanged(QByteArray,qreal,qreal)));
562 connect(m_header, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)),
563 this, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)));
564 connect(m_header, SIGNAL(sortRoleChanged(QByteArray,QByteArray)),
565 this, SIGNAL(sortRoleChanged(QByteArray,QByteArray)));
566
567 m_useHeaderWidths = false;
568
569 m_layouter->setHeaderHeight(m_header->size().height());
570 } else if (!show && m_header) {
571 delete m_header;
572 m_header = 0;
573 m_useHeaderWidths = false;
574 m_layouter->setHeaderHeight(0);
575 }
576 }
577
578 bool KItemListView::isHeaderShown() const
579 {
580 return m_header != 0;
581 }
582
583 QPixmap KItemListView::createDragPixmap(const QSet<int>& indexes) const
584 {
585 Q_UNUSED(indexes);
586 return QPixmap();
587 }
588
589 void KItemListView::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
590 {
591 QGraphicsWidget::paint(painter, option, widget);
592
593 if (m_rubberBand->isActive()) {
594 QRectF rubberBandRect = QRectF(m_rubberBand->startPosition(),
595 m_rubberBand->endPosition()).normalized();
596
597 const QPointF topLeft = rubberBandRect.topLeft();
598 if (scrollOrientation() == Qt::Vertical) {
599 rubberBandRect.moveTo(topLeft.x(), topLeft.y() - scrollOffset());
600 } else {
601 rubberBandRect.moveTo(topLeft.x() - scrollOffset(), topLeft.y());
602 }
603
604 QStyleOptionRubberBand opt;
605 opt.initFrom(widget);
606 opt.shape = QRubberBand::Rectangle;
607 opt.opaque = false;
608 opt.rect = rubberBandRect.toRect();
609 style()->drawControl(QStyle::CE_RubberBand, &opt, painter);
610 }
611 }
612
613 void KItemListView::initializeItemListWidget(KItemListWidget* item)
614 {
615 Q_UNUSED(item);
616 }
617
618 bool KItemListView::itemSizeHintUpdateRequired(const QSet<QByteArray>& changedRoles) const
619 {
620 Q_UNUSED(changedRoles);
621 return true;
622 }
623
624 void KItemListView::onControllerChanged(KItemListController* current, KItemListController* previous)
625 {
626 Q_UNUSED(current);
627 Q_UNUSED(previous);
628 }
629
630 void KItemListView::onModelChanged(KItemModelBase* current, KItemModelBase* previous)
631 {
632 Q_UNUSED(current);
633 Q_UNUSED(previous);
634 }
635
636 void KItemListView::onScrollOrientationChanged(Qt::Orientation current, Qt::Orientation previous)
637 {
638 Q_UNUSED(current);
639 Q_UNUSED(previous);
640 }
641
642 void KItemListView::onItemSizeChanged(const QSizeF& current, const QSizeF& previous)
643 {
644 Q_UNUSED(current);
645 Q_UNUSED(previous);
646 }
647
648 void KItemListView::onScrollOffsetChanged(qreal current, qreal previous)
649 {
650 Q_UNUSED(current);
651 Q_UNUSED(previous);
652 }
653
654 void KItemListView::onVisibleRolesChanged(const QList<QByteArray>& current, const QList<QByteArray>& previous)
655 {
656 Q_UNUSED(current);
657 Q_UNUSED(previous);
658 }
659
660 void KItemListView::onStyleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous)
661 {
662 Q_UNUSED(current);
663 Q_UNUSED(previous);
664 }
665
666 void KItemListView::onTransactionBegin()
667 {
668 }
669
670 void KItemListView::onTransactionEnd()
671 {
672 }
673
674 bool KItemListView::event(QEvent* event)
675 {
676 // Forward all events to the controller and handle them there
677 if (m_controller && m_controller->processEvent(event, transform())) {
678 event->accept();
679 return true;
680 }
681 return QGraphicsWidget::event(event);
682 }
683
684 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent* event)
685 {
686 m_mousePos = transform().map(event->pos());
687 event->accept();
688 }
689
690 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
691 {
692 QGraphicsWidget::mouseMoveEvent(event);
693
694 m_mousePos = transform().map(event->pos());
695 if (m_autoScrollTimer && !m_autoScrollTimer->isActive()) {
696 m_autoScrollTimer->start(InitialAutoScrollDelay);
697 }
698 }
699
700 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent* event)
701 {
702 event->setAccepted(true);
703 setAutoScroll(true);
704 }
705
706 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent *event)
707 {
708 QGraphicsWidget::dragMoveEvent(event);
709
710 m_mousePos = transform().map(event->pos());
711 if (m_autoScrollTimer && !m_autoScrollTimer->isActive()) {
712 m_autoScrollTimer->start(InitialAutoScrollDelay);
713 }
714 }
715
716 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
717 {
718 QGraphicsWidget::dragLeaveEvent(event);
719 setAutoScroll(false);
720 }
721
722 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent* event)
723 {
724 QGraphicsWidget::dropEvent(event);
725 setAutoScroll(false);
726 }
727
728 QList<KItemListWidget*> KItemListView::visibleItemListWidgets() const
729 {
730 return m_visibleItems.values();
731 }
732
733 void KItemListView::slotItemsInserted(const KItemRangeList& itemRanges)
734 {
735 updateVisibleRolesSizes(itemRanges);
736
737 const bool hasMultipleRanges = (itemRanges.count() > 1);
738 if (hasMultipleRanges) {
739 beginTransaction();
740 }
741
742 int previouslyInsertedCount = 0;
743 foreach (const KItemRange& range, itemRanges) {
744 // range.index is related to the model before anything has been inserted.
745 // As in each loop the current item-range gets inserted the index must
746 // be increased by the already previously inserted items.
747 const int index = range.index + previouslyInsertedCount;
748 const int count = range.count;
749 if (index < 0 || count <= 0) {
750 kWarning() << "Invalid item range (index:" << index << ", count:" << count << ")";
751 continue;
752 }
753 previouslyInsertedCount += count;
754
755 m_sizeHintResolver->itemsInserted(index, count);
756
757 // Determine which visible items must be moved
758 QList<int> itemsToMove;
759 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
760 while (it.hasNext()) {
761 it.next();
762 const int visibleItemIndex = it.key();
763 if (visibleItemIndex >= index) {
764 itemsToMove.append(visibleItemIndex);
765 }
766 }
767
768 // Update the indexes of all KItemListWidget instances that are located
769 // after the inserted items. It is important to adjust the indexes in the order
770 // from the highest index to the lowest index to prevent overlaps when setting the new index.
771 qSort(itemsToMove);
772 for (int i = itemsToMove.count() - 1; i >= 0; --i) {
773 KItemListWidget* widget = m_visibleItems.value(itemsToMove[i]);
774 Q_ASSERT(widget);
775 setWidgetIndex(widget, widget->index() + count);
776 }
777
778 m_layouter->markAsDirty();
779 if (m_model->count() == count && m_activeTransactions == 0) {
780 // Check whether a scrollbar is required to show the inserted items. In this case
781 // the size of the layouter will be decreased before calling doLayout(): This prevents
782 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
783 const bool verticalScrollOrientation = (scrollOrientation() == Qt::Vertical);
784 const bool decreaseLayouterSize = ( verticalScrollOrientation && maximumScrollOffset() > size().height()) ||
785 (!verticalScrollOrientation && maximumScrollOffset() > size().width());
786 if (decreaseLayouterSize) {
787 const int scrollBarExtent = style()->pixelMetric(QStyle::PM_ScrollBarExtent);
788 QSizeF layouterSize = m_layouter->size();
789 if (verticalScrollOrientation) {
790 layouterSize.rwidth() -= scrollBarExtent;
791 } else {
792 layouterSize.rheight() -= scrollBarExtent;
793 }
794 m_layouter->setSize(layouterSize);
795 }
796 }
797
798 if (!hasMultipleRanges) {
799 doLayout(Animation, index, count);
800 }
801 }
802
803 if (m_controller) {
804 m_controller->selectionManager()->itemsInserted(itemRanges);
805 }
806
807 if (hasMultipleRanges) {
808 endTransaction();
809 }
810 }
811
812 void KItemListView::slotItemsRemoved(const KItemRangeList& itemRanges)
813 {
814 updateVisibleRolesSizes();
815
816 const bool hasMultipleRanges = (itemRanges.count() > 1);
817 if (hasMultipleRanges) {
818 beginTransaction();
819 }
820
821 for (int i = itemRanges.count() - 1; i >= 0; --i) {
822 const KItemRange& range = itemRanges.at(i);
823 const int index = range.index;
824 const int count = range.count;
825 if (index < 0 || count <= 0) {
826 kWarning() << "Invalid item range (index:" << index << ", count:" << count << ")";
827 continue;
828 }
829
830 m_sizeHintResolver->itemsRemoved(index, count);
831
832 const int firstRemovedIndex = index;
833 const int lastRemovedIndex = index + count - 1;
834 const int lastIndex = m_model->count() + count - 1;
835
836 // Remove all KItemListWidget instances that got deleted
837 for (int i = firstRemovedIndex; i <= lastRemovedIndex; ++i) {
838 KItemListWidget* widget = m_visibleItems.value(i);
839 if (!widget) {
840 continue;
841 }
842
843 m_animation->stop(widget);
844 // Stopping the animation might lead to recycling the widget if
845 // it is invisible (see slotAnimationFinished()).
846 // Check again whether it is still visible:
847 if (!m_visibleItems.contains(i)) {
848 continue;
849 }
850
851 if (m_model->count() == 0) {
852 // For performance reasons no animation is done when all items have
853 // been removed.
854 recycleWidget(widget);
855 } else {
856 // Animate the removing of the items. Special case: When removing an item there
857 // is no valid model index available anymore. For the
858 // remove-animation the item gets removed from m_visibleItems but the widget
859 // will stay alive until the animation has been finished and will
860 // be recycled (deleted) in KItemListView::slotAnimationFinished().
861 m_visibleItems.remove(i);
862 widget->setIndex(-1);
863 m_animation->start(widget, KItemListViewAnimation::DeleteAnimation);
864 }
865 }
866
867 // Update the indexes of all KItemListWidget instances that are located
868 // after the deleted items
869 for (int i = lastRemovedIndex + 1; i <= lastIndex; ++i) {
870 KItemListWidget* widget = m_visibleItems.value(i);
871 if (widget) {
872 const int newIndex = i - count;
873 setWidgetIndex(widget, newIndex);
874 }
875 }
876
877 m_layouter->markAsDirty();
878 if (!hasMultipleRanges) {
879 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
880 // assumes an updated geometry. If items are removed during an active transaction,
881 // the transaction will be temporary deactivated so that doLayout() triggers a
882 // geometry update if necessary.
883 const int activeTransactions = m_activeTransactions;
884 m_activeTransactions = 0;
885 doLayout(Animation, index, -count);
886 m_activeTransactions = activeTransactions;
887 }
888 }
889
890 if (m_controller) {
891 m_controller->selectionManager()->itemsRemoved(itemRanges);
892 }
893
894 if (hasMultipleRanges) {
895 endTransaction();
896 }
897 }
898
899 void KItemListView::slotItemsMoved(const KItemRange& itemRange, const QList<int>& movedToIndexes)
900 {
901 m_sizeHintResolver->itemsMoved(itemRange.index, itemRange.count);
902 m_layouter->markAsDirty();
903
904 if (m_controller) {
905 m_controller->selectionManager()->itemsMoved(itemRange, movedToIndexes);
906 }
907
908 const int firstVisibleMovedIndex = qMax(firstVisibleIndex(), itemRange.index);
909 const int lastVisibleMovedIndex = qMin(lastVisibleIndex(), itemRange.index + itemRange.count - 1);
910
911 for (int index = firstVisibleMovedIndex; index <= lastVisibleMovedIndex; ++index) {
912 KItemListWidget* widget = m_visibleItems.value(index);
913 if (widget) {
914 updateWidgetProperties(widget, index);
915 if (m_grouped) {
916 updateGroupHeaderForWidget(widget);
917 }
918 initializeItemListWidget(widget);
919 }
920 }
921
922 doLayout(NoAnimation);
923 }
924
925 void KItemListView::slotItemsChanged(const KItemRangeList& itemRanges,
926 const QSet<QByteArray>& roles)
927 {
928 const bool updateSizeHints = itemSizeHintUpdateRequired(roles);
929 if (updateSizeHints) {
930 updateVisibleRolesSizes(itemRanges);
931 }
932
933 foreach (const KItemRange& itemRange, itemRanges) {
934 const int index = itemRange.index;
935 const int count = itemRange.count;
936
937 if (updateSizeHints) {
938 m_sizeHintResolver->itemsChanged(index, count, roles);
939 m_layouter->markAsDirty();
940
941 if (!m_layoutTimer->isActive()) {
942 m_layoutTimer->start();
943 }
944 }
945
946 // Apply the changed roles to the visible item-widgets
947 const int lastIndex = index + count - 1;
948 for (int i = index; i <= lastIndex; ++i) {
949 KItemListWidget* widget = m_visibleItems.value(i);
950 if (widget) {
951 widget->setData(m_model->data(i), roles);
952 }
953 }
954
955 if (m_grouped && roles.contains(m_model->sortRole())) {
956 // The sort-role has been changed which might result
957 // in modified group headers
958 updateVisibleGroupHeaders();
959 doLayout(NoAnimation);
960 }
961 }
962 }
963
964 void KItemListView::slotGroupedSortingChanged(bool current)
965 {
966 m_grouped = current;
967 m_layouter->markAsDirty();
968
969 if (m_grouped) {
970 // Apply the height of the header to the layouter
971 const qreal groupHeaderHeight = m_styleOption.fontMetrics.height() +
972 m_styleOption.margin * 2;
973 m_layouter->setGroupHeaderHeight(groupHeaderHeight);
974
975 updateVisibleGroupHeaders();
976 } else {
977 // Clear all visible headers
978 QMutableHashIterator<KItemListWidget*, KItemListGroupHeader*> it (m_visibleGroups);
979 while (it.hasNext()) {
980 it.next();
981 recycleGroupHeaderForWidget(it.key());
982 }
983 Q_ASSERT(m_visibleGroups.isEmpty());
984 }
985
986 doLayout(Animation);
987 }
988
989 void KItemListView::slotSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous)
990 {
991 Q_UNUSED(current);
992 Q_UNUSED(previous);
993 if (m_grouped) {
994 updateVisibleGroupHeaders();
995 doLayout(Animation);
996 }
997 }
998
999 void KItemListView::slotSortRoleChanged(const QByteArray& current, const QByteArray& previous)
1000 {
1001 Q_UNUSED(current);
1002 Q_UNUSED(previous);
1003 if (m_grouped) {
1004 updateVisibleGroupHeaders();
1005 doLayout(Animation);
1006 }
1007 }
1008
1009 void KItemListView::slotCurrentChanged(int current, int previous)
1010 {
1011 Q_UNUSED(previous);
1012
1013 KItemListWidget* previousWidget = m_visibleItems.value(previous, 0);
1014 if (previousWidget) {
1015 Q_ASSERT(previousWidget->isCurrent());
1016 previousWidget->setCurrent(false);
1017 }
1018
1019 KItemListWidget* currentWidget = m_visibleItems.value(current, 0);
1020 if (currentWidget) {
1021 Q_ASSERT(!currentWidget->isCurrent());
1022 currentWidget->setCurrent(true);
1023 }
1024 }
1025
1026 void KItemListView::slotSelectionChanged(const QSet<int>& current, const QSet<int>& previous)
1027 {
1028 Q_UNUSED(previous);
1029
1030 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
1031 while (it.hasNext()) {
1032 it.next();
1033 const int index = it.key();
1034 KItemListWidget* widget = it.value();
1035 widget->setSelected(current.contains(index));
1036 }
1037 }
1038
1039 void KItemListView::slotAnimationFinished(QGraphicsWidget* widget,
1040 KItemListViewAnimation::AnimationType type)
1041 {
1042 KItemListWidget* itemListWidget = qobject_cast<KItemListWidget*>(widget);
1043 Q_ASSERT(itemListWidget);
1044
1045 switch (type) {
1046 case KItemListViewAnimation::DeleteAnimation: {
1047 // As we recycle the widget in this case it is important to assure that no
1048 // other animation has been started. This is a convention in KItemListView and
1049 // not a requirement defined by KItemListViewAnimation.
1050 Q_ASSERT(!m_animation->isStarted(itemListWidget));
1051
1052 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1053 // by m_visibleWidgets and must be deleted manually after the animation has
1054 // been finished.
1055 recycleGroupHeaderForWidget(itemListWidget);
1056 m_widgetCreator->recycle(itemListWidget);
1057 break;
1058 }
1059
1060 case KItemListViewAnimation::CreateAnimation:
1061 case KItemListViewAnimation::MovingAnimation:
1062 case KItemListViewAnimation::ResizeAnimation: {
1063 const int index = itemListWidget->index();
1064 const bool invisible = (index < m_layouter->firstVisibleIndex()) ||
1065 (index > m_layouter->lastVisibleIndex());
1066 if (invisible && !m_animation->isStarted(itemListWidget)) {
1067 recycleWidget(itemListWidget);
1068 }
1069 break;
1070 }
1071
1072 default: break;
1073 }
1074 }
1075
1076 void KItemListView::slotLayoutTimerFinished()
1077 {
1078 m_layouter->setSize(geometry().size());
1079 doLayout(Animation);
1080 }
1081
1082 void KItemListView::slotRubberBandPosChanged()
1083 {
1084 update();
1085 }
1086
1087 void KItemListView::slotRubberBandActivationChanged(bool active)
1088 {
1089 if (active) {
1090 connect(m_rubberBand, SIGNAL(startPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1091 connect(m_rubberBand, SIGNAL(endPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1092 m_skipAutoScrollForRubberBand = true;
1093 } else {
1094 disconnect(m_rubberBand, SIGNAL(startPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1095 disconnect(m_rubberBand, SIGNAL(endPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1096 m_skipAutoScrollForRubberBand = false;
1097 }
1098
1099 update();
1100 }
1101
1102 void KItemListView::slotVisibleRoleWidthChanged(const QByteArray& role,
1103 qreal currentWidth,
1104 qreal previousWidth)
1105 {
1106 Q_UNUSED(previousWidth);
1107
1108 m_useHeaderWidths = true;
1109
1110 if (m_visibleRolesSizes.contains(role)) {
1111 QSizeF roleSize = m_visibleRolesSizes.value(role);
1112 roleSize.setWidth(currentWidth);
1113 m_visibleRolesSizes.insert(role, roleSize);
1114 m_stretchedVisibleRolesSizes.insert(role, roleSize);
1115
1116 // Apply the new size to the layouter
1117 QSizeF dynamicItemSize = m_itemSize;
1118 if (dynamicItemSize.width() < 0) {
1119 const qreal requiredWidth = visibleRolesSizesWidthSum();
1120 dynamicItemSize.setWidth(qMax(size().width(), requiredWidth));
1121 }
1122 if (dynamicItemSize.height() < 0) {
1123 const qreal requiredHeight = visibleRolesSizesHeightSum();
1124 dynamicItemSize.setHeight(qMax(size().height(), requiredHeight));
1125 }
1126
1127 m_layouter->setItemSize(dynamicItemSize);
1128
1129 // Update the role sizes for all visible widgets
1130 foreach (KItemListWidget* widget, visibleItemListWidgets()) {
1131 widget->setVisibleRolesSizes(m_stretchedVisibleRolesSizes);
1132 }
1133
1134 doLayout(Animation);
1135 }
1136 }
1137
1138 void KItemListView::triggerAutoScrolling()
1139 {
1140 if (!m_autoScrollTimer) {
1141 return;
1142 }
1143
1144 int pos = 0;
1145 int visibleSize = 0;
1146 if (scrollOrientation() == Qt::Vertical) {
1147 pos = m_mousePos.y();
1148 visibleSize = size().height();
1149 } else {
1150 pos = m_mousePos.x();
1151 visibleSize = size().width();
1152 }
1153
1154 if (m_autoScrollTimer->interval() == InitialAutoScrollDelay) {
1155 m_autoScrollIncrement = 0;
1156 }
1157
1158 m_autoScrollIncrement = calculateAutoScrollingIncrement(pos, visibleSize, m_autoScrollIncrement);
1159 if (m_autoScrollIncrement == 0) {
1160 // The mouse position is not above an autoscroll margin (the autoscroll timer
1161 // will be restarted in mouseMoveEvent())
1162 m_autoScrollTimer->stop();
1163 return;
1164 }
1165
1166 if (m_rubberBand->isActive() && m_skipAutoScrollForRubberBand) {
1167 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1168 // if the direction of the rubberband is similar to the autoscroll direction. This
1169 // prevents that starting to create a rubberband within the autoscroll margins starts
1170 // an autoscrolling.
1171
1172 const qreal minDiff = 4; // Ignore any autoscrolling if the rubberband is very small
1173 const qreal diff = (scrollOrientation() == Qt::Vertical)
1174 ? m_rubberBand->endPosition().y() - m_rubberBand->startPosition().y()
1175 : m_rubberBand->endPosition().x() - m_rubberBand->startPosition().x();
1176 if (qAbs(diff) < minDiff || (m_autoScrollIncrement < 0 && diff > 0) || (m_autoScrollIncrement > 0 && diff < 0)) {
1177 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1178 // been moved up although the autoscroll direction might be down)
1179 m_autoScrollTimer->stop();
1180 return;
1181 }
1182 }
1183
1184 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1185 // the autoscrolling may not get skipped anymore until a new rubberband is created
1186 m_skipAutoScrollForRubberBand = false;
1187
1188 const qreal maxVisibleOffset = qMax(qreal(0), maximumScrollOffset() - visibleSize);
1189 const qreal newScrollOffset = qMin(scrollOffset() + m_autoScrollIncrement, maxVisibleOffset);
1190 setScrollOffset(newScrollOffset);
1191
1192 // Trigger the autoscroll timer which will periodically call
1193 // triggerAutoScrolling()
1194 m_autoScrollTimer->start(RepeatingAutoScrollDelay);
1195 }
1196
1197 void KItemListView::setController(KItemListController* controller)
1198 {
1199 if (m_controller != controller) {
1200 KItemListController* previous = m_controller;
1201 if (previous) {
1202 KItemListSelectionManager* selectionManager = previous->selectionManager();
1203 disconnect(selectionManager, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1204 disconnect(selectionManager, SIGNAL(selectionChanged(QSet<int>,QSet<int>)), this, SLOT(slotSelectionChanged(QSet<int>,QSet<int>)));
1205 }
1206
1207 m_controller = controller;
1208
1209 if (controller) {
1210 KItemListSelectionManager* selectionManager = controller->selectionManager();
1211 connect(selectionManager, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1212 connect(selectionManager, SIGNAL(selectionChanged(QSet<int>,QSet<int>)), this, SLOT(slotSelectionChanged(QSet<int>,QSet<int>)));
1213 }
1214
1215 onControllerChanged(controller, previous);
1216 }
1217 }
1218
1219 void KItemListView::setModel(KItemModelBase* model)
1220 {
1221 if (m_model == model) {
1222 return;
1223 }
1224
1225 KItemModelBase* previous = m_model;
1226
1227 if (m_model) {
1228 disconnect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
1229 this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
1230 disconnect(m_model, SIGNAL(itemsInserted(KItemRangeList)),
1231 this, SLOT(slotItemsInserted(KItemRangeList)));
1232 disconnect(m_model, SIGNAL(itemsRemoved(KItemRangeList)),
1233 this, SLOT(slotItemsRemoved(KItemRangeList)));
1234 disconnect(m_model, SIGNAL(itemsMoved(KItemRange,QList<int>)),
1235 this, SLOT(slotItemsMoved(KItemRange,QList<int>)));
1236 disconnect(m_model, SIGNAL(groupedSortingChanged(bool)),
1237 this, SLOT(slotGroupedSortingChanged(bool)));
1238 disconnect(m_model, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)),
1239 this, SLOT(slotSortOrderChanged(Qt::SortOrder,Qt::SortOrder)));
1240 disconnect(m_model, SIGNAL(sortRoleChanged(QByteArray,QByteArray)),
1241 this, SLOT(slotSortRoleChanged(QByteArray,QByteArray)));
1242 }
1243
1244 m_model = model;
1245 m_layouter->setModel(model);
1246 m_grouped = model->groupedSorting();
1247
1248 if (m_model) {
1249 connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
1250 this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
1251 connect(m_model, SIGNAL(itemsInserted(KItemRangeList)),
1252 this, SLOT(slotItemsInserted(KItemRangeList)));
1253 connect(m_model, SIGNAL(itemsRemoved(KItemRangeList)),
1254 this, SLOT(slotItemsRemoved(KItemRangeList)));
1255 connect(m_model, SIGNAL(itemsMoved(KItemRange,QList<int>)),
1256 this, SLOT(slotItemsMoved(KItemRange,QList<int>)));
1257 connect(m_model, SIGNAL(groupedSortingChanged(bool)),
1258 this, SLOT(slotGroupedSortingChanged(bool)));
1259 connect(m_model, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)),
1260 this, SLOT(slotSortOrderChanged(Qt::SortOrder,Qt::SortOrder)));
1261 connect(m_model, SIGNAL(sortRoleChanged(QByteArray,QByteArray)),
1262 this, SLOT(slotSortRoleChanged(QByteArray,QByteArray)));
1263 }
1264
1265 onModelChanged(model, previous);
1266 }
1267
1268 KItemListRubberBand* KItemListView::rubberBand() const
1269 {
1270 return m_rubberBand;
1271 }
1272
1273 void KItemListView::doLayout(LayoutAnimationHint hint, int changedIndex, int changedCount)
1274 {
1275 if (m_layoutTimer->isActive()) {
1276 m_layoutTimer->stop();
1277 }
1278
1279 if (!m_model || m_model->count() < 0 || m_activeTransactions > 0) {
1280 return;
1281 }
1282
1283 int firstVisibleIndex = m_layouter->firstVisibleIndex();
1284 if (firstVisibleIndex < 0) {
1285 emitOffsetChanges();
1286 return;
1287 }
1288
1289 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1290 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1291 // is still shown if the maximum offset got decreased.
1292 const qreal visibleOffsetRange = (scrollOrientation() == Qt::Horizontal) ? size().width() : size().height();
1293 const qreal maxOffsetToShowFullRange = maximumScrollOffset() - visibleOffsetRange;
1294 if (scrollOffset() > maxOffsetToShowFullRange) {
1295 m_layouter->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange));
1296 firstVisibleIndex = m_layouter->firstVisibleIndex();
1297 }
1298
1299 const int lastVisibleIndex = m_layouter->lastVisibleIndex();
1300
1301 QList<int> reusableItems = recycleInvisibleItems(firstVisibleIndex, lastVisibleIndex);
1302
1303 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1304 // instances from invisible items are reused. If no reusable items are
1305 // found then new KItemListWidget instances get created.
1306 const bool animate = (hint == Animation);
1307 for (int i = firstVisibleIndex; i <= lastVisibleIndex; ++i) {
1308 bool applyNewPos = true;
1309 bool wasHidden = false;
1310
1311 const QRectF itemBounds = m_layouter->itemRect(i);
1312 const QPointF newPos = itemBounds.topLeft();
1313 KItemListWidget* widget = m_visibleItems.value(i);
1314 if (!widget) {
1315 wasHidden = true;
1316 if (!reusableItems.isEmpty()) {
1317 // Reuse a KItemListWidget instance from an invisible item
1318 const int oldIndex = reusableItems.takeLast();
1319 widget = m_visibleItems.value(oldIndex);
1320 setWidgetIndex(widget, i);
1321
1322 if (m_grouped) {
1323 updateGroupHeaderForWidget(widget);
1324 }
1325 } else {
1326 // No reusable KItemListWidget instance is available, create a new one
1327 widget = createWidget(i);
1328 }
1329 widget->resize(itemBounds.size());
1330
1331 if (animate && changedCount < 0) {
1332 // Items have been deleted, move the created item to the
1333 // imaginary old position. They will get animated to the new position
1334 // later.
1335 const QRectF itemRect = m_layouter->itemRect(i - changedCount);
1336 if (itemRect.isEmpty()) {
1337 const QPointF invisibleOldPos = (scrollOrientation() == Qt::Vertical)
1338 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1339 widget->setPos(invisibleOldPos);
1340 } else {
1341 widget->setPos(itemRect.topLeft());
1342 }
1343 applyNewPos = false;
1344 }
1345 } else if (m_animation->isStarted(widget, KItemListViewAnimation::MovingAnimation)) {
1346 applyNewPos = false;
1347 }
1348
1349 if (animate) {
1350 const bool itemsRemoved = (changedCount < 0);
1351 const bool itemsInserted = (changedCount > 0);
1352 if (itemsRemoved && (i >= changedIndex + changedCount + 1)) {
1353 // The item is located after the removed items. Animate the moving of the position.
1354 applyNewPos = !moveWidget(widget, itemBounds);
1355 } else if (itemsInserted && i >= changedIndex) {
1356 // The item is located after the first inserted item
1357 if (i <= changedIndex + changedCount - 1) {
1358 // The item is an inserted item. Animate the appearing of the item.
1359 // For performance reasons no animation is done when changedCount is equal
1360 // to all available items.
1361 if (changedCount < m_model->count()) {
1362 m_animation->start(widget, KItemListViewAnimation::CreateAnimation);
1363 }
1364 } else if (!m_animation->isStarted(widget, KItemListViewAnimation::CreateAnimation)) {
1365 // The item was already there before, so animate the moving of the position.
1366 // No moving animation is done if the item is animated by a create animation: This
1367 // prevents a "move animation mess" when inserting several ranges in parallel.
1368 applyNewPos = !moveWidget(widget, itemBounds);
1369 }
1370 } else if (!itemsRemoved && !itemsInserted && !wasHidden) {
1371 // The size of the view might have been changed. Animate the moving of the position.
1372 applyNewPos = !moveWidget(widget, itemBounds);
1373 }
1374 }
1375
1376 if (applyNewPos) {
1377 widget->setPos(newPos);
1378 }
1379
1380 Q_ASSERT(widget->index() == i);
1381 widget->setVisible(true);
1382
1383 if (widget->size() != itemBounds.size()) {
1384 // Resize the widget for the item to the changed size.
1385 if (animate) {
1386 // If a dynamic item size is used then no animation is done in the direction
1387 // of the dynamic size.
1388 if (m_itemSize.width() <= 0) {
1389 // The width is dynamic, apply the new width without animation.
1390 widget->resize(itemBounds.width(), widget->size().height());
1391 } else if (m_itemSize.height() <= 0) {
1392 // The height is dynamic, apply the new height without animation.
1393 widget->resize(widget->size().width(), itemBounds.height());
1394 }
1395 m_animation->start(widget, KItemListViewAnimation::ResizeAnimation, itemBounds.size());
1396 } else {
1397 widget->resize(itemBounds.size());
1398 }
1399 }
1400 }
1401
1402 // Delete invisible KItemListWidget instances that have not been reused
1403 foreach (int index, reusableItems) {
1404 recycleWidget(m_visibleItems.value(index));
1405 }
1406
1407 if (m_grouped) {
1408 // Update the layout of all visible group headers
1409 QHashIterator<KItemListWidget*, KItemListGroupHeader*> it(m_visibleGroups);
1410 while (it.hasNext()) {
1411 it.next();
1412 updateGroupHeaderLayout(it.key());
1413 }
1414 }
1415
1416 emitOffsetChanges();
1417 }
1418
1419 QList<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex, int lastVisibleIndex)
1420 {
1421 // Determine all items that are completely invisible and might be
1422 // reused for items that just got (at least partly) visible.
1423 // Items that do e.g. an animated moving of their position are not
1424 // marked as invisible: This assures that a scrolling inside the view
1425 // can be done without breaking an animation.
1426
1427 QList<int> items;
1428
1429 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
1430 while (it.hasNext()) {
1431 it.next();
1432 KItemListWidget* widget = it.value();
1433 const int index = widget->index();
1434 const bool invisible = (index < firstVisibleIndex) || (index > lastVisibleIndex);
1435 if (invisible && !m_animation->isStarted(widget)) {
1436 widget->setVisible(false);
1437 items.append(index);
1438
1439 if (m_grouped) {
1440 recycleGroupHeaderForWidget(widget);
1441 }
1442 }
1443 }
1444
1445 return items;
1446 }
1447
1448 bool KItemListView::moveWidget(KItemListWidget* widget,const QRectF& itemBounds)
1449 {
1450 const QPointF oldPos = widget->pos();
1451 const QPointF newPos = itemBounds.topLeft();
1452 if (oldPos == newPos) {
1453 return false;
1454 }
1455
1456 bool startMovingAnim = m_itemSize.isEmpty();
1457 if (!startMovingAnim) {
1458 // When having a grid the moving-animation should only be started, if it is done within
1459 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1460 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1461 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1462
1463 int zoomDiff = 0;
1464 if (widget->size() != itemBounds.size()) {
1465 // The item-size has been increased or decreased
1466 const bool zoomOut = (widget->size().width() >= itemBounds.size().width()) &&
1467 (widget->size().height() >= itemBounds.size().height());
1468 zoomDiff = zoomOut ? -1 : +1;
1469 }
1470
1471 const qreal xMax = m_itemSize.width();
1472 const qreal yMax = m_itemSize.height();
1473 qreal xDiff = oldPos.x() - newPos.x();
1474 qreal yDiff = oldPos.y() - newPos.y();
1475 if (scrollOrientation() == Qt::Vertical) {
1476 if (zoomDiff != 0) {
1477 // Skip moving animations that changed the row
1478 startMovingAnim = (zoomDiff > 0 && xDiff < xMax) ||
1479 (zoomDiff < 0 && -xDiff < xMax);
1480 } else {
1481 xDiff = qAbs(xDiff);
1482 yDiff = qAbs(yDiff);
1483 startMovingAnim = (xDiff > yDiff && yDiff < yMax);
1484 }
1485 } else {
1486 if (zoomDiff != 0) {
1487 // Skip moving animations that changed the column
1488 startMovingAnim = (zoomDiff > 0 && yDiff < yMax) ||
1489 (zoomDiff < 0 && -yDiff < yMax);
1490 } else {
1491 xDiff = qAbs(xDiff);
1492 yDiff = qAbs(yDiff);
1493 startMovingAnim = (yDiff > xDiff && xDiff < xMax);
1494 }
1495 }
1496 }
1497
1498 if (startMovingAnim) {
1499 m_animation->start(widget, KItemListViewAnimation::MovingAnimation, newPos);
1500 return true;
1501 }
1502
1503 m_animation->stop(widget);
1504 m_animation->start(widget, KItemListViewAnimation::CreateAnimation);
1505 return false;
1506 }
1507
1508 void KItemListView::emitOffsetChanges()
1509 {
1510 const qreal newScrollOffset = m_layouter->scrollOffset();
1511 if (m_oldScrollOffset != newScrollOffset) {
1512 emit scrollOffsetChanged(newScrollOffset, m_oldScrollOffset);
1513 m_oldScrollOffset = newScrollOffset;
1514 }
1515
1516 const qreal newMaximumScrollOffset = m_layouter->maximumScrollOffset();
1517 if (m_oldMaximumScrollOffset != newMaximumScrollOffset) {
1518 emit maximumScrollOffsetChanged(newMaximumScrollOffset, m_oldMaximumScrollOffset);
1519 m_oldMaximumScrollOffset = newMaximumScrollOffset;
1520 }
1521
1522 const qreal newItemOffset = m_layouter->itemOffset();
1523 if (m_oldItemOffset != newItemOffset) {
1524 emit itemOffsetChanged(newItemOffset, m_oldItemOffset);
1525 m_oldItemOffset = newItemOffset;
1526 }
1527
1528 const qreal newMaximumItemOffset = m_layouter->maximumItemOffset();
1529 if (m_oldMaximumItemOffset != newMaximumItemOffset) {
1530 emit maximumItemOffsetChanged(newMaximumItemOffset, m_oldMaximumItemOffset);
1531 m_oldMaximumItemOffset = newMaximumItemOffset;
1532 }
1533 }
1534
1535 KItemListWidget* KItemListView::createWidget(int index)
1536 {
1537 KItemListWidget* widget = m_widgetCreator->create(this);
1538 widget->setFlag(QGraphicsItem::ItemStacksBehindParent);
1539
1540 updateWidgetProperties(widget, index);
1541 m_visibleItems.insert(index, widget);
1542
1543 if (m_grouped) {
1544 updateGroupHeaderForWidget(widget);
1545 }
1546
1547 initializeItemListWidget(widget);
1548 return widget;
1549 }
1550
1551 void KItemListView::recycleWidget(KItemListWidget* widget)
1552 {
1553 if (m_grouped) {
1554 recycleGroupHeaderForWidget(widget);
1555 }
1556
1557 m_visibleItems.remove(widget->index());
1558 m_widgetCreator->recycle(widget);
1559 }
1560
1561 void KItemListView::setWidgetIndex(KItemListWidget* widget, int index)
1562 {
1563 const int oldIndex = widget->index();
1564 m_visibleItems.remove(oldIndex);
1565 updateWidgetProperties(widget, index);
1566 m_visibleItems.insert(index, widget);
1567
1568 initializeItemListWidget(widget);
1569 }
1570
1571 void KItemListView::setLayouterSize(const QSizeF& size, SizeType sizeType)
1572 {
1573 switch (sizeType) {
1574 case LayouterSize: m_layouter->setSize(size); break;
1575 case ItemSize: m_layouter->setItemSize(size); break;
1576 default: break;
1577 }
1578 }
1579
1580 void KItemListView::updateWidgetProperties(KItemListWidget* widget, int index)
1581 {
1582 widget->setVisibleRoles(m_visibleRoles);
1583 widget->setVisibleRolesSizes(m_stretchedVisibleRolesSizes);
1584 widget->setStyleOption(m_styleOption);
1585
1586 const KItemListSelectionManager* selectionManager = m_controller->selectionManager();
1587 widget->setCurrent(index == selectionManager->currentItem());
1588 widget->setSelected(selectionManager->isSelected(index));
1589 widget->setHovered(false);
1590 widget->setAlternatingBackgroundColors(false);
1591 widget->setEnabledSelectionToggle(enabledSelectionToggles());
1592 widget->setIndex(index);
1593 widget->setData(m_model->data(index));
1594 }
1595
1596 void KItemListView::updateGroupHeaderForWidget(KItemListWidget* widget)
1597 {
1598 Q_ASSERT(m_grouped);
1599
1600 const int index = widget->index();
1601 if (!m_layouter->isFirstGroupItem(index)) {
1602 // The widget does not represent the first item of a group
1603 // and hence requires no header
1604 recycleGroupHeaderForWidget(widget);
1605 return;
1606 }
1607
1608 const QList<QPair<int, QVariant> > groups = model()->groups();
1609 if (groups.isEmpty()) {
1610 return;
1611 }
1612
1613 KItemListGroupHeader* header = m_visibleGroups.value(widget);
1614 if (!header) {
1615 header = m_groupHeaderCreator->create(this);
1616 header->setParentItem(widget);
1617 m_visibleGroups.insert(widget, header);
1618 }
1619 Q_ASSERT(header->parentItem() == widget);
1620
1621 // Determine the shown data for the header by doing a binary
1622 // search in the groups-list
1623 int min = 0;
1624 int max = groups.count() - 1;
1625 int mid = 0;
1626 do {
1627 mid = (min + max) / 2;
1628 if (index > groups.at(mid).first) {
1629 min = mid + 1;
1630 } else {
1631 max = mid - 1;
1632 }
1633 } while (groups.at(mid).first != index && min <= max);
1634
1635 header->setData(groups.at(mid).second);
1636 header->setRole(model()->sortRole());
1637 header->setStyleOption(m_styleOption);
1638 header->setScrollOrientation(scrollOrientation());
1639
1640 header->show();
1641 }
1642
1643 void KItemListView::updateGroupHeaderLayout(KItemListWidget* widget)
1644 {
1645 KItemListGroupHeader* header = m_visibleGroups.value(widget);
1646 Q_ASSERT(header);
1647
1648 const int index = widget->index();
1649 const QRectF groupHeaderRect = m_layouter->groupHeaderRect(index);
1650 const QRectF itemRect = m_layouter->itemRect(index);
1651
1652 // The group-header is a child of the itemlist widget. Translate the
1653 // group header position to the relative position.
1654 const QPointF groupHeaderPos(groupHeaderRect.x() - itemRect.x(),
1655 - groupHeaderRect.height());
1656 header->setPos(groupHeaderPos);
1657 header->resize(groupHeaderRect.size());
1658 }
1659
1660 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget* widget)
1661 {
1662 KItemListGroupHeader* header = m_visibleGroups.value(widget);
1663 if (header) {
1664 header->setParentItem(0);
1665 m_groupHeaderCreator->recycle(header);
1666 m_visibleGroups.remove(widget);
1667 }
1668 }
1669
1670 void KItemListView::updateVisibleGroupHeaders()
1671 {
1672 Q_ASSERT(m_grouped);
1673 m_layouter->markAsDirty();
1674
1675 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
1676 while (it.hasNext()) {
1677 it.next();
1678 updateGroupHeaderForWidget(it.value());
1679 }
1680 }
1681
1682 QHash<QByteArray, qreal> KItemListView::headerRolesWidths() const
1683 {
1684 QHash<QByteArray, qreal> rolesWidths;
1685
1686 QHashIterator<QByteArray, QSizeF> it(m_stretchedVisibleRolesSizes);
1687 while (it.hasNext()) {
1688 it.next();
1689 rolesWidths.insert(it.key(), it.value().width());
1690 }
1691
1692 return rolesWidths;
1693 }
1694
1695 void KItemListView::updateVisibleRolesSizes(const KItemRangeList& itemRanges)
1696 {
1697 if (!m_itemSize.isEmpty() || m_useHeaderWidths) {
1698 return;
1699 }
1700
1701 const int itemCount = m_model->count();
1702 int rangesItemCount = 0;
1703 foreach (const KItemRange& range, itemRanges) {
1704 rangesItemCount += range.count;
1705 }
1706
1707 if (itemCount == rangesItemCount) {
1708 m_visibleRolesSizes = visibleRolesSizes(itemRanges);
1709 if (m_header) {
1710 // Assure the the sizes are not smaller than the minimum defined by the header
1711 // TODO: Currently only implemented for a top-aligned header
1712 const qreal minHeaderRoleWidth = m_header->minimumRoleWidth();
1713 QMutableHashIterator<QByteArray, QSizeF> it (m_visibleRolesSizes);
1714 while (it.hasNext()) {
1715 it.next();
1716 const QSizeF& size = it.value();
1717 if (size.width() < minHeaderRoleWidth) {
1718 const QSizeF newSize(minHeaderRoleWidth, size.height());
1719 m_visibleRolesSizes.insert(it.key(), newSize);
1720 }
1721 }
1722 }
1723 } else {
1724 // Only a sub range of the roles need to be determined.
1725 // The chances are good that the sizes of the sub ranges
1726 // already fit into the available sizes and hence no
1727 // expensive update might be required.
1728 bool updateRequired = false;
1729
1730 const QHash<QByteArray, QSizeF> updatedSizes = visibleRolesSizes(itemRanges);
1731 QHashIterator<QByteArray, QSizeF> it(updatedSizes);
1732 while (it.hasNext()) {
1733 it.next();
1734 const QByteArray& role = it.key();
1735 const QSizeF& updatedSize = it.value();
1736 const QSizeF currentSize = m_visibleRolesSizes.value(role);
1737 if (updatedSize.width() > currentSize.width() || updatedSize.height() > currentSize.height()) {
1738 m_visibleRolesSizes.insert(role, updatedSize);
1739 updateRequired = true;
1740 }
1741 }
1742
1743 if (!updateRequired) {
1744 // All the updated sizes are smaller than the current sizes and no change
1745 // of the stretched roles-widths is required
1746 return;
1747 }
1748 }
1749
1750 updateStretchedVisibleRolesSizes();
1751 }
1752
1753 void KItemListView::updateVisibleRolesSizes()
1754 {
1755 if (!m_model) {
1756 return;
1757 }
1758
1759 const int itemCount = m_model->count();
1760 if (itemCount > 0) {
1761 updateVisibleRolesSizes(KItemRangeList() << KItemRange(0, itemCount));
1762 }
1763 }
1764
1765 void KItemListView::updateStretchedVisibleRolesSizes()
1766 {
1767 if (!m_itemSize.isEmpty() || m_useHeaderWidths || m_visibleRoles.isEmpty()) {
1768 return;
1769 }
1770
1771 // Calculate the maximum size of an item by considering the
1772 // visible role sizes and apply them to the layouter. If the
1773 // size does not use the available view-size it the size of the
1774 // first role will get stretched.
1775 m_stretchedVisibleRolesSizes = m_visibleRolesSizes;
1776 const QByteArray role = m_visibleRoles.first();
1777 QSizeF firstRoleSize = m_stretchedVisibleRolesSizes.value(role);
1778
1779 QSizeF dynamicItemSize = m_itemSize;
1780
1781 if (dynamicItemSize.width() <= 0) {
1782 const qreal requiredWidth = visibleRolesSizesWidthSum();
1783 const qreal availableWidth = size().width();
1784 if (requiredWidth < availableWidth) {
1785 // Stretch the first role to use the whole width for the item
1786 firstRoleSize.rwidth() += availableWidth - requiredWidth;
1787 m_stretchedVisibleRolesSizes.insert(role, firstRoleSize);
1788 }
1789 dynamicItemSize.setWidth(qMax(requiredWidth, availableWidth));
1790 }
1791
1792 if (dynamicItemSize.height() <= 0) {
1793 const qreal requiredHeight = visibleRolesSizesHeightSum();
1794 const qreal availableHeight = size().height();
1795 if (requiredHeight < availableHeight) {
1796 // Stretch the first role to use the whole height for the item
1797 firstRoleSize.rheight() += availableHeight - requiredHeight;
1798 m_stretchedVisibleRolesSizes.insert(role, firstRoleSize);
1799 }
1800 dynamicItemSize.setHeight(qMax(requiredHeight, availableHeight));
1801 }
1802
1803 m_layouter->setItemSize(dynamicItemSize);
1804
1805 if (m_header) {
1806 m_header->setVisibleRolesWidths(headerRolesWidths());
1807 m_header->resize(dynamicItemSize.width(), m_header->size().height());
1808 }
1809
1810 // Update the role sizes for all visible widgets
1811 foreach (KItemListWidget* widget, visibleItemListWidgets()) {
1812 widget->setVisibleRolesSizes(m_stretchedVisibleRolesSizes);
1813 }
1814 }
1815
1816 qreal KItemListView::visibleRolesSizesWidthSum() const
1817 {
1818 qreal widthSum = 0;
1819 QHashIterator<QByteArray, QSizeF> it(m_visibleRolesSizes);
1820 while (it.hasNext()) {
1821 it.next();
1822 widthSum += it.value().width();
1823 }
1824 return widthSum;
1825 }
1826
1827 qreal KItemListView::visibleRolesSizesHeightSum() const
1828 {
1829 qreal heightSum = 0;
1830 QHashIterator<QByteArray, QSizeF> it(m_visibleRolesSizes);
1831 while (it.hasNext()) {
1832 it.next();
1833 heightSum += it.value().height();
1834 }
1835 return heightSum;
1836 }
1837
1838 QRectF KItemListView::headerBoundaries() const
1839 {
1840 return m_header ? m_header->geometry() : QRectF();
1841 }
1842
1843 int KItemListView::calculateAutoScrollingIncrement(int pos, int range, int oldInc)
1844 {
1845 int inc = 0;
1846
1847 const int minSpeed = 4;
1848 const int maxSpeed = 128;
1849 const int speedLimiter = 96;
1850 const int autoScrollBorder = 64;
1851
1852 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
1853 // This assures that the autoscrolling speed grows gradually.
1854 const int incLimiter = 1;
1855
1856 if (pos < autoScrollBorder) {
1857 inc = -minSpeed + qAbs(pos - autoScrollBorder) * (pos - autoScrollBorder) / speedLimiter;
1858 inc = qMax(inc, -maxSpeed);
1859 inc = qMax(inc, oldInc - incLimiter);
1860 } else if (pos > range - autoScrollBorder) {
1861 inc = minSpeed + qAbs(pos - range + autoScrollBorder) * (pos - range + autoScrollBorder) / speedLimiter;
1862 inc = qMin(inc, maxSpeed);
1863 inc = qMin(inc, oldInc + incLimiter);
1864 }
1865
1866 return inc;
1867 }
1868
1869
1870
1871 KItemListCreatorBase::~KItemListCreatorBase()
1872 {
1873 qDeleteAll(m_recycleableWidgets);
1874 qDeleteAll(m_createdWidgets);
1875 }
1876
1877 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget* widget)
1878 {
1879 m_createdWidgets.insert(widget);
1880 }
1881
1882 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget* widget)
1883 {
1884 Q_ASSERT(m_createdWidgets.contains(widget));
1885 m_createdWidgets.remove(widget);
1886
1887 if (m_recycleableWidgets.count() < 100) {
1888 m_recycleableWidgets.append(widget);
1889 widget->setVisible(false);
1890 } else {
1891 delete widget;
1892 }
1893 }
1894
1895 QGraphicsWidget* KItemListCreatorBase::popRecycleableWidget()
1896 {
1897 if (m_recycleableWidgets.isEmpty()) {
1898 return 0;
1899 }
1900
1901 QGraphicsWidget* widget = m_recycleableWidgets.takeLast();
1902 m_createdWidgets.insert(widget);
1903 return widget;
1904 }
1905
1906 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
1907 {
1908 }
1909
1910 void KItemListWidgetCreatorBase::recycle(KItemListWidget* widget)
1911 {
1912 widget->setParentItem(0);
1913 widget->setOpacity(1.0);
1914 pushRecycleableWidget(widget);
1915 }
1916
1917 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
1918 {
1919 }
1920
1921 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader* header)
1922 {
1923 header->setOpacity(1.0);
1924 pushRecycleableWidget(header);
1925 }
1926
1927 #include "kitemlistview.moc"