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