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