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