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