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