]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kitemlistview.cpp
Compact view: Padding- and margin-improvements for grouped alignments
[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 updateSiblingsInformation();
837 }
838 }
839
840 if (m_controller) {
841 m_controller->selectionManager()->itemsInserted(itemRanges);
842 }
843
844 if (hasMultipleRanges) {
845 m_endTransactionAnimationHint = NoAnimation;
846 endTransaction();
847 updateSiblingsInformation();
848 }
849 }
850
851 void KItemListView::slotItemsRemoved(const KItemRangeList& itemRanges)
852 {
853 updateVisibleRolesSizes();
854
855 const bool hasMultipleRanges = (itemRanges.count() > 1);
856 if (hasMultipleRanges) {
857 beginTransaction();
858 }
859
860 for (int i = itemRanges.count() - 1; i >= 0; --i) {
861 const KItemRange& range = itemRanges.at(i);
862 const int index = range.index;
863 const int count = range.count;
864 if (index < 0 || count <= 0) {
865 kWarning() << "Invalid item range (index:" << index << ", count:" << count << ")";
866 continue;
867 }
868
869 m_sizeHintResolver->itemsRemoved(index, count);
870
871 const int firstRemovedIndex = index;
872 const int lastRemovedIndex = index + count - 1;
873 const int lastIndex = m_model->count() + count - 1;
874
875 // Remove all KItemListWidget instances that got deleted
876 for (int i = firstRemovedIndex; i <= lastRemovedIndex; ++i) {
877 KItemListWidget* widget = m_visibleItems.value(i);
878 if (!widget) {
879 continue;
880 }
881
882 m_animation->stop(widget);
883 // Stopping the animation might lead to recycling the widget if
884 // it is invisible (see slotAnimationFinished()).
885 // Check again whether it is still visible:
886 if (!m_visibleItems.contains(i)) {
887 continue;
888 }
889
890 if (m_model->count() == 0 || hasMultipleRanges || !animateChangedItemCount(count)) {
891 // Remove the widget without animation
892 recycleWidget(widget);
893 } else {
894 // Animate the removing of the items. Special case: When removing an item there
895 // is no valid model index available anymore. For the
896 // remove-animation the item gets removed from m_visibleItems but the widget
897 // will stay alive until the animation has been finished and will
898 // be recycled (deleted) in KItemListView::slotAnimationFinished().
899 m_visibleItems.remove(i);
900 widget->setIndex(-1);
901 m_animation->start(widget, KItemListViewAnimation::DeleteAnimation);
902 }
903 }
904
905 // Update the indexes of all KItemListWidget instances that are located
906 // after the deleted items
907 for (int i = lastRemovedIndex + 1; i <= lastIndex; ++i) {
908 KItemListWidget* widget = m_visibleItems.value(i);
909 if (widget) {
910 const int newIndex = i - count;
911 setWidgetIndex(widget, newIndex);
912 }
913 }
914
915 m_layouter->markAsDirty();
916 if (!hasMultipleRanges) {
917 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
918 // assumes an updated geometry. If items are removed during an active transaction,
919 // the transaction will be temporary deactivated so that doLayout() triggers a
920 // geometry update if necessary.
921 const int activeTransactions = m_activeTransactions;
922 m_activeTransactions = 0;
923 doLayout(animateChangedItemCount(count) ? Animation : NoAnimation, index, -count);
924 m_activeTransactions = activeTransactions;
925 updateSiblingsInformation();
926 }
927 }
928
929 if (m_controller) {
930 m_controller->selectionManager()->itemsRemoved(itemRanges);
931 }
932
933 if (hasMultipleRanges) {
934 m_endTransactionAnimationHint = NoAnimation;
935 endTransaction();
936 updateSiblingsInformation();
937 }
938 }
939
940 void KItemListView::slotItemsMoved(const KItemRange& itemRange, const QList<int>& movedToIndexes)
941 {
942 m_sizeHintResolver->itemsMoved(itemRange.index, itemRange.count);
943 m_layouter->markAsDirty();
944
945 if (m_controller) {
946 m_controller->selectionManager()->itemsMoved(itemRange, movedToIndexes);
947 }
948
949 const int firstVisibleMovedIndex = qMax(firstVisibleIndex(), itemRange.index);
950 const int lastVisibleMovedIndex = qMin(lastVisibleIndex(), itemRange.index + itemRange.count - 1);
951
952 for (int index = firstVisibleMovedIndex; index <= lastVisibleMovedIndex; ++index) {
953 KItemListWidget* widget = m_visibleItems.value(index);
954 if (widget) {
955 updateWidgetProperties(widget, index);
956 if (m_grouped) {
957 updateGroupHeaderForWidget(widget);
958 }
959 initializeItemListWidget(widget);
960 }
961 }
962
963 doLayout(NoAnimation);
964 updateSiblingsInformation();
965 }
966
967 void KItemListView::slotItemsChanged(const KItemRangeList& itemRanges,
968 const QSet<QByteArray>& roles)
969 {
970 const bool updateSizeHints = itemSizeHintUpdateRequired(roles);
971 if (updateSizeHints) {
972 updateVisibleRolesSizes(itemRanges);
973 }
974
975 foreach (const KItemRange& itemRange, itemRanges) {
976 const int index = itemRange.index;
977 const int count = itemRange.count;
978
979 if (updateSizeHints) {
980 m_sizeHintResolver->itemsChanged(index, count, roles);
981 m_layouter->markAsDirty();
982
983 if (!m_layoutTimer->isActive()) {
984 m_layoutTimer->start();
985 }
986 }
987
988 // Apply the changed roles to the visible item-widgets
989 const int lastIndex = index + count - 1;
990 for (int i = index; i <= lastIndex; ++i) {
991 KItemListWidget* widget = m_visibleItems.value(i);
992 if (widget) {
993 widget->setData(m_model->data(i), roles);
994 }
995 }
996
997 if (m_grouped && roles.contains(m_model->sortRole())) {
998 // The sort-role has been changed which might result
999 // in modified group headers
1000 updateVisibleGroupHeaders();
1001 doLayout(NoAnimation);
1002 }
1003 }
1004 }
1005
1006 void KItemListView::slotGroupedSortingChanged(bool current)
1007 {
1008 m_grouped = current;
1009 m_layouter->markAsDirty();
1010
1011 if (m_grouped) {
1012 updateGroupHeaderHeight();
1013 } else {
1014 // Clear all visible headers
1015 QMutableHashIterator<KItemListWidget*, KItemListGroupHeader*> it (m_visibleGroups);
1016 while (it.hasNext()) {
1017 it.next();
1018 recycleGroupHeaderForWidget(it.key());
1019 }
1020 Q_ASSERT(m_visibleGroups.isEmpty());
1021 }
1022
1023 doLayout(NoAnimation);
1024 }
1025
1026 void KItemListView::slotSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous)
1027 {
1028 Q_UNUSED(current);
1029 Q_UNUSED(previous);
1030 if (m_grouped) {
1031 updateVisibleGroupHeaders();
1032 doLayout(NoAnimation);
1033 }
1034 }
1035
1036 void KItemListView::slotSortRoleChanged(const QByteArray& current, const QByteArray& previous)
1037 {
1038 Q_UNUSED(current);
1039 Q_UNUSED(previous);
1040 if (m_grouped) {
1041 updateVisibleGroupHeaders();
1042 doLayout(NoAnimation);
1043 }
1044 }
1045
1046 void KItemListView::slotCurrentChanged(int current, int previous)
1047 {
1048 Q_UNUSED(previous);
1049
1050 KItemListWidget* previousWidget = m_visibleItems.value(previous, 0);
1051 if (previousWidget) {
1052 Q_ASSERT(previousWidget->isCurrent());
1053 previousWidget->setCurrent(false);
1054 }
1055
1056 KItemListWidget* currentWidget = m_visibleItems.value(current, 0);
1057 if (currentWidget) {
1058 Q_ASSERT(!currentWidget->isCurrent());
1059 currentWidget->setCurrent(true);
1060 }
1061 }
1062
1063 void KItemListView::slotSelectionChanged(const QSet<int>& current, const QSet<int>& previous)
1064 {
1065 Q_UNUSED(previous);
1066
1067 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
1068 while (it.hasNext()) {
1069 it.next();
1070 const int index = it.key();
1071 KItemListWidget* widget = it.value();
1072 widget->setSelected(current.contains(index));
1073 }
1074 }
1075
1076 void KItemListView::slotAnimationFinished(QGraphicsWidget* widget,
1077 KItemListViewAnimation::AnimationType type)
1078 {
1079 KItemListWidget* itemListWidget = qobject_cast<KItemListWidget*>(widget);
1080 Q_ASSERT(itemListWidget);
1081
1082 switch (type) {
1083 case KItemListViewAnimation::DeleteAnimation: {
1084 // As we recycle the widget in this case it is important to assure that no
1085 // other animation has been started. This is a convention in KItemListView and
1086 // not a requirement defined by KItemListViewAnimation.
1087 Q_ASSERT(!m_animation->isStarted(itemListWidget));
1088
1089 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1090 // by m_visibleWidgets and must be deleted manually after the animation has
1091 // been finished.
1092 recycleGroupHeaderForWidget(itemListWidget);
1093 m_widgetCreator->recycle(itemListWidget);
1094 break;
1095 }
1096
1097 case KItemListViewAnimation::CreateAnimation:
1098 case KItemListViewAnimation::MovingAnimation:
1099 case KItemListViewAnimation::ResizeAnimation: {
1100 const int index = itemListWidget->index();
1101 const bool invisible = (index < m_layouter->firstVisibleIndex()) ||
1102 (index > m_layouter->lastVisibleIndex());
1103 if (invisible && !m_animation->isStarted(itemListWidget)) {
1104 recycleWidget(itemListWidget);
1105 }
1106 break;
1107 }
1108
1109 default: break;
1110 }
1111 }
1112
1113 void KItemListView::slotLayoutTimerFinished()
1114 {
1115 m_layouter->setSize(geometry().size());
1116 doLayout(Animation);
1117 }
1118
1119 void KItemListView::slotRubberBandPosChanged()
1120 {
1121 update();
1122 }
1123
1124 void KItemListView::slotRubberBandActivationChanged(bool active)
1125 {
1126 if (active) {
1127 connect(m_rubberBand, SIGNAL(startPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1128 connect(m_rubberBand, SIGNAL(endPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1129 m_skipAutoScrollForRubberBand = true;
1130 } else {
1131 disconnect(m_rubberBand, SIGNAL(startPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1132 disconnect(m_rubberBand, SIGNAL(endPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1133 m_skipAutoScrollForRubberBand = false;
1134 }
1135
1136 update();
1137 }
1138
1139 void KItemListView::slotVisibleRoleWidthChanged(const QByteArray& role,
1140 qreal currentWidth,
1141 qreal previousWidth)
1142 {
1143 Q_UNUSED(previousWidth);
1144
1145 m_useHeaderWidths = true;
1146
1147 if (m_visibleRolesSizes.contains(role)) {
1148 QSizeF roleSize = m_visibleRolesSizes.value(role);
1149 roleSize.setWidth(currentWidth);
1150 m_visibleRolesSizes.insert(role, roleSize);
1151 m_stretchedVisibleRolesSizes.insert(role, roleSize);
1152
1153 // Apply the new size to the layouter
1154 QSizeF dynamicItemSize = m_itemSize;
1155 if (dynamicItemSize.width() < 0) {
1156 const qreal requiredWidth = visibleRolesSizesWidthSum();
1157 dynamicItemSize.setWidth(qMax(size().width(), requiredWidth));
1158 }
1159 if (dynamicItemSize.height() < 0) {
1160 const qreal requiredHeight = visibleRolesSizesHeightSum();
1161 dynamicItemSize.setHeight(qMax(size().height(), requiredHeight));
1162 }
1163
1164 m_layouter->setItemSize(dynamicItemSize);
1165
1166 // Update the role sizes for all visible widgets
1167 foreach (KItemListWidget* widget, visibleItemListWidgets()) {
1168 widget->setVisibleRolesSizes(m_stretchedVisibleRolesSizes);
1169 }
1170
1171 doLayout(NoAnimation);
1172 }
1173 }
1174
1175 void KItemListView::triggerAutoScrolling()
1176 {
1177 if (!m_autoScrollTimer) {
1178 return;
1179 }
1180
1181 int pos = 0;
1182 int visibleSize = 0;
1183 if (scrollOrientation() == Qt::Vertical) {
1184 pos = m_mousePos.y();
1185 visibleSize = size().height();
1186 } else {
1187 pos = m_mousePos.x();
1188 visibleSize = size().width();
1189 }
1190
1191 if (m_autoScrollTimer->interval() == InitialAutoScrollDelay) {
1192 m_autoScrollIncrement = 0;
1193 }
1194
1195 m_autoScrollIncrement = calculateAutoScrollingIncrement(pos, visibleSize, m_autoScrollIncrement);
1196 if (m_autoScrollIncrement == 0) {
1197 // The mouse position is not above an autoscroll margin (the autoscroll timer
1198 // will be restarted in mouseMoveEvent())
1199 m_autoScrollTimer->stop();
1200 return;
1201 }
1202
1203 if (m_rubberBand->isActive() && m_skipAutoScrollForRubberBand) {
1204 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1205 // if the direction of the rubberband is similar to the autoscroll direction. This
1206 // prevents that starting to create a rubberband within the autoscroll margins starts
1207 // an autoscrolling.
1208
1209 const qreal minDiff = 4; // Ignore any autoscrolling if the rubberband is very small
1210 const qreal diff = (scrollOrientation() == Qt::Vertical)
1211 ? m_rubberBand->endPosition().y() - m_rubberBand->startPosition().y()
1212 : m_rubberBand->endPosition().x() - m_rubberBand->startPosition().x();
1213 if (qAbs(diff) < minDiff || (m_autoScrollIncrement < 0 && diff > 0) || (m_autoScrollIncrement > 0 && diff < 0)) {
1214 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1215 // been moved up although the autoscroll direction might be down)
1216 m_autoScrollTimer->stop();
1217 return;
1218 }
1219 }
1220
1221 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1222 // the autoscrolling may not get skipped anymore until a new rubberband is created
1223 m_skipAutoScrollForRubberBand = false;
1224
1225 const qreal maxVisibleOffset = qMax(qreal(0), maximumScrollOffset() - visibleSize);
1226 const qreal newScrollOffset = qMin(scrollOffset() + m_autoScrollIncrement, maxVisibleOffset);
1227 setScrollOffset(newScrollOffset);
1228
1229 // Trigger the autoscroll timer which will periodically call
1230 // triggerAutoScrolling()
1231 m_autoScrollTimer->start(RepeatingAutoScrollDelay);
1232 }
1233
1234 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1235 {
1236 KItemListWidget* widget = qobject_cast<KItemListWidget*>(sender());
1237 Q_ASSERT(widget);
1238 KItemListGroupHeader* groupHeader = m_visibleGroups.value(widget);
1239 Q_ASSERT(groupHeader);
1240 updateGroupHeaderLayout(widget);
1241 }
1242
1243 void KItemListView::setController(KItemListController* controller)
1244 {
1245 if (m_controller != controller) {
1246 KItemListController* previous = m_controller;
1247 if (previous) {
1248 KItemListSelectionManager* selectionManager = previous->selectionManager();
1249 disconnect(selectionManager, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1250 disconnect(selectionManager, SIGNAL(selectionChanged(QSet<int>,QSet<int>)), this, SLOT(slotSelectionChanged(QSet<int>,QSet<int>)));
1251 }
1252
1253 m_controller = controller;
1254
1255 if (controller) {
1256 KItemListSelectionManager* selectionManager = controller->selectionManager();
1257 connect(selectionManager, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1258 connect(selectionManager, SIGNAL(selectionChanged(QSet<int>,QSet<int>)), this, SLOT(slotSelectionChanged(QSet<int>,QSet<int>)));
1259 }
1260
1261 onControllerChanged(controller, previous);
1262 }
1263 }
1264
1265 void KItemListView::setModel(KItemModelBase* model)
1266 {
1267 if (m_model == model) {
1268 return;
1269 }
1270
1271 KItemModelBase* previous = m_model;
1272
1273 if (m_model) {
1274 disconnect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
1275 this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
1276 disconnect(m_model, SIGNAL(itemsInserted(KItemRangeList)),
1277 this, SLOT(slotItemsInserted(KItemRangeList)));
1278 disconnect(m_model, SIGNAL(itemsRemoved(KItemRangeList)),
1279 this, SLOT(slotItemsRemoved(KItemRangeList)));
1280 disconnect(m_model, SIGNAL(itemsMoved(KItemRange,QList<int>)),
1281 this, SLOT(slotItemsMoved(KItemRange,QList<int>)));
1282 disconnect(m_model, SIGNAL(groupedSortingChanged(bool)),
1283 this, SLOT(slotGroupedSortingChanged(bool)));
1284 disconnect(m_model, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)),
1285 this, SLOT(slotSortOrderChanged(Qt::SortOrder,Qt::SortOrder)));
1286 disconnect(m_model, SIGNAL(sortRoleChanged(QByteArray,QByteArray)),
1287 this, SLOT(slotSortRoleChanged(QByteArray,QByteArray)));
1288 }
1289
1290 m_model = model;
1291 m_layouter->setModel(model);
1292 m_grouped = model->groupedSorting();
1293
1294 if (m_model) {
1295 connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
1296 this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
1297 connect(m_model, SIGNAL(itemsInserted(KItemRangeList)),
1298 this, SLOT(slotItemsInserted(KItemRangeList)));
1299 connect(m_model, SIGNAL(itemsRemoved(KItemRangeList)),
1300 this, SLOT(slotItemsRemoved(KItemRangeList)));
1301 connect(m_model, SIGNAL(itemsMoved(KItemRange,QList<int>)),
1302 this, SLOT(slotItemsMoved(KItemRange,QList<int>)));
1303 connect(m_model, SIGNAL(groupedSortingChanged(bool)),
1304 this, SLOT(slotGroupedSortingChanged(bool)));
1305 connect(m_model, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)),
1306 this, SLOT(slotSortOrderChanged(Qt::SortOrder,Qt::SortOrder)));
1307 connect(m_model, SIGNAL(sortRoleChanged(QByteArray,QByteArray)),
1308 this, SLOT(slotSortRoleChanged(QByteArray,QByteArray)));
1309 }
1310
1311 onModelChanged(model, previous);
1312 }
1313
1314 KItemListRubberBand* KItemListView::rubberBand() const
1315 {
1316 return m_rubberBand;
1317 }
1318
1319 void KItemListView::doLayout(LayoutAnimationHint hint, int changedIndex, int changedCount)
1320 {
1321 if (m_layoutTimer->isActive()) {
1322 m_layoutTimer->stop();
1323 }
1324
1325 if (m_activeTransactions > 0) {
1326 if (hint == NoAnimation) {
1327 // As soon as at least one property change should be done without animation,
1328 // the whole transaction will be marked as not animated.
1329 m_endTransactionAnimationHint = NoAnimation;
1330 }
1331 return;
1332 }
1333
1334 if (!m_model || m_model->count() < 0) {
1335 return;
1336 }
1337
1338 int firstVisibleIndex = m_layouter->firstVisibleIndex();
1339 if (firstVisibleIndex < 0) {
1340 emitOffsetChanges();
1341 return;
1342 }
1343
1344 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1345 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1346 // is still shown if the maximum offset got decreased.
1347 const qreal visibleOffsetRange = (scrollOrientation() == Qt::Horizontal) ? size().width() : size().height();
1348 const qreal maxOffsetToShowFullRange = maximumScrollOffset() - visibleOffsetRange;
1349 if (scrollOffset() > maxOffsetToShowFullRange) {
1350 m_layouter->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange));
1351 firstVisibleIndex = m_layouter->firstVisibleIndex();
1352 }
1353
1354 const int lastVisibleIndex = m_layouter->lastVisibleIndex();
1355
1356 int firstSibblingIndex = -1;
1357 int lastSibblingIndex = -1;
1358 const bool supportsExpanding = supportsItemExpanding();
1359
1360 QList<int> reusableItems = recycleInvisibleItems(firstVisibleIndex, lastVisibleIndex, hint);
1361
1362 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1363 // instances from invisible items are reused. If no reusable items are
1364 // found then new KItemListWidget instances get created.
1365 const bool animate = (hint == Animation);
1366 for (int i = firstVisibleIndex; i <= lastVisibleIndex; ++i) {
1367 bool applyNewPos = true;
1368 bool wasHidden = false;
1369
1370 const QRectF itemBounds = m_layouter->itemRect(i);
1371 const QPointF newPos = itemBounds.topLeft();
1372 KItemListWidget* widget = m_visibleItems.value(i);
1373 if (!widget) {
1374 wasHidden = true;
1375 if (!reusableItems.isEmpty()) {
1376 // Reuse a KItemListWidget instance from an invisible item
1377 const int oldIndex = reusableItems.takeLast();
1378 widget = m_visibleItems.value(oldIndex);
1379 setWidgetIndex(widget, i);
1380
1381 if (m_grouped) {
1382 updateGroupHeaderForWidget(widget);
1383 }
1384 } else {
1385 // No reusable KItemListWidget instance is available, create a new one
1386 widget = createWidget(i);
1387 }
1388 widget->resize(itemBounds.size());
1389
1390 if (animate && changedCount < 0) {
1391 // Items have been deleted, move the created item to the
1392 // imaginary old position. They will get animated to the new position
1393 // later.
1394 const QRectF itemRect = m_layouter->itemRect(i - changedCount);
1395 if (itemRect.isEmpty()) {
1396 const QPointF invisibleOldPos = (scrollOrientation() == Qt::Vertical)
1397 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1398 widget->setPos(invisibleOldPos);
1399 } else {
1400 widget->setPos(itemRect.topLeft());
1401 }
1402 applyNewPos = false;
1403 }
1404
1405 if (supportsExpanding && changedCount == 0) {
1406 if (firstSibblingIndex < 0) {
1407 firstSibblingIndex = i;
1408 }
1409 lastSibblingIndex = i;
1410 }
1411 }
1412
1413 if (animate) {
1414 const bool itemsRemoved = (changedCount < 0);
1415 const bool itemsInserted = (changedCount > 0);
1416 if (itemsRemoved && (i >= changedIndex + changedCount + 1)) {
1417 // The item is located after the removed items. Animate the moving of the position.
1418 applyNewPos = !moveWidget(widget, itemBounds);
1419 } else if (itemsInserted && i >= changedIndex) {
1420 // The item is located after the first inserted item
1421 if (i <= changedIndex + changedCount - 1) {
1422 // The item is an inserted item. Animate the appearing of the item.
1423 // For performance reasons no animation is done when changedCount is equal
1424 // to all available items.
1425 if (changedCount < m_model->count()) {
1426 m_animation->start(widget, KItemListViewAnimation::CreateAnimation);
1427 }
1428 } else if (!m_animation->isStarted(widget, KItemListViewAnimation::CreateAnimation)) {
1429 // The item was already there before, so animate the moving of the position.
1430 // No moving animation is done if the item is animated by a create animation: This
1431 // prevents a "move animation mess" when inserting several ranges in parallel.
1432 applyNewPos = !moveWidget(widget, itemBounds);
1433 }
1434 } else if (!itemsRemoved && !itemsInserted && !wasHidden) {
1435 // The size of the view might have been changed. Animate the moving of the position.
1436 applyNewPos = !moveWidget(widget, itemBounds);
1437 }
1438 } else {
1439 m_animation->stop(widget);
1440 }
1441
1442 if (applyNewPos) {
1443 widget->setPos(newPos);
1444 }
1445
1446 Q_ASSERT(widget->index() == i);
1447 widget->setVisible(true);
1448
1449 if (widget->size() != itemBounds.size()) {
1450 // Resize the widget for the item to the changed size.
1451 if (animate) {
1452 // If a dynamic item size is used then no animation is done in the direction
1453 // of the dynamic size.
1454 if (m_itemSize.width() <= 0) {
1455 // The width is dynamic, apply the new width without animation.
1456 widget->resize(itemBounds.width(), widget->size().height());
1457 } else if (m_itemSize.height() <= 0) {
1458 // The height is dynamic, apply the new height without animation.
1459 widget->resize(widget->size().width(), itemBounds.height());
1460 }
1461 m_animation->start(widget, KItemListViewAnimation::ResizeAnimation, itemBounds.size());
1462 } else {
1463 widget->resize(itemBounds.size());
1464 }
1465 }
1466 }
1467
1468 // Delete invisible KItemListWidget instances that have not been reused
1469 foreach (int index, reusableItems) {
1470 recycleWidget(m_visibleItems.value(index));
1471 }
1472
1473 if (supportsExpanding && firstSibblingIndex >= 0) {
1474 Q_ASSERT(lastSibblingIndex >= 0);
1475 updateSiblingsInformation(firstSibblingIndex, lastSibblingIndex);
1476 }
1477
1478 if (m_grouped) {
1479 // Update the layout of all visible group headers
1480 QHashIterator<KItemListWidget*, KItemListGroupHeader*> it(m_visibleGroups);
1481 while (it.hasNext()) {
1482 it.next();
1483 updateGroupHeaderLayout(it.key());
1484 }
1485 }
1486
1487 emitOffsetChanges();
1488 }
1489
1490 QList<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex,
1491 int lastVisibleIndex,
1492 LayoutAnimationHint hint)
1493 {
1494 // Determine all items that are completely invisible and might be
1495 // reused for items that just got (at least partly) visible. If the
1496 // animation hint is set to 'Animation' items that do e.g. an animated
1497 // moving of their position are not marked as invisible: This assures
1498 // that a scrolling inside the view can be done without breaking an animation.
1499
1500 QList<int> items;
1501
1502 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
1503 while (it.hasNext()) {
1504 it.next();
1505
1506 KItemListWidget* widget = it.value();
1507 const int index = widget->index();
1508 const bool invisible = (index < firstVisibleIndex) || (index > lastVisibleIndex);
1509
1510 if (invisible) {
1511 if (m_animation->isStarted(widget)) {
1512 if (hint == NoAnimation) {
1513 // Stopping the animation will call KItemListView::slotAnimationFinished()
1514 // and the widget will be recycled if necessary there.
1515 m_animation->stop(widget);
1516 }
1517 } else {
1518 widget->setVisible(false);
1519 items.append(index);
1520
1521 if (m_grouped) {
1522 recycleGroupHeaderForWidget(widget);
1523 }
1524 }
1525 }
1526 }
1527
1528 return items;
1529 }
1530
1531 bool KItemListView::moveWidget(KItemListWidget* widget,const QRectF& itemBounds)
1532 {
1533 const QPointF oldPos = widget->pos();
1534 const QPointF newPos = itemBounds.topLeft();
1535 if (oldPos == newPos) {
1536 return false;
1537 }
1538
1539 bool startMovingAnim = m_itemSize.isEmpty() || widget->size() != itemBounds.size();
1540 if (!startMovingAnim) {
1541 // When having a grid the moving-animation should only be started, if it is done within
1542 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1543 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1544 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1545 const QSizeF itemMargin = m_layouter->itemMargin();
1546 const qreal xMax = m_itemSize.width() + itemMargin.width();
1547 const qreal yMax = m_itemSize.height() + itemMargin.height();
1548 qreal xDiff = qAbs(oldPos.x() - newPos.x());
1549 qreal yDiff = qAbs(oldPos.y() - newPos.y());
1550 if (scrollOrientation() == Qt::Vertical) {
1551 startMovingAnim = (xDiff > yDiff && yDiff < yMax);
1552 } else {
1553 startMovingAnim = (yDiff > xDiff && xDiff < xMax);
1554 }
1555 }
1556
1557 if (startMovingAnim) {
1558 m_animation->start(widget, KItemListViewAnimation::MovingAnimation, newPos);
1559 return true;
1560 }
1561
1562 m_animation->stop(widget);
1563 m_animation->start(widget, KItemListViewAnimation::CreateAnimation);
1564 return false;
1565 }
1566
1567 void KItemListView::emitOffsetChanges()
1568 {
1569 const qreal newScrollOffset = m_layouter->scrollOffset();
1570 if (m_oldScrollOffset != newScrollOffset) {
1571 emit scrollOffsetChanged(newScrollOffset, m_oldScrollOffset);
1572 m_oldScrollOffset = newScrollOffset;
1573 }
1574
1575 const qreal newMaximumScrollOffset = m_layouter->maximumScrollOffset();
1576 if (m_oldMaximumScrollOffset != newMaximumScrollOffset) {
1577 emit maximumScrollOffsetChanged(newMaximumScrollOffset, m_oldMaximumScrollOffset);
1578 m_oldMaximumScrollOffset = newMaximumScrollOffset;
1579 }
1580
1581 const qreal newItemOffset = m_layouter->itemOffset();
1582 if (m_oldItemOffset != newItemOffset) {
1583 emit itemOffsetChanged(newItemOffset, m_oldItemOffset);
1584 m_oldItemOffset = newItemOffset;
1585 }
1586
1587 const qreal newMaximumItemOffset = m_layouter->maximumItemOffset();
1588 if (m_oldMaximumItemOffset != newMaximumItemOffset) {
1589 emit maximumItemOffsetChanged(newMaximumItemOffset, m_oldMaximumItemOffset);
1590 m_oldMaximumItemOffset = newMaximumItemOffset;
1591 }
1592 }
1593
1594 KItemListWidget* KItemListView::createWidget(int index)
1595 {
1596 KItemListWidget* widget = m_widgetCreator->create(this);
1597 widget->setFlag(QGraphicsItem::ItemStacksBehindParent);
1598
1599 updateWidgetProperties(widget, index);
1600 m_visibleItems.insert(index, widget);
1601
1602 if (m_grouped) {
1603 updateGroupHeaderForWidget(widget);
1604 }
1605
1606 initializeItemListWidget(widget);
1607 return widget;
1608 }
1609
1610 void KItemListView::recycleWidget(KItemListWidget* widget)
1611 {
1612 if (m_grouped) {
1613 recycleGroupHeaderForWidget(widget);
1614 }
1615
1616 m_visibleItems.remove(widget->index());
1617 m_widgetCreator->recycle(widget);
1618 }
1619
1620 void KItemListView::setWidgetIndex(KItemListWidget* widget, int index)
1621 {
1622 const int oldIndex = widget->index();
1623 m_visibleItems.remove(oldIndex);
1624 updateWidgetProperties(widget, index);
1625 m_visibleItems.insert(index, widget);
1626
1627 initializeItemListWidget(widget);
1628 }
1629
1630 void KItemListView::setLayouterSize(const QSizeF& size, SizeType sizeType)
1631 {
1632 switch (sizeType) {
1633 case LayouterSize: m_layouter->setSize(size); break;
1634 case ItemSize: m_layouter->setItemSize(size); break;
1635 default: break;
1636 }
1637 }
1638
1639 void KItemListView::updateWidgetProperties(KItemListWidget* widget, int index)
1640 {
1641 widget->setVisibleRoles(m_visibleRoles);
1642 widget->setVisibleRolesSizes(m_stretchedVisibleRolesSizes);
1643 widget->setStyleOption(m_styleOption);
1644
1645 const KItemListSelectionManager* selectionManager = m_controller->selectionManager();
1646 widget->setCurrent(index == selectionManager->currentItem());
1647 widget->setSelected(selectionManager->isSelected(index));
1648 widget->setHovered(false);
1649 widget->setAlternatingBackgroundColors(false);
1650 widget->setEnabledSelectionToggle(enabledSelectionToggles());
1651 widget->setIndex(index);
1652 widget->setData(m_model->data(index));
1653 widget->setSiblingsInformation(QBitArray());
1654 }
1655
1656 void KItemListView::updateGroupHeaderForWidget(KItemListWidget* widget)
1657 {
1658 Q_ASSERT(m_grouped);
1659
1660 const int index = widget->index();
1661 if (!m_layouter->isFirstGroupItem(index)) {
1662 // The widget does not represent the first item of a group
1663 // and hence requires no header
1664 recycleGroupHeaderForWidget(widget);
1665 return;
1666 }
1667
1668 const QList<QPair<int, QVariant> > groups = model()->groups();
1669 if (groups.isEmpty()) {
1670 return;
1671 }
1672
1673 KItemListGroupHeader* groupHeader = m_visibleGroups.value(widget);
1674 if (!groupHeader) {
1675 groupHeader = m_groupHeaderCreator->create(this);
1676 groupHeader->setParentItem(widget);
1677 m_visibleGroups.insert(widget, groupHeader);
1678 connect(widget, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1679 }
1680 Q_ASSERT(groupHeader->parentItem() == widget);
1681
1682 // Determine the shown data for the header by doing a binary
1683 // search in the groups-list
1684 int min = 0;
1685 int max = groups.count() - 1;
1686 int mid = 0;
1687 do {
1688 mid = (min + max) / 2;
1689 if (index > groups.at(mid).first) {
1690 min = mid + 1;
1691 } else {
1692 max = mid - 1;
1693 }
1694 } while (groups.at(mid).first != index && min <= max);
1695
1696 groupHeader->setData(groups.at(mid).second);
1697 groupHeader->setRole(model()->sortRole());
1698 groupHeader->setStyleOption(m_styleOption);
1699 groupHeader->setScrollOrientation(scrollOrientation());
1700 groupHeader->setItemIndex(index);
1701
1702 groupHeader->show();
1703 }
1704
1705 void KItemListView::updateGroupHeaderLayout(KItemListWidget* widget)
1706 {
1707 KItemListGroupHeader* groupHeader = m_visibleGroups.value(widget);
1708 Q_ASSERT(groupHeader);
1709
1710 const int index = widget->index();
1711 const QRectF groupHeaderRect = m_layouter->groupHeaderRect(index);
1712 const QRectF itemRect = m_layouter->itemRect(index);
1713
1714 // The group-header is a child of the itemlist widget. Translate the
1715 // group header position to the relative position.
1716 if (scrollOrientation() == Qt::Vertical) {
1717 // In the vertical scroll orientation the group header should always span
1718 // the whole width no matter which temporary position the parent widget
1719 // has. In this case the x-position and width will be adjusted manually.
1720 groupHeader->setPos(-widget->x(), -groupHeaderRect.height());
1721 groupHeader->resize(size().width(), groupHeaderRect.size().height());
1722 } else {
1723 groupHeader->setPos(groupHeaderRect.x() - itemRect.x(), -widget->y());
1724 groupHeader->resize(groupHeaderRect.size());
1725 }
1726 }
1727
1728 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget* widget)
1729 {
1730 KItemListGroupHeader* header = m_visibleGroups.value(widget);
1731 if (header) {
1732 header->setParentItem(0);
1733 m_groupHeaderCreator->recycle(header);
1734 m_visibleGroups.remove(widget);
1735 disconnect(widget, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1736 }
1737 }
1738
1739 void KItemListView::updateVisibleGroupHeaders()
1740 {
1741 Q_ASSERT(m_grouped);
1742 m_layouter->markAsDirty();
1743
1744 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
1745 while (it.hasNext()) {
1746 it.next();
1747 updateGroupHeaderForWidget(it.value());
1748 }
1749 }
1750
1751 QHash<QByteArray, qreal> KItemListView::headerRolesWidths() const
1752 {
1753 QHash<QByteArray, qreal> rolesWidths;
1754
1755 QHashIterator<QByteArray, QSizeF> it(m_stretchedVisibleRolesSizes);
1756 while (it.hasNext()) {
1757 it.next();
1758 rolesWidths.insert(it.key(), it.value().width());
1759 }
1760
1761 return rolesWidths;
1762 }
1763
1764 void KItemListView::updateVisibleRolesSizes(const KItemRangeList& itemRanges)
1765 {
1766 if (!m_itemSize.isEmpty() || m_useHeaderWidths) {
1767 return;
1768 }
1769
1770 const int itemCount = m_model->count();
1771 int rangesItemCount = 0;
1772 foreach (const KItemRange& range, itemRanges) {
1773 rangesItemCount += range.count;
1774 }
1775
1776 if (itemCount == rangesItemCount) {
1777 m_visibleRolesSizes = visibleRolesSizes(itemRanges);
1778 if (m_header) {
1779 // Assure the the sizes are not smaller than the minimum defined by the header
1780 // TODO: Currently only implemented for a top-aligned header
1781 const qreal minHeaderRoleWidth = m_header->minimumRoleWidth();
1782 QMutableHashIterator<QByteArray, QSizeF> it (m_visibleRolesSizes);
1783 while (it.hasNext()) {
1784 it.next();
1785 const QSizeF& size = it.value();
1786 if (size.width() < minHeaderRoleWidth) {
1787 const QSizeF newSize(minHeaderRoleWidth, size.height());
1788 m_visibleRolesSizes.insert(it.key(), newSize);
1789 }
1790 }
1791 }
1792 } else {
1793 // Only a sub range of the roles need to be determined.
1794 // The chances are good that the sizes of the sub ranges
1795 // already fit into the available sizes and hence no
1796 // expensive update might be required.
1797 bool updateRequired = false;
1798
1799 const QHash<QByteArray, QSizeF> updatedSizes = visibleRolesSizes(itemRanges);
1800 QHashIterator<QByteArray, QSizeF> it(updatedSizes);
1801 while (it.hasNext()) {
1802 it.next();
1803 const QByteArray& role = it.key();
1804 const QSizeF& updatedSize = it.value();
1805 const QSizeF currentSize = m_visibleRolesSizes.value(role);
1806 if (updatedSize.width() > currentSize.width() || updatedSize.height() > currentSize.height()) {
1807 m_visibleRolesSizes.insert(role, updatedSize);
1808 updateRequired = true;
1809 }
1810 }
1811
1812 if (!updateRequired) {
1813 // All the updated sizes are smaller than the current sizes and no change
1814 // of the stretched roles-widths is required
1815 return;
1816 }
1817 }
1818
1819 updateStretchedVisibleRolesSizes();
1820 }
1821
1822 void KItemListView::updateVisibleRolesSizes()
1823 {
1824 if (!m_model) {
1825 return;
1826 }
1827
1828 const int itemCount = m_model->count();
1829 if (itemCount > 0) {
1830 updateVisibleRolesSizes(KItemRangeList() << KItemRange(0, itemCount));
1831 }
1832 }
1833
1834 void KItemListView::updateStretchedVisibleRolesSizes()
1835 {
1836 if (!m_itemSize.isEmpty() || m_useHeaderWidths || m_visibleRoles.isEmpty()) {
1837 return;
1838 }
1839
1840 // Calculate the maximum size of an item by considering the
1841 // visible role sizes and apply them to the layouter. If the
1842 // size does not use the available view-size it the size of the
1843 // first role will get stretched.
1844 m_stretchedVisibleRolesSizes = m_visibleRolesSizes;
1845 const QByteArray role = m_visibleRoles.first();
1846 QSizeF firstRoleSize = m_stretchedVisibleRolesSizes.value(role);
1847
1848 QSizeF dynamicItemSize = m_itemSize;
1849
1850 if (dynamicItemSize.width() <= 0) {
1851 const qreal requiredWidth = visibleRolesSizesWidthSum();
1852 const qreal availableWidth = size().width();
1853 if (requiredWidth < availableWidth) {
1854 // Stretch the first role to use the whole width for the item
1855 firstRoleSize.rwidth() += availableWidth - requiredWidth;
1856 m_stretchedVisibleRolesSizes.insert(role, firstRoleSize);
1857 }
1858 dynamicItemSize.setWidth(qMax(requiredWidth, availableWidth));
1859 }
1860
1861 if (dynamicItemSize.height() <= 0) {
1862 const qreal requiredHeight = visibleRolesSizesHeightSum();
1863 const qreal availableHeight = size().height();
1864 if (requiredHeight < availableHeight) {
1865 // Stretch the first role to use the whole height for the item
1866 firstRoleSize.rheight() += availableHeight - requiredHeight;
1867 m_stretchedVisibleRolesSizes.insert(role, firstRoleSize);
1868 }
1869 dynamicItemSize.setHeight(qMax(requiredHeight, availableHeight));
1870 }
1871
1872 m_layouter->setItemSize(dynamicItemSize);
1873
1874 if (m_header) {
1875 m_header->setVisibleRolesWidths(headerRolesWidths());
1876 m_header->resize(dynamicItemSize.width(), m_header->size().height());
1877 }
1878
1879 // Update the role sizes for all visible widgets
1880 foreach (KItemListWidget* widget, visibleItemListWidgets()) {
1881 widget->setVisibleRolesSizes(m_stretchedVisibleRolesSizes);
1882 }
1883 }
1884
1885 qreal KItemListView::visibleRolesSizesWidthSum() const
1886 {
1887 qreal widthSum = 0;
1888 QHashIterator<QByteArray, QSizeF> it(m_visibleRolesSizes);
1889 while (it.hasNext()) {
1890 it.next();
1891 widthSum += it.value().width();
1892 }
1893 return widthSum;
1894 }
1895
1896 qreal KItemListView::visibleRolesSizesHeightSum() const
1897 {
1898 qreal heightSum = 0;
1899 QHashIterator<QByteArray, QSizeF> it(m_visibleRolesSizes);
1900 while (it.hasNext()) {
1901 it.next();
1902 heightSum += it.value().height();
1903 }
1904 return heightSum;
1905 }
1906
1907 QRectF KItemListView::headerBoundaries() const
1908 {
1909 return m_header ? m_header->geometry() : QRectF();
1910 }
1911
1912 bool KItemListView::changesItemGridLayout(const QSizeF& newGridSize,
1913 const QSizeF& newItemSize,
1914 const QSizeF& newItemMargin) const
1915 {
1916 if (newItemSize.isEmpty() || newGridSize.isEmpty()) {
1917 return false;
1918 }
1919
1920 if (m_layouter->scrollOrientation() == Qt::Vertical) {
1921 const qreal itemWidth = m_layouter->itemSize().width();
1922 if (itemWidth > 0) {
1923 const int newColumnCount = itemsPerSize(newGridSize.width(),
1924 newItemSize.width(),
1925 newItemMargin.width());
1926 if (m_model->count() > newColumnCount) {
1927 const int oldColumnCount = itemsPerSize(m_layouter->size().width(),
1928 itemWidth,
1929 m_layouter->itemMargin().width());
1930 return oldColumnCount != newColumnCount;
1931 }
1932 }
1933 } else {
1934 const qreal itemHeight = m_layouter->itemSize().height();
1935 if (itemHeight > 0) {
1936 const int newRowCount = itemsPerSize(newGridSize.height(),
1937 newItemSize.height(),
1938 newItemMargin.height());
1939 if (m_model->count() > newRowCount) {
1940 const int oldRowCount = itemsPerSize(m_layouter->size().height(),
1941 itemHeight,
1942 m_layouter->itemMargin().height());
1943 return oldRowCount != newRowCount;
1944 }
1945 }
1946 }
1947
1948 return false;
1949 }
1950
1951 bool KItemListView::animateChangedItemCount(int changedItemCount) const
1952 {
1953 if (m_layouter->size().isEmpty() || m_layouter->itemSize().isEmpty()) {
1954 return false;
1955 }
1956
1957 const int maximum = (scrollOrientation() == Qt::Vertical)
1958 ? m_layouter->size().width() / m_layouter->itemSize().width()
1959 : m_layouter->size().height() / m_layouter->itemSize().height();
1960 // Only animate if up to 2/3 of a row or column are inserted or removed
1961 return changedItemCount <= maximum * 2 / 3;
1962 }
1963
1964
1965 bool KItemListView::scrollBarRequired(const QSizeF& size) const
1966 {
1967 const QSizeF oldSize = m_layouter->size();
1968
1969 m_layouter->setSize(size);
1970 const qreal maxOffset = m_layouter->maximumScrollOffset();
1971 m_layouter->setSize(oldSize);
1972
1973 return m_layouter->scrollOrientation() == Qt::Vertical ? maxOffset > size.height()
1974 : maxOffset > size.width();
1975 }
1976
1977 void KItemListView::updateGroupHeaderHeight()
1978 {
1979 qreal groupHeaderHeight = m_styleOption.fontMetrics.height();
1980 qreal groupHeaderMargin = 0;
1981
1982 if (scrollOrientation() == Qt::Horizontal) {
1983 // The vertical margin above and below the header should be
1984 // equal to the horizontal margin, not the vertical margin
1985 // from m_styleOption.
1986 groupHeaderHeight += 2 * m_styleOption.horizontalMargin;
1987 groupHeaderMargin = m_styleOption.horizontalMargin;
1988 } else if (m_itemSize.isEmpty()){
1989 groupHeaderHeight += 2 * m_styleOption.padding;
1990 groupHeaderMargin = m_styleOption.iconSize / 2;
1991 } else {
1992 groupHeaderHeight += 2 * m_styleOption.padding;
1993 groupHeaderMargin = m_styleOption.iconSize / 4;
1994 }
1995 m_layouter->setGroupHeaderHeight(groupHeaderHeight);
1996 m_layouter->setGroupHeaderMargin(groupHeaderMargin);
1997
1998 updateVisibleGroupHeaders();
1999 }
2000
2001 void KItemListView::updateSiblingsInformation(int firstIndex, int lastIndex)
2002 {
2003 if (!supportsItemExpanding()) {
2004 return;
2005 }
2006
2007 if (firstIndex < 0 || lastIndex < 0) {
2008 firstIndex = m_layouter->firstVisibleIndex();
2009 lastIndex = m_layouter->lastVisibleIndex();
2010 } else {
2011 const bool isRangeVisible = (firstIndex <= m_layouter->lastVisibleIndex() &&
2012 lastIndex >= m_layouter->firstVisibleIndex());
2013 if (!isRangeVisible) {
2014 return;
2015 }
2016 }
2017
2018 int previousParents = 0;
2019 QBitArray previousSiblings;
2020
2021 // The rootIndex describes the first index where the siblings get
2022 // calculated from. For the calculation the upper most parent item
2023 // is required. For performance reasons it is checked first whether
2024 // the visible items before or after the current range already
2025 // contain a siblings information which can be used as base.
2026 int rootIndex = firstIndex;
2027
2028 KItemListWidget* widget = m_visibleItems.value(firstIndex - 1);
2029 if (!widget) {
2030 // There is no visible widget before the range, check whether there
2031 // is one after the range:
2032 widget = m_visibleItems.value(lastIndex + 1);
2033 if (widget) {
2034 // The sibling information of the widget may only be used if
2035 // all items of the range have the same number of parents.
2036 const int parents = m_model->expandedParentsCount(lastIndex + 1);
2037 for (int i = lastIndex; i >= firstIndex; --i) {
2038 if (m_model->expandedParentsCount(i) != parents) {
2039 widget = 0;
2040 break;
2041 }
2042 }
2043 }
2044 }
2045
2046 if (widget) {
2047 // Performance optimization: Use the sibling information of the visible
2048 // widget beside the given range.
2049 previousSiblings = widget->siblingsInformation();
2050 if (previousSiblings.isEmpty()) {
2051 return;
2052 }
2053 previousParents = previousSiblings.count() - 1;
2054 previousSiblings.truncate(previousParents);
2055 } else {
2056 // Potentially slow path: Go back to the upper most parent of firstIndex
2057 // to be able to calculate the initial value for the siblings.
2058 while (rootIndex > 0 && m_model->expandedParentsCount(rootIndex) > 0) {
2059 --rootIndex;
2060 }
2061 }
2062
2063 Q_ASSERT(previousParents >= 0);
2064 for (int i = rootIndex; i <= lastIndex; ++i) {
2065 // Update the parent-siblings in case if the current item represents
2066 // a child or an upper parent.
2067 const int currentParents = m_model->expandedParentsCount(i);
2068 Q_ASSERT(currentParents >= 0);
2069 if (previousParents < currentParents) {
2070 previousParents = currentParents;
2071 previousSiblings.resize(currentParents);
2072 previousSiblings.setBit(currentParents - 1, hasSiblingSuccessor(i - 1));
2073 } else if (previousParents > currentParents) {
2074 previousParents = currentParents;
2075 previousSiblings.truncate(currentParents);
2076 }
2077
2078 if (i >= firstIndex) {
2079 // The index represents a visible item. Apply the parent-siblings
2080 // and update the sibling of the current item.
2081 KItemListWidget* widget = m_visibleItems.value(i);
2082 if (!widget) {
2083 continue;
2084 }
2085
2086 QBitArray siblings = previousSiblings;
2087 siblings.resize(siblings.count() + 1);
2088 siblings.setBit(siblings.count() - 1, hasSiblingSuccessor(i));
2089
2090 widget->setSiblingsInformation(siblings);
2091 }
2092 }
2093 }
2094
2095 bool KItemListView::hasSiblingSuccessor(int index) const
2096 {
2097 bool hasSuccessor = false;
2098 const int parentsCount = m_model->expandedParentsCount(index);
2099 int successorIndex = index + 1;
2100
2101 // Search the next sibling
2102 const int itemCount = m_model->count();
2103 while (successorIndex < itemCount) {
2104 const int currentParentsCount = m_model->expandedParentsCount(successorIndex);
2105 if (currentParentsCount == parentsCount) {
2106 hasSuccessor = true;
2107 break;
2108 } else if (currentParentsCount < parentsCount) {
2109 break;
2110 }
2111 ++successorIndex;
2112 }
2113
2114 if (m_grouped && hasSuccessor) {
2115 // If the sibling is part of another group, don't mark it as
2116 // successor as the group header is between the sibling connections.
2117 for (int i = index + 1; i <= successorIndex; ++i) {
2118 if (m_layouter->isFirstGroupItem(i)) {
2119 hasSuccessor = false;
2120 break;
2121 }
2122 }
2123 }
2124
2125 return hasSuccessor;
2126 }
2127
2128 int KItemListView::calculateAutoScrollingIncrement(int pos, int range, int oldInc)
2129 {
2130 int inc = 0;
2131
2132 const int minSpeed = 4;
2133 const int maxSpeed = 128;
2134 const int speedLimiter = 96;
2135 const int autoScrollBorder = 64;
2136
2137 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2138 // This assures that the autoscrolling speed grows gradually.
2139 const int incLimiter = 1;
2140
2141 if (pos < autoScrollBorder) {
2142 inc = -minSpeed + qAbs(pos - autoScrollBorder) * (pos - autoScrollBorder) / speedLimiter;
2143 inc = qMax(inc, -maxSpeed);
2144 inc = qMax(inc, oldInc - incLimiter);
2145 } else if (pos > range - autoScrollBorder) {
2146 inc = minSpeed + qAbs(pos - range + autoScrollBorder) * (pos - range + autoScrollBorder) / speedLimiter;
2147 inc = qMin(inc, maxSpeed);
2148 inc = qMin(inc, oldInc + incLimiter);
2149 }
2150
2151 return inc;
2152 }
2153
2154 int KItemListView::itemsPerSize(qreal size, qreal itemSize, qreal itemMargin)
2155 {
2156 const qreal availableSize = size - itemMargin;
2157 const int count = availableSize / (itemSize + itemMargin);
2158 return count;
2159 }
2160
2161
2162
2163 KItemListCreatorBase::~KItemListCreatorBase()
2164 {
2165 qDeleteAll(m_recycleableWidgets);
2166 qDeleteAll(m_createdWidgets);
2167 }
2168
2169 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget* widget)
2170 {
2171 m_createdWidgets.insert(widget);
2172 }
2173
2174 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget* widget)
2175 {
2176 Q_ASSERT(m_createdWidgets.contains(widget));
2177 m_createdWidgets.remove(widget);
2178
2179 if (m_recycleableWidgets.count() < 100) {
2180 m_recycleableWidgets.append(widget);
2181 widget->setVisible(false);
2182 } else {
2183 delete widget;
2184 }
2185 }
2186
2187 QGraphicsWidget* KItemListCreatorBase::popRecycleableWidget()
2188 {
2189 if (m_recycleableWidgets.isEmpty()) {
2190 return 0;
2191 }
2192
2193 QGraphicsWidget* widget = m_recycleableWidgets.takeLast();
2194 m_createdWidgets.insert(widget);
2195 return widget;
2196 }
2197
2198 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2199 {
2200 }
2201
2202 void KItemListWidgetCreatorBase::recycle(KItemListWidget* widget)
2203 {
2204 widget->setParentItem(0);
2205 widget->setOpacity(1.0);
2206 pushRecycleableWidget(widget);
2207 }
2208
2209 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2210 {
2211 }
2212
2213 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader* header)
2214 {
2215 header->setOpacity(1.0);
2216 pushRecycleableWidget(header);
2217 }
2218
2219 #include "kitemlistview.moc"