]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kitemlistview.cpp
Don't select items if the selection toggle has been disabled
[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 if (m_model->count() > 0) {
359 prepareLayoutForIncreasedItemCount(rect.size(), LayouterSize);
360 } else {
361 m_layouter->setSize(rect.size());
362 }
363
364 if (!m_layoutTimer->isActive()) {
365 m_layoutTimer->start();
366 }
367
368 // Changing the geometry does not require to do an expensive
369 // update of the visible-roles sizes, only the stretched sizes
370 // need to be adjusted to the new size.
371 updateStretchedVisibleRolesSizes();
372 }
373
374 int KItemListView::itemAt(const QPointF& pos) const
375 {
376 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
377 while (it.hasNext()) {
378 it.next();
379
380 const KItemListWidget* widget = it.value();
381 const QPointF mappedPos = widget->mapFromItem(this, pos);
382 if (widget->contains(mappedPos)) {
383 return it.key();
384 }
385 }
386
387 return -1;
388 }
389
390 bool KItemListView::isAboveSelectionToggle(int index, const QPointF& pos) const
391 {
392 if (!m_enabledSelectionToggles) {
393 return false;
394 }
395
396 const KItemListWidget* widget = m_visibleItems.value(index);
397 if (widget) {
398 const QRectF selectionToggleRect = widget->selectionToggleRect();
399 if (!selectionToggleRect.isEmpty()) {
400 const QPointF mappedPos = widget->mapFromItem(this, pos);
401 return selectionToggleRect.contains(mappedPos);
402 }
403 }
404 return false;
405 }
406
407 bool KItemListView::isAboveExpansionToggle(int index, const QPointF& pos) const
408 {
409 const KItemListWidget* widget = m_visibleItems.value(index);
410 if (widget) {
411 const QRectF expansionToggleRect = widget->expansionToggleRect();
412 if (!expansionToggleRect.isEmpty()) {
413 const QPointF mappedPos = widget->mapFromItem(this, pos);
414 return expansionToggleRect.contains(mappedPos);
415 }
416 }
417 return false;
418 }
419
420 int KItemListView::firstVisibleIndex() const
421 {
422 return m_layouter->firstVisibleIndex();
423 }
424
425 int KItemListView::lastVisibleIndex() const
426 {
427 return m_layouter->lastVisibleIndex();
428 }
429
430 QSizeF KItemListView::itemSizeHint(int index) const
431 {
432 Q_UNUSED(index);
433 return itemSize();
434 }
435
436 QHash<QByteArray, QSizeF> KItemListView::visibleRolesSizes(const KItemRangeList& itemRanges) const
437 {
438 Q_UNUSED(itemRanges);
439 return QHash<QByteArray, QSizeF>();
440 }
441
442 bool KItemListView::supportsItemExpanding() const
443 {
444 return false;
445 }
446
447 QRectF KItemListView::itemRect(int index) const
448 {
449 return m_layouter->itemRect(index);
450 }
451
452 QRectF KItemListView::itemContextRect(int index) const
453 {
454 QRectF contextRect;
455
456 const KItemListWidget* widget = m_visibleItems.value(index);
457 if (widget) {
458 contextRect = widget->iconRect() | widget->textRect();
459 contextRect.translate(itemRect(index).topLeft());
460 }
461
462 return contextRect;
463 }
464
465 void KItemListView::scrollToItem(int index)
466 {
467 QRectF viewGeometry = geometry();
468 if (m_header) {
469 const qreal headerHeight = m_header->size().height();
470 viewGeometry.adjust(0, headerHeight, 0, 0);
471 }
472 const QRectF currentRect = itemRect(index);
473
474 if (!viewGeometry.contains(currentRect)) {
475 qreal newOffset = scrollOffset();
476 if (currentRect.top() < viewGeometry.top()) {
477 Q_ASSERT(scrollOrientation() == Qt::Vertical);
478 newOffset += currentRect.top() - viewGeometry.top();
479 } else if ((currentRect.bottom() > viewGeometry.bottom())) {
480 Q_ASSERT(scrollOrientation() == Qt::Vertical);
481 newOffset += currentRect.bottom() - viewGeometry.bottom();
482 } else if (currentRect.left() < viewGeometry.left()) {
483 if (scrollOrientation() == Qt::Horizontal) {
484 newOffset += currentRect.left() - viewGeometry.left();
485 }
486 } else if ((currentRect.right() > viewGeometry.right())) {
487 if (scrollOrientation() == Qt::Horizontal) {
488 newOffset += currentRect.right() - viewGeometry.right();
489 }
490 }
491
492 if (newOffset != scrollOffset()) {
493 emit scrollTo(newOffset);
494 }
495 }
496 }
497
498 void KItemListView::beginTransaction()
499 {
500 ++m_activeTransactions;
501 if (m_activeTransactions == 1) {
502 onTransactionBegin();
503 }
504 }
505
506 void KItemListView::endTransaction()
507 {
508 --m_activeTransactions;
509 if (m_activeTransactions < 0) {
510 m_activeTransactions = 0;
511 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
512 }
513
514 if (m_activeTransactions == 0) {
515 onTransactionEnd();
516 doLayout(Animation);
517 }
518 }
519
520 bool KItemListView::isTransactionActive() const
521 {
522 return m_activeTransactions > 0;
523 }
524
525
526 void KItemListView::setHeaderShown(bool show)
527 {
528
529 if (show && !m_header) {
530 m_header = new KItemListHeader(this);
531 m_header->setPos(0, 0);
532 m_header->setModel(m_model);
533 m_header->setVisibleRoles(m_visibleRoles);
534 m_header->setVisibleRolesWidths(headerRolesWidths());
535 m_header->setZValue(1);
536
537 connect(m_header, SIGNAL(visibleRoleWidthChanged(QByteArray,qreal,qreal)),
538 this, SLOT(slotVisibleRoleWidthChanged(QByteArray,qreal,qreal)));
539 connect(m_header, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)),
540 this, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)));
541 connect(m_header, SIGNAL(sortRoleChanged(QByteArray,QByteArray)),
542 this, SIGNAL(sortRoleChanged(QByteArray,QByteArray)));
543
544 m_useHeaderWidths = false;
545
546 m_layouter->setHeaderHeight(m_header->size().height());
547 } else if (!show && m_header) {
548 delete m_header;
549 m_header = 0;
550 m_useHeaderWidths = false;
551 m_layouter->setHeaderHeight(0);
552 }
553 }
554
555 bool KItemListView::isHeaderShown() const
556 {
557 return m_header != 0;
558 }
559
560 QPixmap KItemListView::createDragPixmap(const QSet<int>& indexes) const
561 {
562 Q_UNUSED(indexes);
563 return QPixmap();
564 }
565
566 void KItemListView::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
567 {
568 QGraphicsWidget::paint(painter, option, widget);
569
570 if (m_rubberBand->isActive()) {
571 QRectF rubberBandRect = QRectF(m_rubberBand->startPosition(),
572 m_rubberBand->endPosition()).normalized();
573
574 const QPointF topLeft = rubberBandRect.topLeft();
575 if (scrollOrientation() == Qt::Vertical) {
576 rubberBandRect.moveTo(topLeft.x(), topLeft.y() - scrollOffset());
577 } else {
578 rubberBandRect.moveTo(topLeft.x() - scrollOffset(), topLeft.y());
579 }
580
581 QStyleOptionRubberBand opt;
582 opt.initFrom(widget);
583 opt.shape = QRubberBand::Rectangle;
584 opt.opaque = false;
585 opt.rect = rubberBandRect.toRect();
586 style()->drawControl(QStyle::CE_RubberBand, &opt, painter);
587 }
588 }
589
590 void KItemListView::initializeItemListWidget(KItemListWidget* item)
591 {
592 Q_UNUSED(item);
593 }
594
595 bool KItemListView::itemSizeHintUpdateRequired(const QSet<QByteArray>& changedRoles) const
596 {
597 Q_UNUSED(changedRoles);
598 return true;
599 }
600
601 void KItemListView::onControllerChanged(KItemListController* current, KItemListController* previous)
602 {
603 Q_UNUSED(current);
604 Q_UNUSED(previous);
605 }
606
607 void KItemListView::onModelChanged(KItemModelBase* current, KItemModelBase* previous)
608 {
609 Q_UNUSED(current);
610 Q_UNUSED(previous);
611 }
612
613 void KItemListView::onScrollOrientationChanged(Qt::Orientation current, Qt::Orientation previous)
614 {
615 Q_UNUSED(current);
616 Q_UNUSED(previous);
617 }
618
619 void KItemListView::onItemSizeChanged(const QSizeF& current, const QSizeF& previous)
620 {
621 Q_UNUSED(current);
622 Q_UNUSED(previous);
623 }
624
625 void KItemListView::onScrollOffsetChanged(qreal current, qreal previous)
626 {
627 Q_UNUSED(current);
628 Q_UNUSED(previous);
629 }
630
631 void KItemListView::onVisibleRolesChanged(const QList<QByteArray>& current, const QList<QByteArray>& previous)
632 {
633 Q_UNUSED(current);
634 Q_UNUSED(previous);
635 }
636
637 void KItemListView::onStyleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous)
638 {
639 Q_UNUSED(current);
640 Q_UNUSED(previous);
641 }
642
643 void KItemListView::onTransactionBegin()
644 {
645 }
646
647 void KItemListView::onTransactionEnd()
648 {
649 }
650
651 bool KItemListView::event(QEvent* event)
652 {
653 // Forward all events to the controller and handle them there
654 if (m_controller && m_controller->processEvent(event, transform())) {
655 event->accept();
656 return true;
657 }
658 return QGraphicsWidget::event(event);
659 }
660
661 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent* event)
662 {
663 m_mousePos = transform().map(event->pos());
664 event->accept();
665 }
666
667 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
668 {
669 QGraphicsWidget::mouseMoveEvent(event);
670
671 m_mousePos = transform().map(event->pos());
672 if (m_autoScrollTimer && !m_autoScrollTimer->isActive()) {
673 m_autoScrollTimer->start(InitialAutoScrollDelay);
674 }
675 }
676
677 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent* event)
678 {
679 event->setAccepted(true);
680 setAutoScroll(true);
681 }
682
683 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent *event)
684 {
685 QGraphicsWidget::dragMoveEvent(event);
686
687 m_mousePos = transform().map(event->pos());
688 if (m_autoScrollTimer && !m_autoScrollTimer->isActive()) {
689 m_autoScrollTimer->start(InitialAutoScrollDelay);
690 }
691 }
692
693 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
694 {
695 QGraphicsWidget::dragLeaveEvent(event);
696 setAutoScroll(false);
697 }
698
699 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent* event)
700 {
701 QGraphicsWidget::dropEvent(event);
702 setAutoScroll(false);
703 }
704
705 QList<KItemListWidget*> KItemListView::visibleItemListWidgets() const
706 {
707 return m_visibleItems.values();
708 }
709
710 void KItemListView::resizeEvent(QGraphicsSceneResizeEvent* event)
711 {
712 QGraphicsWidget::resizeEvent(event);
713 if (m_itemSize.isEmpty() && m_useHeaderWidths) {
714 QSizeF dynamicItemSize = m_layouter->itemSize();
715 const QSizeF newSize = event->newSize();
716
717 if (m_itemSize.width() < 0) {
718 const qreal requiredWidth = visibleRolesSizesWidthSum();
719 if (newSize.width() > requiredWidth) {
720 dynamicItemSize.setWidth(newSize.width());
721 }
722 const qreal headerWidth = qMax(newSize.width(), requiredWidth);
723 m_header->resize(headerWidth, m_header->size().height());
724 }
725
726 if (m_itemSize.height() < 0) {
727 const qreal requiredHeight = visibleRolesSizesHeightSum();
728 if (newSize.height() > requiredHeight) {
729 dynamicItemSize.setHeight(newSize.height());
730 }
731 // TODO: KItemListHeader is not prepared for vertical alignment
732 }
733
734 m_layouter->setItemSize(dynamicItemSize);
735 }
736 }
737
738 void KItemListView::slotItemsInserted(const KItemRangeList& itemRanges)
739 {
740 updateVisibleRolesSizes(itemRanges);
741
742 const bool hasMultipleRanges = (itemRanges.count() > 1);
743 if (hasMultipleRanges) {
744 beginTransaction();
745 }
746
747 int previouslyInsertedCount = 0;
748 foreach (const KItemRange& range, itemRanges) {
749 // range.index is related to the model before anything has been inserted.
750 // As in each loop the current item-range gets inserted the index must
751 // be increased by the already previously inserted items.
752 const int index = range.index + previouslyInsertedCount;
753 const int count = range.count;
754 if (index < 0 || count <= 0) {
755 kWarning() << "Invalid item range (index:" << index << ", count:" << count << ")";
756 continue;
757 }
758 previouslyInsertedCount += count;
759
760 m_sizeHintResolver->itemsInserted(index, count);
761
762 // Determine which visible items must be moved
763 QList<int> itemsToMove;
764 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
765 while (it.hasNext()) {
766 it.next();
767 const int visibleItemIndex = it.key();
768 if (visibleItemIndex >= index) {
769 itemsToMove.append(visibleItemIndex);
770 }
771 }
772
773 // Update the indexes of all KItemListWidget instances that are located
774 // after the inserted items. It is important to adjust the indexes in the order
775 // from the highest index to the lowest index to prevent overlaps when setting the new index.
776 qSort(itemsToMove);
777 for (int i = itemsToMove.count() - 1; i >= 0; --i) {
778 KItemListWidget* widget = m_visibleItems.value(itemsToMove[i]);
779 Q_ASSERT(widget);
780 setWidgetIndex(widget, widget->index() + count);
781 }
782
783 m_layouter->markAsDirty();
784 if (m_model->count() == count && maximumScrollOffset() > size().height()) {
785 const int scrollBarExtent = style()->pixelMetric(QStyle::PM_ScrollBarExtent);
786 QSizeF layouterSize = m_layouter->size();
787 if (scrollOrientation() == Qt::Vertical) {
788 layouterSize.rwidth() -= scrollBarExtent;
789 } else {
790 layouterSize.rheight() -= scrollBarExtent;
791 }
792 m_layouter->setSize(layouterSize);
793 }
794
795 if (!hasMultipleRanges) {
796 doLayout(Animation, index, count);
797 }
798 }
799
800 if (m_controller) {
801 m_controller->selectionManager()->itemsInserted(itemRanges);
802 }
803
804 if (hasMultipleRanges) {
805 endTransaction();
806 }
807 }
808
809 void KItemListView::slotItemsRemoved(const KItemRangeList& itemRanges)
810 {
811 updateVisibleRolesSizes();
812
813 const bool hasMultipleRanges = (itemRanges.count() > 1);
814 if (hasMultipleRanges) {
815 beginTransaction();
816 }
817
818 for (int i = itemRanges.count() - 1; i >= 0; --i) {
819 const KItemRange& range = itemRanges.at(i);
820 const int index = range.index;
821 const int count = range.count;
822 if (index < 0 || count <= 0) {
823 kWarning() << "Invalid item range (index:" << index << ", count:" << count << ")";
824 continue;
825 }
826
827 m_sizeHintResolver->itemsRemoved(index, count);
828
829 const int firstRemovedIndex = index;
830 const int lastRemovedIndex = index + count - 1;
831 const int lastIndex = m_model->count() + count - 1;
832
833 // Remove all KItemListWidget instances that got deleted
834 for (int i = firstRemovedIndex; i <= lastRemovedIndex; ++i) {
835 KItemListWidget* widget = m_visibleItems.value(i);
836 if (!widget) {
837 continue;
838 }
839
840 m_animation->stop(widget);
841 // Stopping the animation might lead to recycling the widget if
842 // it is invisible (see slotAnimationFinished()).
843 // Check again whether it is still visible:
844 if (!m_visibleItems.contains(i)) {
845 continue;
846 }
847
848 if (m_model->count() == 0) {
849 // For performance reasons no animation is done when all items have
850 // been removed.
851 recycleWidget(widget);
852 } else {
853 // Animate the removing of the items. Special case: When removing an item there
854 // is no valid model index available anymore. For the
855 // remove-animation the item gets removed from m_visibleItems but the widget
856 // will stay alive until the animation has been finished and will
857 // be recycled (deleted) in KItemListView::slotAnimationFinished().
858 m_visibleItems.remove(i);
859 widget->setIndex(-1);
860 m_animation->start(widget, KItemListViewAnimation::DeleteAnimation);
861 }
862 }
863
864 // Update the indexes of all KItemListWidget instances that are located
865 // after the deleted items
866 for (int i = lastRemovedIndex + 1; i <= lastIndex; ++i) {
867 KItemListWidget* widget = m_visibleItems.value(i);
868 if (widget) {
869 const int newIndex = i - count;
870 setWidgetIndex(widget, newIndex);
871 }
872 }
873
874 m_layouter->markAsDirty();
875 if (!hasMultipleRanges) {
876 doLayout(Animation, index, -count);
877 }
878 }
879
880 if (m_controller) {
881 m_controller->selectionManager()->itemsRemoved(itemRanges);
882 }
883
884 if (hasMultipleRanges) {
885 endTransaction();
886 }
887 }
888
889 void KItemListView::slotItemsMoved(const KItemRange& itemRange, const QList<int>& movedToIndexes)
890 {
891 m_sizeHintResolver->itemsMoved(itemRange.index, itemRange.count);
892 m_layouter->markAsDirty();
893
894 if (m_controller) {
895 m_controller->selectionManager()->itemsMoved(itemRange, movedToIndexes);
896 }
897
898 const int firstVisibleMovedIndex = qMax(firstVisibleIndex(), itemRange.index);
899 const int lastVisibleMovedIndex = qMin(lastVisibleIndex(), itemRange.index + itemRange.count - 1);
900
901 for (int index = firstVisibleMovedIndex; index <= lastVisibleMovedIndex; ++index) {
902 KItemListWidget* widget = m_visibleItems.value(index);
903 if (widget) {
904 updateWidgetProperties(widget, index);
905 if (m_grouped) {
906 updateGroupHeaderForWidget(widget);
907 }
908 initializeItemListWidget(widget);
909 }
910 }
911
912 doLayout(NoAnimation);
913 }
914
915 void KItemListView::slotItemsChanged(const KItemRangeList& itemRanges,
916 const QSet<QByteArray>& roles)
917 {
918 const bool updateSizeHints = itemSizeHintUpdateRequired(roles);
919 if (updateSizeHints) {
920 updateVisibleRolesSizes(itemRanges);
921 }
922
923 foreach (const KItemRange& itemRange, itemRanges) {
924 const int index = itemRange.index;
925 const int count = itemRange.count;
926
927 if (updateSizeHints) {
928 m_sizeHintResolver->itemsChanged(index, count, roles);
929 m_layouter->markAsDirty();
930
931 if (!m_layoutTimer->isActive()) {
932 m_layoutTimer->start();
933 }
934 }
935
936 // Apply the changed roles to the visible item-widgets
937 const int lastIndex = index + count - 1;
938 for (int i = index; i <= lastIndex; ++i) {
939 KItemListWidget* widget = m_visibleItems.value(i);
940 if (widget) {
941 widget->setData(m_model->data(i), roles);
942 }
943 }
944
945 if (m_grouped && roles.contains(m_model->sortRole())) {
946 // The sort-role has been changed which might result
947 // in modified group headers
948 updateVisibleGroupHeaders();
949 doLayout(NoAnimation);
950 }
951 }
952 }
953
954 void KItemListView::slotGroupedSortingChanged(bool current)
955 {
956 m_grouped = current;
957 m_layouter->markAsDirty();
958
959 if (m_grouped) {
960 // Apply the height of the header to the layouter
961 const qreal groupHeaderHeight = m_styleOption.fontMetrics.height() +
962 m_styleOption.margin * 2;
963 m_layouter->setGroupHeaderHeight(groupHeaderHeight);
964
965 updateVisibleGroupHeaders();
966 } else {
967 // Clear all visible headers
968 QMutableHashIterator<KItemListWidget*, KItemListGroupHeader*> it (m_visibleGroups);
969 while (it.hasNext()) {
970 it.next();
971 recycleGroupHeaderForWidget(it.key());
972 }
973 Q_ASSERT(m_visibleGroups.isEmpty());
974 }
975
976 doLayout(Animation);
977 }
978
979 void KItemListView::slotSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous)
980 {
981 Q_UNUSED(current);
982 Q_UNUSED(previous);
983 if (m_grouped) {
984 updateVisibleGroupHeaders();
985 doLayout(Animation);
986 }
987 }
988
989 void KItemListView::slotSortRoleChanged(const QByteArray& current, const QByteArray& previous)
990 {
991 Q_UNUSED(current);
992 Q_UNUSED(previous);
993 if (m_grouped) {
994 updateVisibleGroupHeaders();
995 doLayout(Animation);
996 }
997 }
998
999 void KItemListView::slotCurrentChanged(int current, int previous)
1000 {
1001 Q_UNUSED(previous);
1002
1003 KItemListWidget* previousWidget = m_visibleItems.value(previous, 0);
1004 if (previousWidget) {
1005 Q_ASSERT(previousWidget->isCurrent());
1006 previousWidget->setCurrent(false);
1007 }
1008
1009 KItemListWidget* currentWidget = m_visibleItems.value(current, 0);
1010 if (currentWidget) {
1011 Q_ASSERT(!currentWidget->isCurrent());
1012 currentWidget->setCurrent(true);
1013 }
1014 }
1015
1016 void KItemListView::slotSelectionChanged(const QSet<int>& current, const QSet<int>& previous)
1017 {
1018 Q_UNUSED(previous);
1019
1020 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
1021 while (it.hasNext()) {
1022 it.next();
1023 const int index = it.key();
1024 KItemListWidget* widget = it.value();
1025 widget->setSelected(current.contains(index));
1026 }
1027 }
1028
1029 void KItemListView::slotAnimationFinished(QGraphicsWidget* widget,
1030 KItemListViewAnimation::AnimationType type)
1031 {
1032 KItemListWidget* itemListWidget = qobject_cast<KItemListWidget*>(widget);
1033 Q_ASSERT(itemListWidget);
1034
1035 switch (type) {
1036 case KItemListViewAnimation::DeleteAnimation: {
1037 // As we recycle the widget in this case it is important to assure that no
1038 // other animation has been started. This is a convention in KItemListView and
1039 // not a requirement defined by KItemListViewAnimation.
1040 Q_ASSERT(!m_animation->isStarted(itemListWidget));
1041
1042 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1043 // by m_visibleWidgets and must be deleted manually after the animation has
1044 // been finished.
1045 recycleGroupHeaderForWidget(itemListWidget);
1046 m_widgetCreator->recycle(itemListWidget);
1047 break;
1048 }
1049
1050 case KItemListViewAnimation::CreateAnimation:
1051 case KItemListViewAnimation::MovingAnimation:
1052 case KItemListViewAnimation::ResizeAnimation: {
1053 const int index = itemListWidget->index();
1054 const bool invisible = (index < m_layouter->firstVisibleIndex()) ||
1055 (index > m_layouter->lastVisibleIndex());
1056 if (invisible && !m_animation->isStarted(itemListWidget)) {
1057 recycleWidget(itemListWidget);
1058 }
1059 break;
1060 }
1061
1062 default: break;
1063 }
1064 }
1065
1066 void KItemListView::slotLayoutTimerFinished()
1067 {
1068 m_layouter->setSize(geometry().size());
1069 doLayout(Animation);
1070 }
1071
1072 void KItemListView::slotRubberBandPosChanged()
1073 {
1074 update();
1075 }
1076
1077 void KItemListView::slotRubberBandActivationChanged(bool active)
1078 {
1079 if (active) {
1080 connect(m_rubberBand, SIGNAL(startPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1081 connect(m_rubberBand, SIGNAL(endPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1082 m_skipAutoScrollForRubberBand = true;
1083 } else {
1084 disconnect(m_rubberBand, SIGNAL(startPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1085 disconnect(m_rubberBand, SIGNAL(endPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1086 m_skipAutoScrollForRubberBand = false;
1087 }
1088
1089 update();
1090 }
1091
1092 void KItemListView::slotVisibleRoleWidthChanged(const QByteArray& role,
1093 qreal currentWidth,
1094 qreal previousWidth)
1095 {
1096 Q_UNUSED(previousWidth);
1097
1098 m_useHeaderWidths = true;
1099
1100 if (m_visibleRolesSizes.contains(role)) {
1101 QSizeF roleSize = m_visibleRolesSizes.value(role);
1102 roleSize.setWidth(currentWidth);
1103 m_visibleRolesSizes.insert(role, roleSize);
1104 m_stretchedVisibleRolesSizes.insert(role, roleSize);
1105
1106 // Apply the new size to the layouter
1107 QSizeF dynamicItemSize = m_itemSize;
1108 if (dynamicItemSize.width() < 0) {
1109 const qreal requiredWidth = visibleRolesSizesWidthSum();
1110 dynamicItemSize.setWidth(qMax(size().width(), requiredWidth));
1111 }
1112 if (dynamicItemSize.height() < 0) {
1113 const qreal requiredHeight = visibleRolesSizesHeightSum();
1114 dynamicItemSize.setHeight(qMax(size().height(), requiredHeight));
1115 }
1116
1117 m_layouter->setItemSize(dynamicItemSize);
1118
1119 // Update the role sizes for all visible widgets
1120 foreach (KItemListWidget* widget, visibleItemListWidgets()) {
1121 widget->setVisibleRolesSizes(m_stretchedVisibleRolesSizes);
1122 }
1123
1124 doLayout(Animation);
1125 }
1126 }
1127
1128 void KItemListView::triggerAutoScrolling()
1129 {
1130 if (!m_autoScrollTimer) {
1131 return;
1132 }
1133
1134 int pos = 0;
1135 int visibleSize = 0;
1136 if (scrollOrientation() == Qt::Vertical) {
1137 pos = m_mousePos.y();
1138 visibleSize = size().height();
1139 } else {
1140 pos = m_mousePos.x();
1141 visibleSize = size().width();
1142 }
1143
1144 if (m_autoScrollTimer->interval() == InitialAutoScrollDelay) {
1145 m_autoScrollIncrement = 0;
1146 }
1147
1148 m_autoScrollIncrement = calculateAutoScrollingIncrement(pos, visibleSize, m_autoScrollIncrement);
1149 if (m_autoScrollIncrement == 0) {
1150 // The mouse position is not above an autoscroll margin (the autoscroll timer
1151 // will be restarted in mouseMoveEvent())
1152 m_autoScrollTimer->stop();
1153 return;
1154 }
1155
1156 if (m_rubberBand->isActive() && m_skipAutoScrollForRubberBand) {
1157 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1158 // if the direction of the rubberband is similar to the autoscroll direction. This
1159 // prevents that starting to create a rubberband within the autoscroll margins starts
1160 // an autoscrolling.
1161
1162 const qreal minDiff = 4; // Ignore any autoscrolling if the rubberband is very small
1163 const qreal diff = (scrollOrientation() == Qt::Vertical)
1164 ? m_rubberBand->endPosition().y() - m_rubberBand->startPosition().y()
1165 : m_rubberBand->endPosition().x() - m_rubberBand->startPosition().x();
1166 if (qAbs(diff) < minDiff || (m_autoScrollIncrement < 0 && diff > 0) || (m_autoScrollIncrement > 0 && diff < 0)) {
1167 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1168 // been moved up although the autoscroll direction might be down)
1169 m_autoScrollTimer->stop();
1170 return;
1171 }
1172 }
1173
1174 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1175 // the autoscrolling may not get skipped anymore until a new rubberband is created
1176 m_skipAutoScrollForRubberBand = false;
1177
1178 const qreal maxVisibleOffset = qMax(qreal(0), maximumScrollOffset() - visibleSize);
1179 const qreal newScrollOffset = qMin(scrollOffset() + m_autoScrollIncrement, maxVisibleOffset);
1180 setScrollOffset(newScrollOffset);
1181
1182 // Trigger the autoscroll timer which will periodically call
1183 // triggerAutoScrolling()
1184 m_autoScrollTimer->start(RepeatingAutoScrollDelay);
1185 }
1186
1187 void KItemListView::setController(KItemListController* controller)
1188 {
1189 if (m_controller != controller) {
1190 KItemListController* previous = m_controller;
1191 if (previous) {
1192 KItemListSelectionManager* selectionManager = previous->selectionManager();
1193 disconnect(selectionManager, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1194 disconnect(selectionManager, SIGNAL(selectionChanged(QSet<int>,QSet<int>)), this, SLOT(slotSelectionChanged(QSet<int>,QSet<int>)));
1195 }
1196
1197 m_controller = controller;
1198
1199 if (controller) {
1200 KItemListSelectionManager* selectionManager = controller->selectionManager();
1201 connect(selectionManager, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1202 connect(selectionManager, SIGNAL(selectionChanged(QSet<int>,QSet<int>)), this, SLOT(slotSelectionChanged(QSet<int>,QSet<int>)));
1203 }
1204
1205 onControllerChanged(controller, previous);
1206 }
1207 }
1208
1209 void KItemListView::setModel(KItemModelBase* model)
1210 {
1211 if (m_model == model) {
1212 return;
1213 }
1214
1215 KItemModelBase* previous = m_model;
1216
1217 if (m_model) {
1218 disconnect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
1219 this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
1220 disconnect(m_model, SIGNAL(itemsInserted(KItemRangeList)),
1221 this, SLOT(slotItemsInserted(KItemRangeList)));
1222 disconnect(m_model, SIGNAL(itemsRemoved(KItemRangeList)),
1223 this, SLOT(slotItemsRemoved(KItemRangeList)));
1224 disconnect(m_model, SIGNAL(itemsMoved(KItemRange,QList<int>)),
1225 this, SLOT(slotItemsMoved(KItemRange,QList<int>)));
1226 disconnect(m_model, SIGNAL(groupedSortingChanged(bool)),
1227 this, SLOT(slotGroupedSortingChanged(bool)));
1228 disconnect(m_model, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)),
1229 this, SLOT(slotSortOrderChanged(Qt::SortOrder,Qt::SortOrder)));
1230 disconnect(m_model, SIGNAL(sortRoleChanged(QByteArray,QByteArray)),
1231 this, SLOT(slotSortRoleChanged(QByteArray,QByteArray)));
1232 }
1233
1234 m_model = model;
1235 m_layouter->setModel(model);
1236 m_grouped = model->groupedSorting();
1237
1238 if (m_model) {
1239 connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
1240 this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
1241 connect(m_model, SIGNAL(itemsInserted(KItemRangeList)),
1242 this, SLOT(slotItemsInserted(KItemRangeList)));
1243 connect(m_model, SIGNAL(itemsRemoved(KItemRangeList)),
1244 this, SLOT(slotItemsRemoved(KItemRangeList)));
1245 connect(m_model, SIGNAL(itemsMoved(KItemRange,QList<int>)),
1246 this, SLOT(slotItemsMoved(KItemRange,QList<int>)));
1247 connect(m_model, SIGNAL(groupedSortingChanged(bool)),
1248 this, SLOT(slotGroupedSortingChanged(bool)));
1249 connect(m_model, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)),
1250 this, SLOT(slotSortOrderChanged(Qt::SortOrder,Qt::SortOrder)));
1251 connect(m_model, SIGNAL(sortRoleChanged(QByteArray,QByteArray)),
1252 this, SLOT(slotSortRoleChanged(QByteArray,QByteArray)));
1253 }
1254
1255 onModelChanged(model, previous);
1256 }
1257
1258 KItemListRubberBand* KItemListView::rubberBand() const
1259 {
1260 return m_rubberBand;
1261 }
1262
1263 void KItemListView::doLayout(LayoutAnimationHint hint, int changedIndex, int changedCount)
1264 {
1265 if (m_layoutTimer->isActive()) {
1266 m_layoutTimer->stop();
1267 }
1268
1269 if (!m_model || m_model->count() < 0 || m_activeTransactions > 0) {
1270 return;
1271 }
1272
1273 const int firstVisibleIndex = m_layouter->firstVisibleIndex();
1274 const int lastVisibleIndex = m_layouter->lastVisibleIndex();
1275 if (firstVisibleIndex < 0) {
1276 emitOffsetChanges();
1277 return;
1278 }
1279
1280 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1281 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1282 // is still shown if the maximum offset got decreased.
1283 const qreal visibleOffsetRange = (scrollOrientation() == Qt::Horizontal) ? size().width() : size().height();
1284 const qreal maxOffsetToShowFullRange = maximumScrollOffset() - visibleOffsetRange;
1285 if (scrollOffset() > maxOffsetToShowFullRange) {
1286 m_layouter->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange));
1287 }
1288
1289 // Determine all items that are completely invisible and might be
1290 // reused for items that just got (at least partly) visible.
1291 // Items that do e.g. an animated moving of their position are not
1292 // marked as invisible: This assures that a scrolling inside the view
1293 // can be done without breaking an animation.
1294 QList<int> reusableItems;
1295 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
1296 while (it.hasNext()) {
1297 it.next();
1298 KItemListWidget* widget = it.value();
1299 const int index = widget->index();
1300 const bool invisible = (index < firstVisibleIndex) || (index > lastVisibleIndex);
1301 if (invisible && !m_animation->isStarted(widget)) {
1302 widget->setVisible(false);
1303 reusableItems.append(index);
1304
1305 if (m_grouped) {
1306 recycleGroupHeaderForWidget(widget);
1307 }
1308 }
1309 }
1310
1311 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1312 // instances from invisible items are reused. If no reusable items are
1313 // found then new KItemListWidget instances get created.
1314 const bool animate = (hint == Animation);
1315 for (int i = firstVisibleIndex; i <= lastVisibleIndex; ++i) {
1316 bool applyNewPos = true;
1317 bool wasHidden = false;
1318
1319 const QRectF itemBounds = m_layouter->itemRect(i);
1320 const QPointF newPos = itemBounds.topLeft();
1321 KItemListWidget* widget = m_visibleItems.value(i);
1322 if (!widget) {
1323 wasHidden = true;
1324 if (!reusableItems.isEmpty()) {
1325 // Reuse a KItemListWidget instance from an invisible item
1326 const int oldIndex = reusableItems.takeLast();
1327 widget = m_visibleItems.value(oldIndex);
1328 setWidgetIndex(widget, i);
1329
1330 if (m_grouped) {
1331 updateGroupHeaderForWidget(widget);
1332 }
1333 } else {
1334 // No reusable KItemListWidget instance is available, create a new one
1335 widget = createWidget(i);
1336 }
1337 widget->resize(itemBounds.size());
1338
1339 if (animate && changedCount < 0) {
1340 // Items have been deleted, move the created item to the
1341 // imaginary old position. They will get animated to the new position
1342 // later.
1343 const QRectF itemRect = m_layouter->itemRect(i - changedCount);
1344 if (itemRect.isEmpty()) {
1345 const QPointF invisibleOldPos = (scrollOrientation() == Qt::Vertical)
1346 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1347 widget->setPos(invisibleOldPos);
1348 } else {
1349 widget->setPos(itemRect.topLeft());
1350 }
1351 applyNewPos = false;
1352 }
1353 } else if (m_animation->isStarted(widget, KItemListViewAnimation::MovingAnimation)) {
1354 applyNewPos = false;
1355 }
1356
1357 if (animate) {
1358 const bool itemsRemoved = (changedCount < 0);
1359 const bool itemsInserted = (changedCount > 0);
1360 if (itemsRemoved && (i >= changedIndex + changedCount + 1)) {
1361 // The item is located after the removed items. Animate the moving of the position.
1362 m_animation->start(widget, KItemListViewAnimation::MovingAnimation, newPos);
1363 applyNewPos = false;
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 m_animation->start(widget, KItemListViewAnimation::MovingAnimation, newPos);
1378 applyNewPos = false;
1379 }
1380 } else if (!itemsRemoved && !itemsInserted && !wasHidden) {
1381 // The size of the view might have been changed. Animate the moving of the position.
1382 m_animation->start(widget, KItemListViewAnimation::MovingAnimation, newPos);
1383 applyNewPos = false;
1384 }
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 void KItemListView::emitOffsetChanges()
1431 {
1432 const qreal newScrollOffset = m_layouter->scrollOffset();
1433 if (m_oldScrollOffset != newScrollOffset) {
1434 emit scrollOffsetChanged(newScrollOffset, m_oldScrollOffset);
1435 m_oldScrollOffset = newScrollOffset;
1436 }
1437
1438 const qreal newMaximumScrollOffset = m_layouter->maximumScrollOffset();
1439 if (m_oldMaximumScrollOffset != newMaximumScrollOffset) {
1440 emit maximumScrollOffsetChanged(newMaximumScrollOffset, m_oldMaximumScrollOffset);
1441 m_oldMaximumScrollOffset = newMaximumScrollOffset;
1442 }
1443
1444 const qreal newItemOffset = m_layouter->itemOffset();
1445 if (m_oldItemOffset != newItemOffset) {
1446 emit itemOffsetChanged(newItemOffset, m_oldItemOffset);
1447 m_oldItemOffset = newItemOffset;
1448 }
1449
1450 const qreal newMaximumItemOffset = m_layouter->maximumItemOffset();
1451 if (m_oldMaximumItemOffset != newMaximumItemOffset) {
1452 emit maximumItemOffsetChanged(newMaximumItemOffset, m_oldMaximumItemOffset);
1453 m_oldMaximumItemOffset = newMaximumItemOffset;
1454 }
1455 }
1456
1457 KItemListWidget* KItemListView::createWidget(int index)
1458 {
1459 KItemListWidget* widget = m_widgetCreator->create(this);
1460 widget->setFlag(QGraphicsItem::ItemStacksBehindParent);
1461
1462 updateWidgetProperties(widget, index);
1463 m_visibleItems.insert(index, widget);
1464
1465 if (m_grouped) {
1466 updateGroupHeaderForWidget(widget);
1467 }
1468
1469 initializeItemListWidget(widget);
1470 return widget;
1471 }
1472
1473 void KItemListView::recycleWidget(KItemListWidget* widget)
1474 {
1475 if (m_grouped) {
1476 recycleGroupHeaderForWidget(widget);
1477 }
1478
1479 m_visibleItems.remove(widget->index());
1480 m_widgetCreator->recycle(widget);
1481 }
1482
1483 void KItemListView::setWidgetIndex(KItemListWidget* widget, int index)
1484 {
1485 const int oldIndex = widget->index();
1486 m_visibleItems.remove(oldIndex);
1487 updateWidgetProperties(widget, index);
1488 m_visibleItems.insert(index, widget);
1489
1490 initializeItemListWidget(widget);
1491 }
1492
1493 void KItemListView::prepareLayoutForIncreasedItemCount(const QSizeF& size, SizeType sizeType)
1494 {
1495 // Calculate the first visible index and last visible index for the current size
1496 const int currentFirst = m_layouter->firstVisibleIndex();
1497 const int currentLast = m_layouter->lastVisibleIndex();
1498
1499 const QSizeF currentSize = (sizeType == LayouterSize) ? m_layouter->size() : m_layouter->itemSize();
1500
1501 // Calculate the first visible index and last visible index for the new size
1502 setLayouterSize(size, sizeType);
1503 const int newFirst = m_layouter->firstVisibleIndex();
1504 const int newLast = m_layouter->lastVisibleIndex();
1505
1506 if ((currentFirst != newFirst) || (currentLast != newLast)) {
1507 // At least one index has been changed. Assure that widgets for all possible
1508 // visible items get created so that a move-animation can be started later.
1509 const int maxVisibleItems = m_layouter->maximumVisibleItems();
1510 int minFirst = qMin(newFirst, currentFirst);
1511 const int maxLast = qMax(newLast, currentLast);
1512
1513 if (maxLast - minFirst + 1 < maxVisibleItems) {
1514 // Increasing the size might result in a smaller KItemListView::offset().
1515 // Decrease the first visible index in a way that at least the maximum
1516 // visible items are shown.
1517 minFirst = qMax(0, maxLast - maxVisibleItems + 1);
1518 }
1519
1520 if (maxLast - minFirst > maxVisibleItems + maxVisibleItems / 2) {
1521 // The creating of widgets is quite expensive. Assure that never more
1522 // than 50 % of the maximum visible items get created for the animations.
1523 return;
1524 }
1525
1526 setLayouterSize(currentSize, sizeType);
1527 for (int i = minFirst; i <= maxLast; ++i) {
1528 if (!m_visibleItems.contains(i)) {
1529 KItemListWidget* widget = createWidget(i);
1530 const QRectF itemRect = m_layouter->itemRect(i);
1531 widget->setPos(itemRect.topLeft());
1532 widget->resize(itemRect.size());
1533 }
1534 }
1535 setLayouterSize(size, sizeType);
1536 }
1537 }
1538
1539 void KItemListView::setLayouterSize(const QSizeF& size, SizeType sizeType)
1540 {
1541 switch (sizeType) {
1542 case LayouterSize: m_layouter->setSize(size); break;
1543 case ItemSize: m_layouter->setItemSize(size); break;
1544 default: break;
1545 }
1546 }
1547
1548 void KItemListView::updateWidgetProperties(KItemListWidget* widget, int index)
1549 {
1550 widget->setVisibleRoles(m_visibleRoles);
1551 widget->setVisibleRolesSizes(m_stretchedVisibleRolesSizes);
1552 widget->setStyleOption(m_styleOption);
1553
1554 const KItemListSelectionManager* selectionManager = m_controller->selectionManager();
1555 widget->setCurrent(index == selectionManager->currentItem());
1556 widget->setSelected(selectionManager->isSelected(index));
1557 widget->setHovered(false);
1558 widget->setAlternatingBackgroundColors(false);
1559 widget->setEnabledSelectionToggle(enabledSelectionToggles());
1560 widget->setIndex(index);
1561 widget->setData(m_model->data(index));
1562 }
1563
1564 void KItemListView::updateGroupHeaderForWidget(KItemListWidget* widget)
1565 {
1566 Q_ASSERT(m_grouped);
1567
1568 const int index = widget->index();
1569 if (!m_layouter->isFirstGroupItem(index)) {
1570 // The widget does not represent the first item of a group
1571 // and hence requires no header
1572 recycleGroupHeaderForWidget(widget);
1573 return;
1574 }
1575
1576 const QList<QPair<int, QVariant> > groups = model()->groups();
1577 if (groups.isEmpty()) {
1578 return;
1579 }
1580
1581 KItemListGroupHeader* header = m_visibleGroups.value(widget);
1582 if (!header) {
1583 header = m_groupHeaderCreator->create(this);
1584 header->setParentItem(widget);
1585 m_visibleGroups.insert(widget, header);
1586 }
1587 Q_ASSERT(header->parentItem() == widget);
1588
1589 // Determine the shown data for the header by doing a binary
1590 // search in the groups-list
1591 int min = 0;
1592 int max = groups.count() - 1;
1593 int mid = 0;
1594 do {
1595 mid = (min + max) / 2;
1596 if (index > groups.at(mid).first) {
1597 min = mid + 1;
1598 } else {
1599 max = mid - 1;
1600 }
1601 } while (groups.at(mid).first != index && min <= max);
1602
1603 header->setData(groups.at(mid).second);
1604 header->setRole(model()->sortRole());
1605 header->setStyleOption(m_styleOption);
1606 header->setScrollOrientation(scrollOrientation());
1607
1608 header->show();
1609 }
1610
1611 void KItemListView::updateGroupHeaderLayout(KItemListWidget* widget)
1612 {
1613 KItemListGroupHeader* header = m_visibleGroups.value(widget);
1614 Q_ASSERT(header);
1615
1616 const int index = widget->index();
1617 const QRectF groupHeaderRect = m_layouter->groupHeaderRect(index);
1618 const QRectF itemRect = m_layouter->itemRect(index);
1619
1620 // The group-header is a child of the itemlist widget. Translate the
1621 // group header position to the relative position.
1622 const QPointF groupHeaderPos(groupHeaderRect.x() - itemRect.x(),
1623 - groupHeaderRect.height());
1624 header->setPos(groupHeaderPos);
1625 header->resize(groupHeaderRect.size());
1626 }
1627
1628 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget* widget)
1629 {
1630 KItemListGroupHeader* header = m_visibleGroups.value(widget);
1631 if (header) {
1632 header->setParentItem(0);
1633 m_groupHeaderCreator->recycle(header);
1634 m_visibleGroups.remove(widget);
1635 }
1636 }
1637
1638 void KItemListView::updateVisibleGroupHeaders()
1639 {
1640 Q_ASSERT(m_grouped);
1641 m_layouter->markAsDirty();
1642
1643 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
1644 while (it.hasNext()) {
1645 it.next();
1646 updateGroupHeaderForWidget(it.value());
1647 }
1648 }
1649
1650 QHash<QByteArray, qreal> KItemListView::headerRolesWidths() const
1651 {
1652 QHash<QByteArray, qreal> rolesWidths;
1653
1654 QHashIterator<QByteArray, QSizeF> it(m_stretchedVisibleRolesSizes);
1655 while (it.hasNext()) {
1656 it.next();
1657 rolesWidths.insert(it.key(), it.value().width());
1658 }
1659
1660 return rolesWidths;
1661 }
1662
1663 void KItemListView::updateVisibleRolesSizes(const KItemRangeList& itemRanges)
1664 {
1665 if (!m_itemSize.isEmpty() || m_useHeaderWidths) {
1666 return;
1667 }
1668
1669 const int itemCount = m_model->count();
1670 int rangesItemCount = 0;
1671 foreach (const KItemRange& range, itemRanges) {
1672 rangesItemCount += range.count;
1673 }
1674
1675 if (itemCount == rangesItemCount) {
1676 m_visibleRolesSizes = visibleRolesSizes(itemRanges);
1677 if (m_header) {
1678 // Assure the the sizes are not smaller than the minimum defined by the header
1679 // TODO: Currently only implemented for a top-aligned header
1680 const qreal minHeaderRoleWidth = m_header->minimumRoleWidth();
1681 QMutableHashIterator<QByteArray, QSizeF> it (m_visibleRolesSizes);
1682 while (it.hasNext()) {
1683 it.next();
1684 const QSizeF& size = it.value();
1685 if (size.width() < minHeaderRoleWidth) {
1686 const QSizeF newSize(minHeaderRoleWidth, size.height());
1687 m_visibleRolesSizes.insert(it.key(), newSize);
1688 }
1689 }
1690 }
1691 } else {
1692 // Only a sub range of the roles need to be determined.
1693 // The chances are good that the sizes of the sub ranges
1694 // already fit into the available sizes and hence no
1695 // expensive update might be required.
1696 bool updateRequired = false;
1697
1698 const QHash<QByteArray, QSizeF> updatedSizes = visibleRolesSizes(itemRanges);
1699 QHashIterator<QByteArray, QSizeF> it(updatedSizes);
1700 while (it.hasNext()) {
1701 it.next();
1702 const QByteArray& role = it.key();
1703 const QSizeF& updatedSize = it.value();
1704 const QSizeF currentSize = m_visibleRolesSizes.value(role);
1705 if (updatedSize.width() > currentSize.width() || updatedSize.height() > currentSize.height()) {
1706 m_visibleRolesSizes.insert(role, updatedSize);
1707 updateRequired = true;
1708 }
1709 }
1710
1711 if (!updateRequired) {
1712 // All the updated sizes are smaller than the current sizes and no change
1713 // of the stretched roles-widths is required
1714 return;
1715 }
1716 }
1717
1718 updateStretchedVisibleRolesSizes();
1719 }
1720
1721 void KItemListView::updateVisibleRolesSizes()
1722 {
1723 if (!m_model) {
1724 return;
1725 }
1726
1727 const int itemCount = m_model->count();
1728 if (itemCount > 0) {
1729 updateVisibleRolesSizes(KItemRangeList() << KItemRange(0, itemCount));
1730 }
1731 }
1732
1733 void KItemListView::updateStretchedVisibleRolesSizes()
1734 {
1735 if (!m_itemSize.isEmpty() || m_useHeaderWidths || m_visibleRoles.isEmpty()) {
1736 return;
1737 }
1738
1739 // Calculate the maximum size of an item by considering the
1740 // visible role sizes and apply them to the layouter. If the
1741 // size does not use the available view-size it the size of the
1742 // first role will get stretched.
1743 m_stretchedVisibleRolesSizes = m_visibleRolesSizes;
1744 const QByteArray role = m_visibleRoles.first();
1745 QSizeF firstRoleSize = m_stretchedVisibleRolesSizes.value(role);
1746
1747 QSizeF dynamicItemSize = m_itemSize;
1748
1749 if (dynamicItemSize.width() <= 0) {
1750 const qreal requiredWidth = visibleRolesSizesWidthSum();
1751 const qreal availableWidth = size().width();
1752 if (requiredWidth < availableWidth) {
1753 // Stretch the first role to use the whole width for the item
1754 firstRoleSize.rwidth() += availableWidth - requiredWidth;
1755 m_stretchedVisibleRolesSizes.insert(role, firstRoleSize);
1756 }
1757 dynamicItemSize.setWidth(qMax(requiredWidth, availableWidth));
1758 }
1759
1760 if (dynamicItemSize.height() <= 0) {
1761 const qreal requiredHeight = visibleRolesSizesHeightSum();
1762 const qreal availableHeight = size().height();
1763 if (requiredHeight < availableHeight) {
1764 // Stretch the first role to use the whole height for the item
1765 firstRoleSize.rheight() += availableHeight - requiredHeight;
1766 m_stretchedVisibleRolesSizes.insert(role, firstRoleSize);
1767 }
1768 dynamicItemSize.setHeight(qMax(requiredHeight, availableHeight));
1769 }
1770
1771 m_layouter->setItemSize(dynamicItemSize);
1772
1773 if (m_header) {
1774 m_header->setVisibleRolesWidths(headerRolesWidths());
1775 m_header->resize(dynamicItemSize.width(), m_header->size().height());
1776 }
1777
1778 // Update the role sizes for all visible widgets
1779 foreach (KItemListWidget* widget, visibleItemListWidgets()) {
1780 widget->setVisibleRolesSizes(m_stretchedVisibleRolesSizes);
1781 }
1782 }
1783
1784 qreal KItemListView::visibleRolesSizesWidthSum() const
1785 {
1786 qreal widthSum = 0;
1787 QHashIterator<QByteArray, QSizeF> it(m_visibleRolesSizes);
1788 while (it.hasNext()) {
1789 it.next();
1790 widthSum += it.value().width();
1791 }
1792 return widthSum;
1793 }
1794
1795 qreal KItemListView::visibleRolesSizesHeightSum() const
1796 {
1797 qreal heightSum = 0;
1798 QHashIterator<QByteArray, QSizeF> it(m_visibleRolesSizes);
1799 while (it.hasNext()) {
1800 it.next();
1801 heightSum += it.value().height();
1802 }
1803 return heightSum;
1804 }
1805
1806 QRectF KItemListView::headerBoundaries() const
1807 {
1808 return m_header ? m_header->geometry() : QRectF();
1809 }
1810
1811 int KItemListView::calculateAutoScrollingIncrement(int pos, int range, int oldInc)
1812 {
1813 int inc = 0;
1814
1815 const int minSpeed = 4;
1816 const int maxSpeed = 128;
1817 const int speedLimiter = 96;
1818 const int autoScrollBorder = 64;
1819
1820 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
1821 // This assures that the autoscrolling speed grows gradually.
1822 const int incLimiter = 1;
1823
1824 if (pos < autoScrollBorder) {
1825 inc = -minSpeed + qAbs(pos - autoScrollBorder) * (pos - autoScrollBorder) / speedLimiter;
1826 inc = qMax(inc, -maxSpeed);
1827 inc = qMax(inc, oldInc - incLimiter);
1828 } else if (pos > range - autoScrollBorder) {
1829 inc = minSpeed + qAbs(pos - range + autoScrollBorder) * (pos - range + autoScrollBorder) / speedLimiter;
1830 inc = qMin(inc, maxSpeed);
1831 inc = qMin(inc, oldInc + incLimiter);
1832 }
1833
1834 return inc;
1835 }
1836
1837
1838
1839 KItemListCreatorBase::~KItemListCreatorBase()
1840 {
1841 qDeleteAll(m_recycleableWidgets);
1842 qDeleteAll(m_createdWidgets);
1843 }
1844
1845 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget* widget)
1846 {
1847 m_createdWidgets.insert(widget);
1848 }
1849
1850 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget* widget)
1851 {
1852 Q_ASSERT(m_createdWidgets.contains(widget));
1853 m_createdWidgets.remove(widget);
1854
1855 if (m_recycleableWidgets.count() < 100) {
1856 m_recycleableWidgets.append(widget);
1857 widget->setVisible(false);
1858 } else {
1859 delete widget;
1860 }
1861 }
1862
1863 QGraphicsWidget* KItemListCreatorBase::popRecycleableWidget()
1864 {
1865 if (m_recycleableWidgets.isEmpty()) {
1866 return 0;
1867 }
1868
1869 QGraphicsWidget* widget = m_recycleableWidgets.takeLast();
1870 m_createdWidgets.insert(widget);
1871 return widget;
1872 }
1873
1874 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
1875 {
1876 }
1877
1878 void KItemListWidgetCreatorBase::recycle(KItemListWidget* widget)
1879 {
1880 widget->setParentItem(0);
1881 widget->setOpacity(1.0);
1882 pushRecycleableWidget(widget);
1883 }
1884
1885 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
1886 {
1887 }
1888
1889 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader* header)
1890 {
1891 header->setOpacity(1.0);
1892 pushRecycleableWidget(header);
1893 }
1894
1895 #include "kitemlistview.moc"