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