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