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