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