]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kitemlistview.cpp
Finetuning of margins and alternate row colors
[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 doLayout(NoAnimation);
1089 }
1090
1091 void KItemListView::slotSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous)
1092 {
1093 Q_UNUSED(current);
1094 Q_UNUSED(previous);
1095 if (m_grouped) {
1096 updateVisibleGroupHeaders();
1097 doLayout(NoAnimation);
1098 }
1099 }
1100
1101 void KItemListView::slotSortRoleChanged(const QByteArray& current, const QByteArray& previous)
1102 {
1103 Q_UNUSED(current);
1104 Q_UNUSED(previous);
1105 if (m_grouped) {
1106 updateVisibleGroupHeaders();
1107 doLayout(NoAnimation);
1108 }
1109 }
1110
1111 void KItemListView::slotCurrentChanged(int current, int previous)
1112 {
1113 Q_UNUSED(previous);
1114
1115 KItemListWidget* previousWidget = m_visibleItems.value(previous, 0);
1116 if (previousWidget) {
1117 previousWidget->setCurrent(false);
1118 }
1119
1120 KItemListWidget* currentWidget = m_visibleItems.value(current, 0);
1121 if (currentWidget) {
1122 currentWidget->setCurrent(true);
1123 }
1124 }
1125
1126 void KItemListView::slotSelectionChanged(const QSet<int>& current, const QSet<int>& previous)
1127 {
1128 Q_UNUSED(previous);
1129
1130 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
1131 while (it.hasNext()) {
1132 it.next();
1133 const int index = it.key();
1134 KItemListWidget* widget = it.value();
1135 widget->setSelected(current.contains(index));
1136 }
1137 }
1138
1139 void KItemListView::slotAnimationFinished(QGraphicsWidget* widget,
1140 KItemListViewAnimation::AnimationType type)
1141 {
1142 KItemListWidget* itemListWidget = qobject_cast<KItemListWidget*>(widget);
1143 Q_ASSERT(itemListWidget);
1144
1145 switch (type) {
1146 case KItemListViewAnimation::DeleteAnimation: {
1147 // As we recycle the widget in this case it is important to assure that no
1148 // other animation has been started. This is a convention in KItemListView and
1149 // not a requirement defined by KItemListViewAnimation.
1150 Q_ASSERT(!m_animation->isStarted(itemListWidget));
1151
1152 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1153 // by m_visibleWidgets and must be deleted manually after the animation has
1154 // been finished.
1155 recycleGroupHeaderForWidget(itemListWidget);
1156 m_widgetCreator->recycle(itemListWidget);
1157 break;
1158 }
1159
1160 case KItemListViewAnimation::CreateAnimation:
1161 case KItemListViewAnimation::MovingAnimation:
1162 case KItemListViewAnimation::ResizeAnimation: {
1163 const int index = itemListWidget->index();
1164 const bool invisible = (index < m_layouter->firstVisibleIndex()) ||
1165 (index > m_layouter->lastVisibleIndex());
1166 if (invisible && !m_animation->isStarted(itemListWidget)) {
1167 recycleWidget(itemListWidget);
1168 }
1169 break;
1170 }
1171
1172 default: break;
1173 }
1174 }
1175
1176 void KItemListView::slotLayoutTimerFinished()
1177 {
1178 m_layouter->setSize(geometry().size());
1179 doLayout(Animation);
1180 }
1181
1182 void KItemListView::slotRubberBandPosChanged()
1183 {
1184 update();
1185 }
1186
1187 void KItemListView::slotRubberBandActivationChanged(bool active)
1188 {
1189 if (active) {
1190 connect(m_rubberBand, SIGNAL(startPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1191 connect(m_rubberBand, SIGNAL(endPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1192 m_skipAutoScrollForRubberBand = true;
1193 } else {
1194 disconnect(m_rubberBand, SIGNAL(startPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1195 disconnect(m_rubberBand, SIGNAL(endPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1196 m_skipAutoScrollForRubberBand = false;
1197 }
1198
1199 update();
1200 }
1201
1202 void KItemListView::slotVisibleRoleWidthChanged(const QByteArray& role,
1203 qreal currentWidth,
1204 qreal previousWidth)
1205 {
1206 Q_UNUSED(previousWidth);
1207
1208 m_useHeaderWidths = true;
1209
1210 if (m_visibleRolesSizes.contains(role)) {
1211 QSizeF roleSize = m_visibleRolesSizes.value(role);
1212 roleSize.setWidth(currentWidth);
1213 m_visibleRolesSizes.insert(role, roleSize);
1214 m_stretchedVisibleRolesSizes.insert(role, roleSize);
1215
1216 // Apply the new size to the layouter
1217 QSizeF dynamicItemSize = m_itemSize;
1218 if (dynamicItemSize.width() < 0) {
1219 const qreal requiredWidth = visibleRolesSizesWidthSum();
1220 dynamicItemSize.setWidth(qMax(size().width(), requiredWidth));
1221 }
1222 if (dynamicItemSize.height() < 0) {
1223 const qreal requiredHeight = visibleRolesSizesHeightSum();
1224 dynamicItemSize.setHeight(qMax(size().height(), requiredHeight));
1225 }
1226
1227 m_layouter->setItemSize(dynamicItemSize);
1228
1229 // Update the role sizes for all visible widgets
1230 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
1231 while (it.hasNext()) {
1232 it.next();
1233 it.value()->setVisibleRolesSizes(m_stretchedVisibleRolesSizes);
1234 }
1235 doLayout(NoAnimation);
1236 }
1237 }
1238
1239 void KItemListView::triggerAutoScrolling()
1240 {
1241 if (!m_autoScrollTimer) {
1242 return;
1243 }
1244
1245 int pos = 0;
1246 int visibleSize = 0;
1247 if (scrollOrientation() == Qt::Vertical) {
1248 pos = m_mousePos.y();
1249 visibleSize = size().height();
1250 } else {
1251 pos = m_mousePos.x();
1252 visibleSize = size().width();
1253 }
1254
1255 if (m_autoScrollTimer->interval() == InitialAutoScrollDelay) {
1256 m_autoScrollIncrement = 0;
1257 }
1258
1259 m_autoScrollIncrement = calculateAutoScrollingIncrement(pos, visibleSize, m_autoScrollIncrement);
1260 if (m_autoScrollIncrement == 0) {
1261 // The mouse position is not above an autoscroll margin (the autoscroll timer
1262 // will be restarted in mouseMoveEvent())
1263 m_autoScrollTimer->stop();
1264 return;
1265 }
1266
1267 if (m_rubberBand->isActive() && m_skipAutoScrollForRubberBand) {
1268 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1269 // if the direction of the rubberband is similar to the autoscroll direction. This
1270 // prevents that starting to create a rubberband within the autoscroll margins starts
1271 // an autoscrolling.
1272
1273 const qreal minDiff = 4; // Ignore any autoscrolling if the rubberband is very small
1274 const qreal diff = (scrollOrientation() == Qt::Vertical)
1275 ? m_rubberBand->endPosition().y() - m_rubberBand->startPosition().y()
1276 : m_rubberBand->endPosition().x() - m_rubberBand->startPosition().x();
1277 if (qAbs(diff) < minDiff || (m_autoScrollIncrement < 0 && diff > 0) || (m_autoScrollIncrement > 0 && diff < 0)) {
1278 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1279 // been moved up although the autoscroll direction might be down)
1280 m_autoScrollTimer->stop();
1281 return;
1282 }
1283 }
1284
1285 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1286 // the autoscrolling may not get skipped anymore until a new rubberband is created
1287 m_skipAutoScrollForRubberBand = false;
1288
1289 const qreal maxVisibleOffset = qMax(qreal(0), maximumScrollOffset() - visibleSize);
1290 const qreal newScrollOffset = qMin(scrollOffset() + m_autoScrollIncrement, maxVisibleOffset);
1291 setScrollOffset(newScrollOffset);
1292
1293 // Trigger the autoscroll timer which will periodically call
1294 // triggerAutoScrolling()
1295 m_autoScrollTimer->start(RepeatingAutoScrollDelay);
1296 }
1297
1298 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1299 {
1300 KItemListWidget* widget = qobject_cast<KItemListWidget*>(sender());
1301 Q_ASSERT(widget);
1302 KItemListGroupHeader* groupHeader = m_visibleGroups.value(widget);
1303 Q_ASSERT(groupHeader);
1304 updateGroupHeaderLayout(widget);
1305 }
1306
1307 void KItemListView::setController(KItemListController* controller)
1308 {
1309 if (m_controller != controller) {
1310 KItemListController* previous = m_controller;
1311 if (previous) {
1312 KItemListSelectionManager* selectionManager = previous->selectionManager();
1313 disconnect(selectionManager, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1314 disconnect(selectionManager, SIGNAL(selectionChanged(QSet<int>,QSet<int>)), this, SLOT(slotSelectionChanged(QSet<int>,QSet<int>)));
1315 }
1316
1317 m_controller = controller;
1318
1319 if (controller) {
1320 KItemListSelectionManager* selectionManager = controller->selectionManager();
1321 connect(selectionManager, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1322 connect(selectionManager, SIGNAL(selectionChanged(QSet<int>,QSet<int>)), this, SLOT(slotSelectionChanged(QSet<int>,QSet<int>)));
1323 }
1324
1325 onControllerChanged(controller, previous);
1326 }
1327 }
1328
1329 void KItemListView::setModel(KItemModelBase* model)
1330 {
1331 if (m_model == model) {
1332 return;
1333 }
1334
1335 KItemModelBase* previous = m_model;
1336
1337 if (m_model) {
1338 disconnect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
1339 this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
1340 disconnect(m_model, SIGNAL(itemsInserted(KItemRangeList)),
1341 this, SLOT(slotItemsInserted(KItemRangeList)));
1342 disconnect(m_model, SIGNAL(itemsRemoved(KItemRangeList)),
1343 this, SLOT(slotItemsRemoved(KItemRangeList)));
1344 disconnect(m_model, SIGNAL(itemsMoved(KItemRange,QList<int>)),
1345 this, SLOT(slotItemsMoved(KItemRange,QList<int>)));
1346 disconnect(m_model, SIGNAL(groupedSortingChanged(bool)),
1347 this, SLOT(slotGroupedSortingChanged(bool)));
1348 disconnect(m_model, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)),
1349 this, SLOT(slotSortOrderChanged(Qt::SortOrder,Qt::SortOrder)));
1350 disconnect(m_model, SIGNAL(sortRoleChanged(QByteArray,QByteArray)),
1351 this, SLOT(slotSortRoleChanged(QByteArray,QByteArray)));
1352 }
1353
1354 m_model = model;
1355 m_layouter->setModel(model);
1356 m_grouped = model->groupedSorting();
1357
1358 if (m_model) {
1359 connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
1360 this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
1361 connect(m_model, SIGNAL(itemsInserted(KItemRangeList)),
1362 this, SLOT(slotItemsInserted(KItemRangeList)));
1363 connect(m_model, SIGNAL(itemsRemoved(KItemRangeList)),
1364 this, SLOT(slotItemsRemoved(KItemRangeList)));
1365 connect(m_model, SIGNAL(itemsMoved(KItemRange,QList<int>)),
1366 this, SLOT(slotItemsMoved(KItemRange,QList<int>)));
1367 connect(m_model, SIGNAL(groupedSortingChanged(bool)),
1368 this, SLOT(slotGroupedSortingChanged(bool)));
1369 connect(m_model, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)),
1370 this, SLOT(slotSortOrderChanged(Qt::SortOrder,Qt::SortOrder)));
1371 connect(m_model, SIGNAL(sortRoleChanged(QByteArray,QByteArray)),
1372 this, SLOT(slotSortRoleChanged(QByteArray,QByteArray)));
1373 }
1374
1375 onModelChanged(model, previous);
1376 }
1377
1378 KItemListRubberBand* KItemListView::rubberBand() const
1379 {
1380 return m_rubberBand;
1381 }
1382
1383 void KItemListView::doLayout(LayoutAnimationHint hint, int changedIndex, int changedCount)
1384 {
1385 if (m_layoutTimer->isActive()) {
1386 m_layoutTimer->stop();
1387 }
1388
1389 if (m_activeTransactions > 0) {
1390 if (hint == NoAnimation) {
1391 // As soon as at least one property change should be done without animation,
1392 // the whole transaction will be marked as not animated.
1393 m_endTransactionAnimationHint = NoAnimation;
1394 }
1395 return;
1396 }
1397
1398 if (!m_model || m_model->count() < 0) {
1399 return;
1400 }
1401
1402 int firstVisibleIndex = m_layouter->firstVisibleIndex();
1403 if (firstVisibleIndex < 0) {
1404 emitOffsetChanges();
1405 return;
1406 }
1407
1408 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1409 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1410 // is still shown if the maximum offset got decreased.
1411 const qreal visibleOffsetRange = (scrollOrientation() == Qt::Horizontal) ? size().width() : size().height();
1412 const qreal maxOffsetToShowFullRange = maximumScrollOffset() - visibleOffsetRange;
1413 if (scrollOffset() > maxOffsetToShowFullRange) {
1414 m_layouter->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange));
1415 firstVisibleIndex = m_layouter->firstVisibleIndex();
1416 }
1417
1418 const int lastVisibleIndex = m_layouter->lastVisibleIndex();
1419
1420 int firstSibblingIndex = -1;
1421 int lastSibblingIndex = -1;
1422 const bool supportsExpanding = supportsItemExpanding();
1423
1424 QList<int> reusableItems = recycleInvisibleItems(firstVisibleIndex, lastVisibleIndex, hint);
1425
1426 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1427 // instances from invisible items are reused. If no reusable items are
1428 // found then new KItemListWidget instances get created.
1429 const bool animate = (hint == Animation);
1430 for (int i = firstVisibleIndex; i <= lastVisibleIndex; ++i) {
1431 bool applyNewPos = true;
1432 bool wasHidden = false;
1433
1434 const QRectF itemBounds = m_layouter->itemRect(i);
1435 const QPointF newPos = itemBounds.topLeft();
1436 KItemListWidget* widget = m_visibleItems.value(i);
1437 if (!widget) {
1438 wasHidden = true;
1439 if (!reusableItems.isEmpty()) {
1440 // Reuse a KItemListWidget instance from an invisible item
1441 const int oldIndex = reusableItems.takeLast();
1442 widget = m_visibleItems.value(oldIndex);
1443 setWidgetIndex(widget, i);
1444 updateWidgetProperties(widget, i);
1445 initializeItemListWidget(widget);
1446 } else {
1447 // No reusable KItemListWidget instance is available, create a new one
1448 widget = createWidget(i);
1449 }
1450 widget->resize(itemBounds.size());
1451
1452 if (animate && changedCount < 0) {
1453 // Items have been deleted, move the created item to the
1454 // imaginary old position. They will get animated to the new position
1455 // later.
1456 const QRectF itemRect = m_layouter->itemRect(i - changedCount);
1457 if (itemRect.isEmpty()) {
1458 const QPointF invisibleOldPos = (scrollOrientation() == Qt::Vertical)
1459 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1460 widget->setPos(invisibleOldPos);
1461 } else {
1462 widget->setPos(itemRect.topLeft());
1463 }
1464 applyNewPos = false;
1465 }
1466
1467 if (supportsExpanding && changedCount == 0) {
1468 if (firstSibblingIndex < 0) {
1469 firstSibblingIndex = i;
1470 }
1471 lastSibblingIndex = i;
1472 }
1473 }
1474
1475 if (animate) {
1476 const bool itemsRemoved = (changedCount < 0);
1477 const bool itemsInserted = (changedCount > 0);
1478 if (itemsRemoved && (i >= changedIndex + changedCount + 1)) {
1479 // The item is located after the removed items. Animate the moving of the position.
1480 applyNewPos = !moveWidget(widget, newPos);
1481 } else if (itemsInserted && i >= changedIndex) {
1482 // The item is located after the first inserted item
1483 if (i <= changedIndex + changedCount - 1) {
1484 // The item is an inserted item. Animate the appearing of the item.
1485 // For performance reasons no animation is done when changedCount is equal
1486 // to all available items.
1487 if (changedCount < m_model->count()) {
1488 m_animation->start(widget, KItemListViewAnimation::CreateAnimation);
1489 }
1490 } else if (!m_animation->isStarted(widget, KItemListViewAnimation::CreateAnimation)) {
1491 // The item was already there before, so animate the moving of the position.
1492 // No moving animation is done if the item is animated by a create animation: This
1493 // prevents a "move animation mess" when inserting several ranges in parallel.
1494 applyNewPos = !moveWidget(widget, newPos);
1495 }
1496 } else if (!itemsRemoved && !itemsInserted && !wasHidden) {
1497 // The size of the view might have been changed. Animate the moving of the position.
1498 applyNewPos = !moveWidget(widget, newPos);
1499 }
1500 } else {
1501 m_animation->stop(widget);
1502 }
1503
1504 if (applyNewPos) {
1505 widget->setPos(newPos);
1506 }
1507
1508 Q_ASSERT(widget->index() == i);
1509 widget->setVisible(true);
1510
1511 if (widget->size() != itemBounds.size()) {
1512 // Resize the widget for the item to the changed size.
1513 if (animate) {
1514 // If a dynamic item size is used then no animation is done in the direction
1515 // of the dynamic size.
1516 if (m_itemSize.width() <= 0) {
1517 // The width is dynamic, apply the new width without animation.
1518 widget->resize(itemBounds.width(), widget->size().height());
1519 } else if (m_itemSize.height() <= 0) {
1520 // The height is dynamic, apply the new height without animation.
1521 widget->resize(widget->size().width(), itemBounds.height());
1522 }
1523 m_animation->start(widget, KItemListViewAnimation::ResizeAnimation, itemBounds.size());
1524 } else {
1525 widget->resize(itemBounds.size());
1526 }
1527 }
1528
1529 // Updating the cell-information must be done as last step: The decision whether the
1530 // moving-animation should be started at all is based on the previous cell-information.
1531 const Cell cell(m_layouter->itemColumn(i), m_layouter->itemRow(i));
1532 m_visibleCells.insert(i, cell);
1533 }
1534
1535 // Delete invisible KItemListWidget instances that have not been reused
1536 foreach (int index, reusableItems) {
1537 recycleWidget(m_visibleItems.value(index));
1538 }
1539
1540 if (supportsExpanding && firstSibblingIndex >= 0) {
1541 Q_ASSERT(lastSibblingIndex >= 0);
1542 updateSiblingsInformation(firstSibblingIndex, lastSibblingIndex);
1543 }
1544
1545 if (m_grouped) {
1546 // Update the layout of all visible group headers
1547 QHashIterator<KItemListWidget*, KItemListGroupHeader*> it(m_visibleGroups);
1548 while (it.hasNext()) {
1549 it.next();
1550 updateGroupHeaderLayout(it.key());
1551 }
1552 }
1553
1554 emitOffsetChanges();
1555 }
1556
1557 QList<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex,
1558 int lastVisibleIndex,
1559 LayoutAnimationHint hint)
1560 {
1561 // Determine all items that are completely invisible and might be
1562 // reused for items that just got (at least partly) visible. If the
1563 // animation hint is set to 'Animation' items that do e.g. an animated
1564 // moving of their position are not marked as invisible: This assures
1565 // that a scrolling inside the view can be done without breaking an animation.
1566
1567 QList<int> items;
1568
1569 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
1570 while (it.hasNext()) {
1571 it.next();
1572
1573 KItemListWidget* widget = it.value();
1574 const int index = widget->index();
1575 const bool invisible = (index < firstVisibleIndex) || (index > lastVisibleIndex);
1576
1577 if (invisible) {
1578 if (m_animation->isStarted(widget)) {
1579 if (hint == NoAnimation) {
1580 // Stopping the animation will call KItemListView::slotAnimationFinished()
1581 // and the widget will be recycled if necessary there.
1582 m_animation->stop(widget);
1583 }
1584 } else {
1585 widget->setVisible(false);
1586 items.append(index);
1587
1588 if (m_grouped) {
1589 recycleGroupHeaderForWidget(widget);
1590 }
1591 }
1592 }
1593 }
1594
1595 return items;
1596 }
1597
1598 bool KItemListView::moveWidget(KItemListWidget* widget,const QPointF& newPos)
1599 {
1600 if (widget->pos() == newPos) {
1601 return false;
1602 }
1603
1604 bool startMovingAnim = false;
1605
1606 // When having a grid the moving-animation should only be started, if it is done within
1607 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1608 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1609 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1610 const int index = widget->index();
1611 const Cell cell = m_visibleCells.value(index);
1612 if (cell.column >= 0 && cell.row >= 0) {
1613 if (scrollOrientation() == Qt::Vertical) {
1614 startMovingAnim = (cell.row == m_layouter->itemRow(index));
1615 } else {
1616 startMovingAnim = (cell.column == m_layouter->itemColumn(index));
1617 }
1618 }
1619
1620 if (startMovingAnim) {
1621 m_animation->start(widget, KItemListViewAnimation::MovingAnimation, newPos);
1622 return true;
1623 }
1624
1625 m_animation->stop(widget);
1626 m_animation->start(widget, KItemListViewAnimation::CreateAnimation);
1627 return false;
1628 }
1629
1630 void KItemListView::emitOffsetChanges()
1631 {
1632 const qreal newScrollOffset = m_layouter->scrollOffset();
1633 if (m_oldScrollOffset != newScrollOffset) {
1634 emit scrollOffsetChanged(newScrollOffset, m_oldScrollOffset);
1635 m_oldScrollOffset = newScrollOffset;
1636 }
1637
1638 const qreal newMaximumScrollOffset = m_layouter->maximumScrollOffset();
1639 if (m_oldMaximumScrollOffset != newMaximumScrollOffset) {
1640 emit maximumScrollOffsetChanged(newMaximumScrollOffset, m_oldMaximumScrollOffset);
1641 m_oldMaximumScrollOffset = newMaximumScrollOffset;
1642 }
1643
1644 const qreal newItemOffset = m_layouter->itemOffset();
1645 if (m_oldItemOffset != newItemOffset) {
1646 emit itemOffsetChanged(newItemOffset, m_oldItemOffset);
1647 m_oldItemOffset = newItemOffset;
1648 }
1649
1650 const qreal newMaximumItemOffset = m_layouter->maximumItemOffset();
1651 if (m_oldMaximumItemOffset != newMaximumItemOffset) {
1652 emit maximumItemOffsetChanged(newMaximumItemOffset, m_oldMaximumItemOffset);
1653 m_oldMaximumItemOffset = newMaximumItemOffset;
1654 }
1655 }
1656
1657 KItemListWidget* KItemListView::createWidget(int index)
1658 {
1659 KItemListWidget* widget = m_widgetCreator->create(this);
1660 widget->setFlag(QGraphicsItem::ItemStacksBehindParent);
1661
1662 m_visibleItems.insert(index, widget);
1663 m_visibleCells.insert(index, Cell());
1664 updateWidgetProperties(widget, index);
1665 initializeItemListWidget(widget);
1666 return widget;
1667 }
1668
1669 void KItemListView::recycleWidget(KItemListWidget* widget)
1670 {
1671 if (m_grouped) {
1672 recycleGroupHeaderForWidget(widget);
1673 }
1674
1675 const int index = widget->index();
1676 m_visibleItems.remove(index);
1677 m_visibleCells.remove(index);
1678
1679 m_widgetCreator->recycle(widget);
1680 }
1681
1682 void KItemListView::setWidgetIndex(KItemListWidget* widget, int index)
1683 {
1684 const int oldIndex = widget->index();
1685 m_visibleItems.remove(oldIndex);
1686 m_visibleCells.remove(oldIndex);
1687
1688 m_visibleItems.insert(index, widget);
1689 m_visibleCells.insert(index, Cell());
1690
1691 widget->setIndex(index);
1692 }
1693
1694 void KItemListView::moveWidgetToIndex(KItemListWidget* widget, int index)
1695 {
1696 const int oldIndex = widget->index();
1697 const Cell oldCell = m_visibleCells.value(oldIndex);
1698
1699 setWidgetIndex(widget, index);
1700
1701 const Cell newCell(m_layouter->itemColumn(index), m_layouter->itemRow(index));
1702 const bool vertical = (scrollOrientation() == Qt::Vertical);
1703 const bool updateCell = (vertical && oldCell.row == newCell.row) ||
1704 (!vertical && oldCell.column == newCell.column);
1705 if (updateCell) {
1706 m_visibleCells.insert(index, newCell);
1707 }
1708 }
1709
1710 void KItemListView::setLayouterSize(const QSizeF& size, SizeType sizeType)
1711 {
1712 switch (sizeType) {
1713 case LayouterSize: m_layouter->setSize(size); break;
1714 case ItemSize: m_layouter->setItemSize(size); break;
1715 default: break;
1716 }
1717 }
1718
1719 void KItemListView::updateWidgetProperties(KItemListWidget* widget, int index)
1720 {
1721 widget->setVisibleRoles(m_visibleRoles);
1722 widget->setVisibleRolesSizes(m_stretchedVisibleRolesSizes);
1723 widget->setStyleOption(m_styleOption);
1724
1725 const KItemListSelectionManager* selectionManager = m_controller->selectionManager();
1726 widget->setCurrent(index == selectionManager->currentItem());
1727 widget->setSelected(selectionManager->isSelected(index));
1728 widget->setHovered(false);
1729 widget->setEnabledSelectionToggle(enabledSelectionToggles());
1730 widget->setIndex(index);
1731 widget->setData(m_model->data(index));
1732 widget->setSiblingsInformation(QBitArray());
1733 updateAlternateBackgroundForWidget(widget);
1734
1735 if (m_grouped) {
1736 updateGroupHeaderForWidget(widget);
1737 }
1738 }
1739
1740 void KItemListView::updateGroupHeaderForWidget(KItemListWidget* widget)
1741 {
1742 Q_ASSERT(m_grouped);
1743
1744 const int index = widget->index();
1745 if (!m_layouter->isFirstGroupItem(index)) {
1746 // The widget does not represent the first item of a group
1747 // and hence requires no header
1748 recycleGroupHeaderForWidget(widget);
1749 return;
1750 }
1751
1752 const QList<QPair<int, QVariant> > groups = model()->groups();
1753 if (groups.isEmpty()) {
1754 return;
1755 }
1756
1757 KItemListGroupHeader* groupHeader = m_visibleGroups.value(widget);
1758 if (!groupHeader) {
1759 groupHeader = m_groupHeaderCreator->create(this);
1760 groupHeader->setParentItem(widget);
1761 m_visibleGroups.insert(widget, groupHeader);
1762 connect(widget, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1763 }
1764 Q_ASSERT(groupHeader->parentItem() == widget);
1765
1766 const int groupIndex = groupIndexForItem(index);
1767 Q_ASSERT(groupIndex >= 0);
1768 groupHeader->setData(groups.at(groupIndex).second);
1769 groupHeader->setRole(model()->sortRole());
1770 groupHeader->setStyleOption(m_styleOption);
1771 groupHeader->setScrollOrientation(scrollOrientation());
1772 groupHeader->setItemIndex(index);
1773
1774 groupHeader->show();
1775 }
1776
1777 void KItemListView::updateGroupHeaderLayout(KItemListWidget* widget)
1778 {
1779 KItemListGroupHeader* groupHeader = m_visibleGroups.value(widget);
1780 Q_ASSERT(groupHeader);
1781
1782 const int index = widget->index();
1783 const QRectF groupHeaderRect = m_layouter->groupHeaderRect(index);
1784 const QRectF itemRect = m_layouter->itemRect(index);
1785
1786 // The group-header is a child of the itemlist widget. Translate the
1787 // group header position to the relative position.
1788 if (scrollOrientation() == Qt::Vertical) {
1789 // In the vertical scroll orientation the group header should always span
1790 // the whole width no matter which temporary position the parent widget
1791 // has. In this case the x-position and width will be adjusted manually.
1792 groupHeader->setPos(-widget->x(), -groupHeaderRect.height());
1793 groupHeader->resize(size().width(), groupHeaderRect.size().height());
1794 } else {
1795 groupHeader->setPos(groupHeaderRect.x() - itemRect.x(), -widget->y());
1796 groupHeader->resize(groupHeaderRect.size());
1797 }
1798 }
1799
1800 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget* widget)
1801 {
1802 KItemListGroupHeader* header = m_visibleGroups.value(widget);
1803 if (header) {
1804 header->setParentItem(0);
1805 m_groupHeaderCreator->recycle(header);
1806 m_visibleGroups.remove(widget);
1807 disconnect(widget, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1808 }
1809 }
1810
1811 void KItemListView::updateVisibleGroupHeaders()
1812 {
1813 Q_ASSERT(m_grouped);
1814 m_layouter->markAsDirty();
1815
1816 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
1817 while (it.hasNext()) {
1818 it.next();
1819 updateGroupHeaderForWidget(it.value());
1820 }
1821 }
1822
1823 int KItemListView::groupIndexForItem(int index) const
1824 {
1825 Q_ASSERT(m_grouped);
1826
1827 const QList<QPair<int, QVariant> > groups = model()->groups();
1828 if (groups.isEmpty()) {
1829 return -1;
1830 }
1831
1832 int min = 0;
1833 int max = groups.count() - 1;
1834 int mid = 0;
1835 do {
1836 mid = (min + max) / 2;
1837 if (index > groups[mid].first) {
1838 min = mid + 1;
1839 } else {
1840 max = mid - 1;
1841 }
1842 } while (groups[mid].first != index && min <= max);
1843
1844 if (min > max) {
1845 while (groups[mid].first > index && mid > 0) {
1846 --mid;
1847 }
1848 }
1849
1850 return mid;
1851 }
1852
1853 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget* widget)
1854 {
1855 bool enabled = useAlternateBackgrounds();
1856 if (enabled) {
1857 const int index = widget->index();
1858 enabled = (index & 0x1) > 0;
1859 if (m_grouped) {
1860 const int groupIndex = groupIndexForItem(index);
1861 if (groupIndex >= 0) {
1862 const QList<QPair<int, QVariant> > groups = model()->groups();
1863 const int indexOfFirstGroupItem = groups[groupIndex].first;
1864 const int relativeIndex = index - indexOfFirstGroupItem;
1865 enabled = (relativeIndex & 0x1) > 0;
1866 }
1867 }
1868 }
1869 widget->setAlternateBackground(enabled);
1870 }
1871
1872 bool KItemListView::useAlternateBackgrounds() const
1873 {
1874 return m_itemSize.isEmpty() && m_visibleRoles.count() > 1;
1875 }
1876
1877 QHash<QByteArray, qreal> KItemListView::headerRolesWidths() const
1878 {
1879 QHash<QByteArray, qreal> rolesWidths;
1880
1881 QHashIterator<QByteArray, QSizeF> it(m_stretchedVisibleRolesSizes);
1882 while (it.hasNext()) {
1883 it.next();
1884 rolesWidths.insert(it.key(), it.value().width());
1885 }
1886
1887 return rolesWidths;
1888 }
1889
1890 void KItemListView::updateVisibleRolesSizes(const KItemRangeList& itemRanges)
1891 {
1892 if (!m_itemSize.isEmpty() || m_useHeaderWidths) {
1893 return;
1894 }
1895
1896 const int itemCount = m_model->count();
1897 int rangesItemCount = 0;
1898 foreach (const KItemRange& range, itemRanges) {
1899 rangesItemCount += range.count;
1900 }
1901
1902 if (itemCount == rangesItemCount) {
1903 m_visibleRolesSizes = visibleRolesSizes(itemRanges);
1904 if (m_header) {
1905 // Assure the the sizes are not smaller than the minimum defined by the header
1906 // TODO: Currently only implemented for a top-aligned header
1907 const qreal minHeaderRoleWidth = m_header->minimumRoleWidth();
1908 QMutableHashIterator<QByteArray, QSizeF> it (m_visibleRolesSizes);
1909 while (it.hasNext()) {
1910 it.next();
1911 const QSizeF& size = it.value();
1912 if (size.width() < minHeaderRoleWidth) {
1913 const QSizeF newSize(minHeaderRoleWidth, size.height());
1914 m_visibleRolesSizes.insert(it.key(), newSize);
1915 }
1916 }
1917 }
1918 } else {
1919 // Only a sub range of the roles need to be determined.
1920 // The chances are good that the sizes of the sub ranges
1921 // already fit into the available sizes and hence no
1922 // expensive update might be required.
1923 bool updateRequired = false;
1924
1925 const QHash<QByteArray, QSizeF> updatedSizes = visibleRolesSizes(itemRanges);
1926 QHashIterator<QByteArray, QSizeF> it(updatedSizes);
1927 while (it.hasNext()) {
1928 it.next();
1929 const QByteArray& role = it.key();
1930 const QSizeF& updatedSize = it.value();
1931 const QSizeF currentSize = m_visibleRolesSizes.value(role);
1932 if (updatedSize.width() > currentSize.width() || updatedSize.height() > currentSize.height()) {
1933 m_visibleRolesSizes.insert(role, updatedSize);
1934 updateRequired = true;
1935 }
1936 }
1937
1938 if (!updateRequired) {
1939 // All the updated sizes are smaller than the current sizes and no change
1940 // of the stretched roles-widths is required
1941 return;
1942 }
1943 }
1944
1945 updateStretchedVisibleRolesSizes();
1946 }
1947
1948 void KItemListView::updateVisibleRolesSizes()
1949 {
1950 if (!m_model) {
1951 return;
1952 }
1953
1954 const int itemCount = m_model->count();
1955 if (itemCount > 0) {
1956 updateVisibleRolesSizes(KItemRangeList() << KItemRange(0, itemCount));
1957 }
1958 }
1959
1960 void KItemListView::updateStretchedVisibleRolesSizes()
1961 {
1962 if (!m_itemSize.isEmpty() || m_useHeaderWidths || m_visibleRoles.isEmpty()) {
1963 return;
1964 }
1965
1966 // Calculate the maximum size of an item by considering the
1967 // visible role sizes and apply them to the layouter. If the
1968 // size does not use the available view-size it the size of the
1969 // first role will get stretched.
1970 m_stretchedVisibleRolesSizes = m_visibleRolesSizes;
1971 const QByteArray role = m_visibleRoles.first();
1972 QSizeF firstRoleSize = m_stretchedVisibleRolesSizes.value(role);
1973
1974 QSizeF dynamicItemSize = m_itemSize;
1975
1976 if (dynamicItemSize.width() <= 0) {
1977 const qreal requiredWidth = visibleRolesSizesWidthSum();
1978 const qreal availableWidth = size().width();
1979 if (requiredWidth < availableWidth) {
1980 // Stretch the first role to use the whole width for the item
1981 firstRoleSize.rwidth() += availableWidth - requiredWidth;
1982 m_stretchedVisibleRolesSizes.insert(role, firstRoleSize);
1983 }
1984 dynamicItemSize.setWidth(qMax(requiredWidth, availableWidth));
1985 }
1986
1987 if (dynamicItemSize.height() <= 0) {
1988 const qreal requiredHeight = visibleRolesSizesHeightSum();
1989 const qreal availableHeight = size().height();
1990 if (requiredHeight < availableHeight) {
1991 // Stretch the first role to use the whole height for the item
1992 firstRoleSize.rheight() += availableHeight - requiredHeight;
1993 m_stretchedVisibleRolesSizes.insert(role, firstRoleSize);
1994 }
1995 dynamicItemSize.setHeight(qMax(requiredHeight, availableHeight));
1996 }
1997
1998 m_layouter->setItemSize(dynamicItemSize);
1999
2000 if (m_header) {
2001 m_header->setVisibleRolesWidths(headerRolesWidths());
2002 m_header->resize(dynamicItemSize.width(), m_header->size().height());
2003 }
2004
2005 // Update the role sizes for all visible widgets
2006 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
2007 while (it.hasNext()) {
2008 it.next();
2009 it.value()->setVisibleRolesSizes(m_stretchedVisibleRolesSizes);
2010 }
2011 }
2012
2013 qreal KItemListView::visibleRolesSizesWidthSum() const
2014 {
2015 qreal widthSum = 0;
2016 QHashIterator<QByteArray, QSizeF> it(m_visibleRolesSizes);
2017 while (it.hasNext()) {
2018 it.next();
2019 widthSum += it.value().width();
2020 }
2021 return widthSum;
2022 }
2023
2024 qreal KItemListView::visibleRolesSizesHeightSum() const
2025 {
2026 qreal heightSum = 0;
2027 QHashIterator<QByteArray, QSizeF> it(m_visibleRolesSizes);
2028 while (it.hasNext()) {
2029 it.next();
2030 heightSum += it.value().height();
2031 }
2032 return heightSum;
2033 }
2034
2035 QRectF KItemListView::headerBoundaries() const
2036 {
2037 return m_header ? m_header->geometry() : QRectF();
2038 }
2039
2040 bool KItemListView::changesItemGridLayout(const QSizeF& newGridSize,
2041 const QSizeF& newItemSize,
2042 const QSizeF& newItemMargin) const
2043 {
2044 if (newItemSize.isEmpty() || newGridSize.isEmpty()) {
2045 return false;
2046 }
2047
2048 if (m_layouter->scrollOrientation() == Qt::Vertical) {
2049 const qreal itemWidth = m_layouter->itemSize().width();
2050 if (itemWidth > 0) {
2051 const int newColumnCount = itemsPerSize(newGridSize.width(),
2052 newItemSize.width(),
2053 newItemMargin.width());
2054 if (m_model->count() > newColumnCount) {
2055 const int oldColumnCount = itemsPerSize(m_layouter->size().width(),
2056 itemWidth,
2057 m_layouter->itemMargin().width());
2058 return oldColumnCount != newColumnCount;
2059 }
2060 }
2061 } else {
2062 const qreal itemHeight = m_layouter->itemSize().height();
2063 if (itemHeight > 0) {
2064 const int newRowCount = itemsPerSize(newGridSize.height(),
2065 newItemSize.height(),
2066 newItemMargin.height());
2067 if (m_model->count() > newRowCount) {
2068 const int oldRowCount = itemsPerSize(m_layouter->size().height(),
2069 itemHeight,
2070 m_layouter->itemMargin().height());
2071 return oldRowCount != newRowCount;
2072 }
2073 }
2074 }
2075
2076 return false;
2077 }
2078
2079 bool KItemListView::animateChangedItemCount(int changedItemCount) const
2080 {
2081 if (m_layouter->size().isEmpty() || m_layouter->itemSize().isEmpty()) {
2082 return false;
2083 }
2084
2085 const int maximum = (scrollOrientation() == Qt::Vertical)
2086 ? m_layouter->size().width() / m_layouter->itemSize().width()
2087 : m_layouter->size().height() / m_layouter->itemSize().height();
2088 // Only animate if up to 2/3 of a row or column are inserted or removed
2089 return changedItemCount <= maximum * 2 / 3;
2090 }
2091
2092
2093 bool KItemListView::scrollBarRequired(const QSizeF& size) const
2094 {
2095 const QSizeF oldSize = m_layouter->size();
2096
2097 m_layouter->setSize(size);
2098 const qreal maxOffset = m_layouter->maximumScrollOffset();
2099 m_layouter->setSize(oldSize);
2100
2101 return m_layouter->scrollOrientation() == Qt::Vertical ? maxOffset > size.height()
2102 : maxOffset > size.width();
2103 }
2104
2105 void KItemListView::updateGroupHeaderHeight()
2106 {
2107 qreal groupHeaderHeight = m_styleOption.fontMetrics.height();
2108 qreal groupHeaderMargin = 0;
2109
2110 if (scrollOrientation() == Qt::Horizontal) {
2111 // The vertical margin above and below the header should be
2112 // equal to the horizontal margin, not the vertical margin
2113 // from m_styleOption.
2114 groupHeaderHeight += 2 * m_styleOption.horizontalMargin;
2115 groupHeaderMargin = m_styleOption.horizontalMargin;
2116 } else if (m_itemSize.isEmpty()){
2117 groupHeaderHeight += 4 * m_styleOption.padding;
2118 groupHeaderMargin = m_styleOption.iconSize / 2;
2119 } else {
2120 groupHeaderHeight += 2 * m_styleOption.padding + m_styleOption.verticalMargin;
2121 groupHeaderMargin = m_styleOption.iconSize / 4;
2122 }
2123 m_layouter->setGroupHeaderHeight(groupHeaderHeight);
2124 m_layouter->setGroupHeaderMargin(groupHeaderMargin);
2125
2126 updateVisibleGroupHeaders();
2127 }
2128
2129 void KItemListView::updateSiblingsInformation(int firstIndex, int lastIndex)
2130 {
2131 if (!supportsItemExpanding() || !m_model) {
2132 return;
2133 }
2134
2135 if (firstIndex < 0 || lastIndex < 0) {
2136 firstIndex = m_layouter->firstVisibleIndex();
2137 lastIndex = m_layouter->lastVisibleIndex();
2138 } else {
2139 const bool isRangeVisible = (firstIndex <= m_layouter->lastVisibleIndex() &&
2140 lastIndex >= m_layouter->firstVisibleIndex());
2141 if (!isRangeVisible) {
2142 return;
2143 }
2144 }
2145
2146 int previousParents = 0;
2147 QBitArray previousSiblings;
2148
2149 // The rootIndex describes the first index where the siblings get
2150 // calculated from. For the calculation the upper most parent item
2151 // is required. For performance reasons it is checked first whether
2152 // the visible items before or after the current range already
2153 // contain a siblings information which can be used as base.
2154 int rootIndex = firstIndex;
2155
2156 KItemListWidget* widget = m_visibleItems.value(firstIndex - 1);
2157 if (!widget) {
2158 // There is no visible widget before the range, check whether there
2159 // is one after the range:
2160 widget = m_visibleItems.value(lastIndex + 1);
2161 if (widget) {
2162 // The sibling information of the widget may only be used if
2163 // all items of the range have the same number of parents.
2164 const int parents = m_model->expandedParentsCount(lastIndex + 1);
2165 for (int i = lastIndex; i >= firstIndex; --i) {
2166 if (m_model->expandedParentsCount(i) != parents) {
2167 widget = 0;
2168 break;
2169 }
2170 }
2171 }
2172 }
2173
2174 if (widget) {
2175 // Performance optimization: Use the sibling information of the visible
2176 // widget beside the given range.
2177 previousSiblings = widget->siblingsInformation();
2178 if (previousSiblings.isEmpty()) {
2179 return;
2180 }
2181 previousParents = previousSiblings.count() - 1;
2182 previousSiblings.truncate(previousParents);
2183 } else {
2184 // Potentially slow path: Go back to the upper most parent of firstIndex
2185 // to be able to calculate the initial value for the siblings.
2186 while (rootIndex > 0 && m_model->expandedParentsCount(rootIndex) > 0) {
2187 --rootIndex;
2188 }
2189 }
2190
2191 Q_ASSERT(previousParents >= 0);
2192 for (int i = rootIndex; i <= lastIndex; ++i) {
2193 // Update the parent-siblings in case if the current item represents
2194 // a child or an upper parent.
2195 const int currentParents = m_model->expandedParentsCount(i);
2196 Q_ASSERT(currentParents >= 0);
2197 if (previousParents < currentParents) {
2198 previousParents = currentParents;
2199 previousSiblings.resize(currentParents);
2200 previousSiblings.setBit(currentParents - 1, hasSiblingSuccessor(i - 1));
2201 } else if (previousParents > currentParents) {
2202 previousParents = currentParents;
2203 previousSiblings.truncate(currentParents);
2204 }
2205
2206 if (i >= firstIndex) {
2207 // The index represents a visible item. Apply the parent-siblings
2208 // and update the sibling of the current item.
2209 KItemListWidget* widget = m_visibleItems.value(i);
2210 if (!widget) {
2211 continue;
2212 }
2213
2214 QBitArray siblings = previousSiblings;
2215 siblings.resize(siblings.count() + 1);
2216 siblings.setBit(siblings.count() - 1, hasSiblingSuccessor(i));
2217
2218 widget->setSiblingsInformation(siblings);
2219 }
2220 }
2221 }
2222
2223 bool KItemListView::hasSiblingSuccessor(int index) const
2224 {
2225 bool hasSuccessor = false;
2226 const int parentsCount = m_model->expandedParentsCount(index);
2227 int successorIndex = index + 1;
2228
2229 // Search the next sibling
2230 const int itemCount = m_model->count();
2231 while (successorIndex < itemCount) {
2232 const int currentParentsCount = m_model->expandedParentsCount(successorIndex);
2233 if (currentParentsCount == parentsCount) {
2234 hasSuccessor = true;
2235 break;
2236 } else if (currentParentsCount < parentsCount) {
2237 break;
2238 }
2239 ++successorIndex;
2240 }
2241
2242 if (m_grouped && hasSuccessor) {
2243 // If the sibling is part of another group, don't mark it as
2244 // successor as the group header is between the sibling connections.
2245 for (int i = index + 1; i <= successorIndex; ++i) {
2246 if (m_layouter->isFirstGroupItem(i)) {
2247 hasSuccessor = false;
2248 break;
2249 }
2250 }
2251 }
2252
2253 return hasSuccessor;
2254 }
2255
2256 int KItemListView::calculateAutoScrollingIncrement(int pos, int range, int oldInc)
2257 {
2258 int inc = 0;
2259
2260 const int minSpeed = 4;
2261 const int maxSpeed = 128;
2262 const int speedLimiter = 96;
2263 const int autoScrollBorder = 64;
2264
2265 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2266 // This assures that the autoscrolling speed grows gradually.
2267 const int incLimiter = 1;
2268
2269 if (pos < autoScrollBorder) {
2270 inc = -minSpeed + qAbs(pos - autoScrollBorder) * (pos - autoScrollBorder) / speedLimiter;
2271 inc = qMax(inc, -maxSpeed);
2272 inc = qMax(inc, oldInc - incLimiter);
2273 } else if (pos > range - autoScrollBorder) {
2274 inc = minSpeed + qAbs(pos - range + autoScrollBorder) * (pos - range + autoScrollBorder) / speedLimiter;
2275 inc = qMin(inc, maxSpeed);
2276 inc = qMin(inc, oldInc + incLimiter);
2277 }
2278
2279 return inc;
2280 }
2281
2282 int KItemListView::itemsPerSize(qreal size, qreal itemSize, qreal itemMargin)
2283 {
2284 const qreal availableSize = size - itemMargin;
2285 const int count = availableSize / (itemSize + itemMargin);
2286 return count;
2287 }
2288
2289
2290
2291 KItemListCreatorBase::~KItemListCreatorBase()
2292 {
2293 qDeleteAll(m_recycleableWidgets);
2294 qDeleteAll(m_createdWidgets);
2295 }
2296
2297 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget* widget)
2298 {
2299 m_createdWidgets.insert(widget);
2300 }
2301
2302 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget* widget)
2303 {
2304 Q_ASSERT(m_createdWidgets.contains(widget));
2305 m_createdWidgets.remove(widget);
2306
2307 if (m_recycleableWidgets.count() < 100) {
2308 m_recycleableWidgets.append(widget);
2309 widget->setVisible(false);
2310 } else {
2311 delete widget;
2312 }
2313 }
2314
2315 QGraphicsWidget* KItemListCreatorBase::popRecycleableWidget()
2316 {
2317 if (m_recycleableWidgets.isEmpty()) {
2318 return 0;
2319 }
2320
2321 QGraphicsWidget* widget = m_recycleableWidgets.takeLast();
2322 m_createdWidgets.insert(widget);
2323 return widget;
2324 }
2325
2326 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2327 {
2328 }
2329
2330 void KItemListWidgetCreatorBase::recycle(KItemListWidget* widget)
2331 {
2332 widget->setParentItem(0);
2333 widget->setOpacity(1.0);
2334 pushRecycleableWidget(widget);
2335 }
2336
2337 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2338 {
2339 }
2340
2341 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader* header)
2342 {
2343 header->setOpacity(1.0);
2344 pushRecycleableWidget(header);
2345 }
2346
2347 #include "kitemlistview.moc"