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