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