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