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