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