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