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