]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kitemlistview.cpp
Don't use mixed units in size-column of details-view
[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_grouped(false),
56 m_activeTransactions(0),
57 m_itemSize(),
58 m_controller(0),
59 m_model(0),
60 m_visibleRoles(),
61 m_visibleRolesSizes(),
62 m_stretchedVisibleRolesSizes(),
63 m_widgetCreator(0),
64 m_groupHeaderCreator(0),
65 m_styleOption(),
66 m_visibleItems(),
67 m_visibleGroups(),
68 m_sizeHintResolver(0),
69 m_layouter(0),
70 m_animation(0),
71 m_layoutTimer(0),
72 m_oldScrollOffset(0),
73 m_oldMaximumScrollOffset(0),
74 m_oldItemOffset(0),
75 m_oldMaximumItemOffset(0),
76 m_skipAutoScrollForRubberBand(false),
77 m_rubberBand(0),
78 m_mousePos(),
79 m_autoScrollIncrement(0),
80 m_autoScrollTimer(0),
81 m_header(0),
82 m_useHeaderWidths(false)
83 {
84 setAcceptHoverEvents(true);
85
86 m_sizeHintResolver = new KItemListSizeHintResolver(this);
87
88 m_layouter = new KItemListViewLayouter(this);
89 m_layouter->setSizeHintResolver(m_sizeHintResolver);
90
91 m_animation = new KItemListViewAnimation(this);
92 connect(m_animation, SIGNAL(finished(QGraphicsWidget*,KItemListViewAnimation::AnimationType)),
93 this, SLOT(slotAnimationFinished(QGraphicsWidget*,KItemListViewAnimation::AnimationType)));
94
95 m_layoutTimer = new QTimer(this);
96 m_layoutTimer->setInterval(300);
97 m_layoutTimer->setSingleShot(true);
98 connect(m_layoutTimer, SIGNAL(timeout()), this, SLOT(slotLayoutTimerFinished()));
99
100 m_rubberBand = new KItemListRubberBand(this);
101 connect(m_rubberBand, SIGNAL(activationChanged(bool)), this, SLOT(slotRubberBandActivationChanged(bool)));
102 }
103
104 KItemListView::~KItemListView()
105 {
106 delete m_sizeHintResolver;
107 m_sizeHintResolver = 0;
108 }
109
110 void KItemListView::setScrollOrientation(Qt::Orientation orientation)
111 {
112 const Qt::Orientation previousOrientation = m_layouter->scrollOrientation();
113 if (orientation == previousOrientation) {
114 return;
115 }
116
117 m_layouter->setScrollOrientation(orientation);
118 m_animation->setScrollOrientation(orientation);
119 m_sizeHintResolver->clearCache();
120
121 if (m_grouped) {
122 QMutableHashIterator<KItemListWidget*, KItemListGroupHeader*> it (m_visibleGroups);
123 while (it.hasNext()) {
124 it.next();
125 it.value()->setScrollOrientation(orientation);
126 }
127 }
128
129 doLayout(Animation, 0, 0);
130
131 onScrollOrientationChanged(orientation, previousOrientation);
132 emit scrollOrientationChanged(orientation, previousOrientation);
133 }
134
135 Qt::Orientation KItemListView::scrollOrientation() const
136 {
137 return m_layouter->scrollOrientation();
138 }
139
140 void KItemListView::setItemSize(const QSizeF& itemSize)
141 {
142 const QSizeF previousSize = m_itemSize;
143 if (itemSize == previousSize) {
144 return;
145 }
146
147 m_itemSize = itemSize;
148
149 const bool emptySize = itemSize.isEmpty();
150 if (emptySize) {
151 updateVisibleRolesSizes();
152 } else {
153 if (itemSize.width() < previousSize.width() || itemSize.height() < previousSize.height()) {
154 prepareLayoutForIncreasedItemCount(itemSize, ItemSize);
155 } else {
156 m_layouter->setItemSize(itemSize);
157 }
158 }
159
160 m_sizeHintResolver->clearCache();
161 doLayout(Animation, 0, 0);
162 onItemSizeChanged(itemSize, previousSize);
163 }
164
165 QSizeF KItemListView::itemSize() const
166 {
167 return m_itemSize;
168 }
169
170 void KItemListView::setScrollOffset(qreal offset)
171 {
172 if (offset < 0) {
173 offset = 0;
174 }
175
176 const qreal previousOffset = m_layouter->scrollOffset();
177 if (offset == previousOffset) {
178 return;
179 }
180
181 m_layouter->setScrollOffset(offset);
182 m_animation->setScrollOffset(offset);
183 if (!m_layoutTimer->isActive()) {
184 doLayout(NoAnimation, 0, 0);
185 }
186 onScrollOffsetChanged(offset, previousOffset);
187 }
188
189 qreal KItemListView::scrollOffset() const
190 {
191 return m_layouter->scrollOffset();
192 }
193
194 qreal KItemListView::maximumScrollOffset() const
195 {
196 return m_layouter->maximumScrollOffset();
197 }
198
199 void KItemListView::setItemOffset(qreal offset)
200 {
201 m_layouter->setItemOffset(offset);
202 if (m_header) {
203 m_header->setPos(-offset, 0);
204 }
205 if (!m_layoutTimer->isActive()) {
206 doLayout(NoAnimation, 0, 0);
207 }
208 }
209
210 qreal KItemListView::itemOffset() const
211 {
212 return m_layouter->itemOffset();
213 }
214
215 qreal KItemListView::maximumItemOffset() const
216 {
217 return m_layouter->maximumItemOffset();
218 }
219
220 void KItemListView::setVisibleRoles(const QList<QByteArray>& roles)
221 {
222 const QList<QByteArray> previousRoles = m_visibleRoles;
223 m_visibleRoles = roles;
224
225 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
226 while (it.hasNext()) {
227 it.next();
228 KItemListWidget* widget = it.value();
229 widget->setVisibleRoles(roles);
230 widget->setVisibleRolesSizes(m_stretchedVisibleRolesSizes);
231 }
232
233 m_sizeHintResolver->clearCache();
234 m_layouter->markAsDirty();
235
236 if (m_header) {
237 m_header->setVisibleRoles(roles);
238 m_header->setVisibleRolesWidths(headerRolesWidths());
239 m_useHeaderWidths = false;
240 }
241
242 updateVisibleRolesSizes();
243 doLayout(Animation, 0, 0);
244
245 onVisibleRolesChanged(roles, previousRoles);
246 }
247
248 QList<QByteArray> KItemListView::visibleRoles() const
249 {
250 return m_visibleRoles;
251 }
252
253 void KItemListView::setAutoScroll(bool enabled)
254 {
255 if (enabled && !m_autoScrollTimer) {
256 m_autoScrollTimer = new QTimer(this);
257 m_autoScrollTimer->setSingleShot(false);
258 connect(m_autoScrollTimer, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
259 m_autoScrollTimer->start(InitialAutoScrollDelay);
260 } else if (!enabled && m_autoScrollTimer) {
261 delete m_autoScrollTimer;
262 m_autoScrollTimer = 0;
263 }
264
265 }
266
267 bool KItemListView::autoScroll() const
268 {
269 return m_autoScrollTimer != 0;
270 }
271
272 KItemListController* KItemListView::controller() const
273 {
274 return m_controller;
275 }
276
277 KItemModelBase* KItemListView::model() const
278 {
279 return m_model;
280 }
281
282 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase* widgetCreator)
283 {
284 m_widgetCreator = widgetCreator;
285 }
286
287 KItemListWidgetCreatorBase* KItemListView::widgetCreator() const
288 {
289 return m_widgetCreator;
290 }
291
292 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase* groupHeaderCreator)
293 {
294 m_groupHeaderCreator = groupHeaderCreator;
295 }
296
297 KItemListGroupHeaderCreatorBase* KItemListView::groupHeaderCreator() const
298 {
299 return m_groupHeaderCreator;
300 }
301
302 void KItemListView::setStyleOption(const KItemListStyleOption& option)
303 {
304 const KItemListStyleOption previousOption = m_styleOption;
305 m_styleOption = option;
306
307 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
308 while (it.hasNext()) {
309 it.next();
310 it.value()->setStyleOption(option);
311 }
312
313 m_sizeHintResolver->clearCache();
314 doLayout(Animation, 0, 0);
315 onStyleOptionChanged(option, previousOption);
316 }
317
318 const KItemListStyleOption& KItemListView::styleOption() const
319 {
320 return m_styleOption;
321 }
322
323 void KItemListView::setGeometry(const QRectF& rect)
324 {
325 QGraphicsWidget::setGeometry(rect);
326
327 if (!m_model) {
328 return;
329 }
330
331 if (m_model->count() > 0) {
332 prepareLayoutForIncreasedItemCount(rect.size(), LayouterSize);
333 } else {
334 m_layouter->setSize(rect.size());
335 }
336
337 if (!m_layoutTimer->isActive()) {
338 m_layoutTimer->start();
339 }
340
341 // Changing the geometry does not require to do an expensive
342 // update of the visible-roles sizes, only the stretched sizes
343 // need to be adjusted to the new size.
344 updateStretchedVisibleRolesSizes();
345 }
346
347 int KItemListView::itemAt(const QPointF& pos) const
348 {
349 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
350 while (it.hasNext()) {
351 it.next();
352
353 const KItemListWidget* widget = it.value();
354 const QPointF mappedPos = widget->mapFromItem(this, pos);
355 if (widget->contains(mappedPos)) {
356 return it.key();
357 }
358 }
359
360 return -1;
361 }
362
363 bool KItemListView::isAboveSelectionToggle(int index, const QPointF& pos) const
364 {
365 Q_UNUSED(index);
366 Q_UNUSED(pos);
367 return false;
368 }
369
370 bool KItemListView::isAboveExpansionToggle(int index, const QPointF& pos) const
371 {
372 const KItemListWidget* widget = m_visibleItems.value(index);
373 if (widget) {
374 const QRectF expansionToggleRect = widget->expansionToggleRect();
375 if (!expansionToggleRect.isEmpty()) {
376 const QPointF mappedPos = widget->mapFromItem(this, pos);
377 return expansionToggleRect.contains(mappedPos);
378 }
379 }
380 return false;
381 }
382
383 int KItemListView::firstVisibleIndex() const
384 {
385 return m_layouter->firstVisibleIndex();
386 }
387
388 int KItemListView::lastVisibleIndex() const
389 {
390 return m_layouter->lastVisibleIndex();
391 }
392
393 QSizeF KItemListView::itemSizeHint(int index) const
394 {
395 Q_UNUSED(index);
396 return itemSize();
397 }
398
399 QHash<QByteArray, QSizeF> KItemListView::visibleRolesSizes(const KItemRangeList& itemRanges) const
400 {
401 Q_UNUSED(itemRanges);
402 return QHash<QByteArray, QSizeF>();
403 }
404
405 QRectF KItemListView::itemRect(int index) const
406 {
407 return m_layouter->itemRect(index);
408 }
409
410 int KItemListView::itemsPerOffset() const
411 {
412 return m_layouter->itemsPerOffset();
413 }
414
415 void KItemListView::beginTransaction()
416 {
417 ++m_activeTransactions;
418 if (m_activeTransactions == 1) {
419 onTransactionBegin();
420 }
421 }
422
423 void KItemListView::endTransaction()
424 {
425 --m_activeTransactions;
426 if (m_activeTransactions < 0) {
427 m_activeTransactions = 0;
428 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
429 }
430
431 if (m_activeTransactions == 0) {
432 onTransactionEnd();
433 doLayout(Animation, 0, 0);
434 }
435 }
436
437 bool KItemListView::isTransactionActive() const
438 {
439 return m_activeTransactions > 0;
440 }
441
442
443 void KItemListView::setHeaderShown(bool show)
444 {
445
446 if (show && !m_header) {
447 m_header = new KItemListHeader(this);
448 m_header->setPos(0, 0);
449 m_header->setModel(m_model);
450 m_header->setVisibleRoles(m_visibleRoles);
451 m_header->setVisibleRolesWidths(headerRolesWidths());
452 m_header->setZValue(1);
453
454 m_useHeaderWidths = false;
455
456 connect(m_header, SIGNAL(visibleRoleWidthChanged(QByteArray,qreal,qreal)),
457 this, SLOT(slotVisibleRoleWidthChanged(QByteArray,qreal,qreal)));
458
459 m_layouter->setHeaderHeight(m_header->size().height());
460 } else if (!show && m_header) {
461 delete m_header;
462 m_header = 0;
463 m_useHeaderWidths = false;
464 m_layouter->setHeaderHeight(0);
465 }
466 }
467
468 bool KItemListView::isHeaderShown() const
469 {
470 return m_header != 0;
471 }
472
473 QPixmap KItemListView::createDragPixmap(const QSet<int>& indexes) const
474 {
475 Q_UNUSED(indexes);
476 return QPixmap();
477 }
478
479 void KItemListView::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
480 {
481 QGraphicsWidget::paint(painter, option, widget);
482
483 if (m_rubberBand->isActive()) {
484 QRectF rubberBandRect = QRectF(m_rubberBand->startPosition(),
485 m_rubberBand->endPosition()).normalized();
486
487 const QPointF topLeft = rubberBandRect.topLeft();
488 if (scrollOrientation() == Qt::Vertical) {
489 rubberBandRect.moveTo(topLeft.x(), topLeft.y() - scrollOffset());
490 } else {
491 rubberBandRect.moveTo(topLeft.x() - scrollOffset(), topLeft.y());
492 }
493
494 QStyleOptionRubberBand opt;
495 opt.initFrom(widget);
496 opt.shape = QRubberBand::Rectangle;
497 opt.opaque = false;
498 opt.rect = rubberBandRect.toRect();
499 style()->drawControl(QStyle::CE_RubberBand, &opt, painter);
500 }
501 }
502
503 void KItemListView::initializeItemListWidget(KItemListWidget* item)
504 {
505 Q_UNUSED(item);
506 }
507
508 bool KItemListView::itemSizeHintUpdateRequired(const QSet<QByteArray>& changedRoles) const
509 {
510 Q_UNUSED(changedRoles);
511 return true;
512 }
513
514 void KItemListView::onControllerChanged(KItemListController* current, KItemListController* previous)
515 {
516 Q_UNUSED(current);
517 Q_UNUSED(previous);
518 }
519
520 void KItemListView::onModelChanged(KItemModelBase* current, KItemModelBase* previous)
521 {
522 Q_UNUSED(current);
523 Q_UNUSED(previous);
524 }
525
526 void KItemListView::onScrollOrientationChanged(Qt::Orientation current, Qt::Orientation previous)
527 {
528 Q_UNUSED(current);
529 Q_UNUSED(previous);
530 }
531
532 void KItemListView::onItemSizeChanged(const QSizeF& current, const QSizeF& previous)
533 {
534 Q_UNUSED(current);
535 Q_UNUSED(previous);
536 }
537
538 void KItemListView::onScrollOffsetChanged(qreal current, qreal previous)
539 {
540 Q_UNUSED(current);
541 Q_UNUSED(previous);
542 }
543
544 void KItemListView::onVisibleRolesChanged(const QList<QByteArray>& current, const QList<QByteArray>& previous)
545 {
546 Q_UNUSED(current);
547 Q_UNUSED(previous);
548 }
549
550 void KItemListView::onStyleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous)
551 {
552 Q_UNUSED(current);
553 Q_UNUSED(previous);
554 }
555
556 void KItemListView::onTransactionBegin()
557 {
558 }
559
560 void KItemListView::onTransactionEnd()
561 {
562 }
563
564 bool KItemListView::event(QEvent* event)
565 {
566 // Forward all events to the controller and handle them there
567 if (m_controller && m_controller->processEvent(event, transform())) {
568 event->accept();
569 return true;
570 }
571 return QGraphicsWidget::event(event);
572 }
573
574 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent* event)
575 {
576 m_mousePos = transform().map(event->pos());
577 event->accept();
578 }
579
580 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
581 {
582 QGraphicsWidget::mouseMoveEvent(event);
583
584 m_mousePos = transform().map(event->pos());
585 if (m_autoScrollTimer && !m_autoScrollTimer->isActive()) {
586 m_autoScrollTimer->start(InitialAutoScrollDelay);
587 }
588 }
589
590 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent* event)
591 {
592 event->setAccepted(true);
593 setAutoScroll(true);
594 }
595
596 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent *event)
597 {
598 QGraphicsWidget::dragMoveEvent(event);
599
600 m_mousePos = transform().map(event->pos());
601 if (m_autoScrollTimer && !m_autoScrollTimer->isActive()) {
602 m_autoScrollTimer->start(InitialAutoScrollDelay);
603 }
604 }
605
606 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
607 {
608 QGraphicsWidget::dragLeaveEvent(event);
609 setAutoScroll(false);
610 }
611
612 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent* event)
613 {
614 QGraphicsWidget::dropEvent(event);
615 setAutoScroll(false);
616 }
617
618 QList<KItemListWidget*> KItemListView::visibleItemListWidgets() const
619 {
620 return m_visibleItems.values();
621 }
622
623 void KItemListView::resizeEvent(QGraphicsSceneResizeEvent* event)
624 {
625 QGraphicsWidget::resizeEvent(event);
626 if (m_itemSize.isEmpty() && m_useHeaderWidths) {
627 QSizeF dynamicItemSize = m_layouter->itemSize();
628 const QSizeF newSize = event->newSize();
629
630 if (m_itemSize.width() < 0) {
631 const qreal requiredWidth = visibleRolesSizesWidthSum();
632 if (newSize.width() > requiredWidth) {
633 dynamicItemSize.setWidth(newSize.width());
634 }
635 const qreal headerWidth = qMax(newSize.width(), requiredWidth);
636 m_header->resize(headerWidth, m_header->size().height());
637 }
638
639 if (m_itemSize.height() < 0) {
640 const qreal requiredHeight = visibleRolesSizesHeightSum();
641 if (newSize.height() > requiredHeight) {
642 dynamicItemSize.setHeight(newSize.height());
643 }
644 // TODO: KItemListHeader is not prepared for vertical alignment
645 }
646
647 m_layouter->setItemSize(dynamicItemSize);
648 }
649 }
650
651 void KItemListView::slotItemsInserted(const KItemRangeList& itemRanges)
652 {
653 updateVisibleRolesSizes(itemRanges);
654
655 const bool hasMultipleRanges = (itemRanges.count() > 1);
656 if (hasMultipleRanges) {
657 beginTransaction();
658 }
659
660 int previouslyInsertedCount = 0;
661 foreach (const KItemRange& range, itemRanges) {
662 // range.index is related to the model before anything has been inserted.
663 // As in each loop the current item-range gets inserted the index must
664 // be increased by the already previously inserted items.
665 const int index = range.index + previouslyInsertedCount;
666 const int count = range.count;
667 if (index < 0 || count <= 0) {
668 kWarning() << "Invalid item range (index:" << index << ", count:" << count << ")";
669 continue;
670 }
671 previouslyInsertedCount += count;
672
673 m_sizeHintResolver->itemsInserted(index, count);
674
675 // Determine which visible items must be moved
676 QList<int> itemsToMove;
677 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
678 while (it.hasNext()) {
679 it.next();
680 const int visibleItemIndex = it.key();
681 if (visibleItemIndex >= index) {
682 itemsToMove.append(visibleItemIndex);
683 }
684 }
685
686 // Update the indexes of all KItemListWidget instances that are located
687 // after the inserted items. It is important to adjust the indexes in the order
688 // from the highest index to the lowest index to prevent overlaps when setting the new index.
689 qSort(itemsToMove);
690 for (int i = itemsToMove.count() - 1; i >= 0; --i) {
691 KItemListWidget* widget = m_visibleItems.value(itemsToMove[i]);
692 Q_ASSERT(widget);
693 setWidgetIndex(widget, widget->index() + count);
694 }
695
696 m_layouter->markAsDirty();
697 if (m_model->count() == count && maximumScrollOffset() > size().height()) {
698 kDebug() << "Scrollbar required, skipping layout";
699 const int scrollBarExtent = style()->pixelMetric(QStyle::PM_ScrollBarExtent);
700 QSizeF layouterSize = m_layouter->size();
701 if (scrollOrientation() == Qt::Vertical) {
702 layouterSize.rwidth() -= scrollBarExtent;
703 } else {
704 layouterSize.rheight() -= scrollBarExtent;
705 }
706 m_layouter->setSize(layouterSize);
707 }
708
709 if (!hasMultipleRanges) {
710 doLayout(Animation, index, count);
711 update();
712 }
713 }
714
715 if (m_controller) {
716 m_controller->selectionManager()->itemsInserted(itemRanges);
717 }
718
719 if (hasMultipleRanges) {
720 endTransaction();
721 }
722 }
723
724 void KItemListView::slotItemsRemoved(const KItemRangeList& itemRanges)
725 {
726 updateVisibleRolesSizes();
727
728 const bool hasMultipleRanges = (itemRanges.count() > 1);
729 if (hasMultipleRanges) {
730 beginTransaction();
731 }
732
733 for (int i = itemRanges.count() - 1; i >= 0; --i) {
734 const KItemRange& range = itemRanges.at(i);
735 const int index = range.index;
736 const int count = range.count;
737 if (index < 0 || count <= 0) {
738 kWarning() << "Invalid item range (index:" << index << ", count:" << count << ")";
739 continue;
740 }
741
742 m_sizeHintResolver->itemsRemoved(index, count);
743
744 const int firstRemovedIndex = index;
745 const int lastRemovedIndex = index + count - 1;
746 const int lastIndex = m_model->count() + count - 1;
747
748 // Remove all KItemListWidget instances that got deleted
749 for (int i = firstRemovedIndex; i <= lastRemovedIndex; ++i) {
750 KItemListWidget* widget = m_visibleItems.value(i);
751 if (!widget) {
752 continue;
753 }
754
755 m_animation->stop(widget);
756 // Stopping the animation might lead to recycling the widget if
757 // it is invisible (see slotAnimationFinished()).
758 // Check again whether it is still visible:
759 if (!m_visibleItems.contains(i)) {
760 continue;
761 }
762
763 if (m_model->count() == 0) {
764 // For performance reasons no animation is done when all items have
765 // been removed.
766 recycleWidget(widget);
767 } else {
768 // Animate the removing of the items. Special case: When removing an item there
769 // is no valid model index available anymore. For the
770 // remove-animation the item gets removed from m_visibleItems but the widget
771 // will stay alive until the animation has been finished and will
772 // be recycled (deleted) in KItemListView::slotAnimationFinished().
773 m_visibleItems.remove(i);
774 widget->setIndex(-1);
775 m_animation->start(widget, KItemListViewAnimation::DeleteAnimation);
776 }
777 }
778
779 // Update the indexes of all KItemListWidget instances that are located
780 // after the deleted items
781 for (int i = lastRemovedIndex + 1; i <= lastIndex; ++i) {
782 KItemListWidget* widget = m_visibleItems.value(i);
783 if (widget) {
784 const int newIndex = i - count;
785 setWidgetIndex(widget, newIndex);
786 }
787 }
788
789 m_layouter->markAsDirty();
790 if (!hasMultipleRanges) {
791 doLayout(Animation, index, -count);
792 update();
793 }
794 }
795
796 if (m_controller) {
797 m_controller->selectionManager()->itemsRemoved(itemRanges);
798 }
799
800 if (hasMultipleRanges) {
801 endTransaction();
802 }
803 }
804
805 void KItemListView::slotItemsMoved(const KItemRange& itemRange, const QList<int>& movedToIndexes)
806 {
807 const int firstVisibleMovedIndex = qMax(firstVisibleIndex(), itemRange.index);
808 const int lastVisibleMovedIndex = qMin(lastVisibleIndex(), itemRange.index + itemRange.count - 1);
809
810 for (int index = firstVisibleMovedIndex; index <= lastVisibleMovedIndex; ++index) {
811 KItemListWidget* widget = m_visibleItems.value(index);
812 if (widget) {
813 updateWidgetProperties(widget, index);
814 }
815 }
816
817 if (m_controller) {
818 m_controller->selectionManager()->itemsMoved(itemRange, movedToIndexes);
819 }
820 }
821
822 void KItemListView::slotItemsChanged(const KItemRangeList& itemRanges,
823 const QSet<QByteArray>& roles)
824 {
825 const bool updateSizeHints = itemSizeHintUpdateRequired(roles);
826 if (updateSizeHints) {
827 updateVisibleRolesSizes(itemRanges);
828 }
829
830 foreach (const KItemRange& itemRange, itemRanges) {
831 const int index = itemRange.index;
832 const int count = itemRange.count;
833
834 if (updateSizeHints) {
835 m_sizeHintResolver->itemsChanged(index, count, roles);
836 m_layouter->markAsDirty();
837
838 if (!m_layoutTimer->isActive()) {
839 m_layoutTimer->start();
840 }
841 }
842
843 // Apply the changed roles to the visible item-widgets
844 const int lastIndex = index + count - 1;
845 for (int i = index; i <= lastIndex; ++i) {
846 KItemListWidget* widget = m_visibleItems.value(i);
847 if (widget) {
848 widget->setData(m_model->data(i), roles);
849 }
850 }
851
852 if (m_grouped && roles.contains(m_model->sortRole())) {
853 // The sort-role has been changed which might result
854 // in modified group headers
855 updateVisibleGroupHeaders();
856 doLayout(NoAnimation, 0, 0);
857 if (!m_layoutTimer->isActive()) {
858 m_layoutTimer->start();
859 }
860 }
861 }
862 }
863
864 void KItemListView::slotGroupedSortingChanged(bool current)
865 {
866 m_grouped = current;
867 m_layouter->markAsDirty();
868
869 if (m_grouped) {
870 // Apply the height of the header to the layouter
871 const qreal groupHeaderHeight = m_styleOption.fontMetrics.height() +
872 m_styleOption.margin * 2;
873 m_layouter->setGroupHeaderHeight(groupHeaderHeight);
874
875 updateVisibleGroupHeaders();
876 } else {
877 // Clear all visible headers
878 QMutableHashIterator<KItemListWidget*, KItemListGroupHeader*> it (m_visibleGroups);
879 while (it.hasNext()) {
880 it.next();
881 recycleGroupHeaderForWidget(it.key());
882 }
883 Q_ASSERT(m_visibleGroups.isEmpty());
884 }
885
886 doLayout(Animation, 0, 0);
887 }
888
889 void KItemListView::slotSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous)
890 {
891 Q_UNUSED(current);
892 Q_UNUSED(previous);
893 if (m_grouped) {
894 updateVisibleGroupHeaders();
895 doLayout(Animation, 0, 0);
896 }
897 }
898
899 void KItemListView::slotSortRoleChanged(const QByteArray& current, const QByteArray& previous)
900 {
901 Q_UNUSED(current);
902 Q_UNUSED(previous);
903 if (m_grouped) {
904 updateVisibleGroupHeaders();
905 doLayout(Animation, 0, 0);
906 }
907 }
908
909 void KItemListView::slotCurrentChanged(int current, int previous)
910 {
911 Q_UNUSED(previous);
912
913 KItemListWidget* previousWidget = m_visibleItems.value(previous, 0);
914 if (previousWidget) {
915 Q_ASSERT(previousWidget->isCurrent());
916 previousWidget->setCurrent(false);
917 }
918
919 KItemListWidget* currentWidget = m_visibleItems.value(current, 0);
920 if (currentWidget) {
921 Q_ASSERT(!currentWidget->isCurrent());
922 currentWidget->setCurrent(true);
923 }
924
925 const QRectF viewGeometry = geometry();
926 const QRectF currentRect = itemRect(current);
927
928 if (!viewGeometry.contains(currentRect)) {
929 // Make sure that the new current item is fully visible in the view.
930 qreal newOffset = scrollOffset();
931 if (currentRect.top() < viewGeometry.top()) {
932 Q_ASSERT(scrollOrientation() == Qt::Vertical);
933 newOffset += currentRect.top() - viewGeometry.top();
934 } else if ((currentRect.bottom() > viewGeometry.bottom())) {
935 Q_ASSERT(scrollOrientation() == Qt::Vertical);
936 newOffset += currentRect.bottom() - viewGeometry.bottom();
937 } else if (currentRect.left() < viewGeometry.left()) {
938 if (scrollOrientation() == Qt::Horizontal) {
939 newOffset += currentRect.left() - viewGeometry.left();
940 }
941 } else if ((currentRect.right() > viewGeometry.right())) {
942 if (scrollOrientation() == Qt::Horizontal) {
943 newOffset += currentRect.right() - viewGeometry.right();
944 }
945 }
946
947 if (newOffset != scrollOffset()) {
948 emit scrollTo(newOffset);
949 }
950 }
951 }
952
953 void KItemListView::slotSelectionChanged(const QSet<int>& current, const QSet<int>& previous)
954 {
955 Q_UNUSED(previous);
956
957 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
958 while (it.hasNext()) {
959 it.next();
960 const int index = it.key();
961 KItemListWidget* widget = it.value();
962 widget->setSelected(current.contains(index));
963 }
964 }
965
966 void KItemListView::slotAnimationFinished(QGraphicsWidget* widget,
967 KItemListViewAnimation::AnimationType type)
968 {
969 KItemListWidget* itemListWidget = qobject_cast<KItemListWidget*>(widget);
970 Q_ASSERT(itemListWidget);
971
972 switch (type) {
973 case KItemListViewAnimation::DeleteAnimation: {
974 // As we recycle the widget in this case it is important to assure that no
975 // other animation has been started. This is a convention in KItemListView and
976 // not a requirement defined by KItemListViewAnimation.
977 Q_ASSERT(!m_animation->isStarted(itemListWidget));
978
979 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
980 // by m_visibleWidgets and must be deleted manually after the animation has
981 // been finished.
982 recycleGroupHeaderForWidget(itemListWidget);
983 m_widgetCreator->recycle(itemListWidget);
984 break;
985 }
986
987 case KItemListViewAnimation::CreateAnimation:
988 case KItemListViewAnimation::MovingAnimation:
989 case KItemListViewAnimation::ResizeAnimation: {
990 const int index = itemListWidget->index();
991 const bool invisible = (index < m_layouter->firstVisibleIndex()) ||
992 (index > m_layouter->lastVisibleIndex());
993 if (invisible && !m_animation->isStarted(itemListWidget)) {
994 recycleWidget(itemListWidget);
995 }
996 break;
997 }
998
999 default: break;
1000 }
1001 }
1002
1003 void KItemListView::slotLayoutTimerFinished()
1004 {
1005 m_layouter->setSize(geometry().size());
1006 doLayout(Animation, 0, 0);
1007 }
1008
1009 void KItemListView::slotRubberBandPosChanged()
1010 {
1011 update();
1012 }
1013
1014 void KItemListView::slotRubberBandActivationChanged(bool active)
1015 {
1016 if (active) {
1017 connect(m_rubberBand, SIGNAL(startPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1018 connect(m_rubberBand, SIGNAL(endPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1019 m_skipAutoScrollForRubberBand = true;
1020 } else {
1021 disconnect(m_rubberBand, SIGNAL(startPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1022 disconnect(m_rubberBand, SIGNAL(endPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1023 m_skipAutoScrollForRubberBand = false;
1024 }
1025
1026 update();
1027 }
1028
1029 void KItemListView::slotVisibleRoleWidthChanged(const QByteArray& role,
1030 qreal currentWidth,
1031 qreal previousWidth)
1032 {
1033 Q_UNUSED(previousWidth);
1034
1035 m_useHeaderWidths = true;
1036
1037 if (m_visibleRolesSizes.contains(role)) {
1038 QSizeF roleSize = m_visibleRolesSizes.value(role);
1039 roleSize.setWidth(currentWidth);
1040 m_visibleRolesSizes.insert(role, roleSize);
1041 m_stretchedVisibleRolesSizes.insert(role, roleSize);
1042
1043 // Apply the new size to the layouter
1044 QSizeF dynamicItemSize = m_itemSize;
1045 if (dynamicItemSize.width() < 0) {
1046 const qreal requiredWidth = visibleRolesSizesWidthSum();
1047 dynamicItemSize.setWidth(qMax(size().width(), requiredWidth));
1048 }
1049 if (dynamicItemSize.height() < 0) {
1050 const qreal requiredHeight = visibleRolesSizesHeightSum();
1051 dynamicItemSize.setHeight(qMax(size().height(), requiredHeight));
1052 }
1053
1054 m_layouter->setItemSize(dynamicItemSize);
1055
1056 // Update the role sizes for all visible widgets
1057 foreach (KItemListWidget* widget, visibleItemListWidgets()) {
1058 widget->setVisibleRolesSizes(m_stretchedVisibleRolesSizes);
1059 }
1060
1061 doLayout(Animation, 0, 0);
1062 }
1063 }
1064
1065 void KItemListView::triggerAutoScrolling()
1066 {
1067 if (!m_autoScrollTimer) {
1068 return;
1069 }
1070
1071 int pos = 0;
1072 int visibleSize = 0;
1073 if (scrollOrientation() == Qt::Vertical) {
1074 pos = m_mousePos.y();
1075 visibleSize = size().height();
1076 } else {
1077 pos = m_mousePos.x();
1078 visibleSize = size().width();
1079 }
1080
1081 if (m_autoScrollTimer->interval() == InitialAutoScrollDelay) {
1082 m_autoScrollIncrement = 0;
1083 }
1084
1085 m_autoScrollIncrement = calculateAutoScrollingIncrement(pos, visibleSize, m_autoScrollIncrement);
1086 if (m_autoScrollIncrement == 0) {
1087 // The mouse position is not above an autoscroll margin (the autoscroll timer
1088 // will be restarted in mouseMoveEvent())
1089 m_autoScrollTimer->stop();
1090 return;
1091 }
1092
1093 if (m_rubberBand->isActive() && m_skipAutoScrollForRubberBand) {
1094 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1095 // if the direction of the rubberband is similar to the autoscroll direction. This
1096 // prevents that starting to create a rubberband within the autoscroll margins starts
1097 // an autoscrolling.
1098
1099 const qreal minDiff = 4; // Ignore any autoscrolling if the rubberband is very small
1100 const qreal diff = (scrollOrientation() == Qt::Vertical)
1101 ? m_rubberBand->endPosition().y() - m_rubberBand->startPosition().y()
1102 : m_rubberBand->endPosition().x() - m_rubberBand->startPosition().x();
1103 if (qAbs(diff) < minDiff || (m_autoScrollIncrement < 0 && diff > 0) || (m_autoScrollIncrement > 0 && diff < 0)) {
1104 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1105 // been moved up although the autoscroll direction might be down)
1106 m_autoScrollTimer->stop();
1107 return;
1108 }
1109 }
1110
1111 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1112 // the autoscrolling may not get skipped anymore until a new rubberband is created
1113 m_skipAutoScrollForRubberBand = false;
1114
1115 setScrollOffset(scrollOffset() + m_autoScrollIncrement);
1116
1117 // Trigger the autoscroll timer which will periodically call
1118 // triggerAutoScrolling()
1119 m_autoScrollTimer->start(RepeatingAutoScrollDelay);
1120 }
1121
1122 void KItemListView::setController(KItemListController* controller)
1123 {
1124 if (m_controller != controller) {
1125 KItemListController* previous = m_controller;
1126 if (previous) {
1127 KItemListSelectionManager* selectionManager = previous->selectionManager();
1128 disconnect(selectionManager, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1129 disconnect(selectionManager, SIGNAL(selectionChanged(QSet<int>,QSet<int>)), this, SLOT(slotSelectionChanged(QSet<int>,QSet<int>)));
1130 }
1131
1132 m_controller = controller;
1133
1134 if (controller) {
1135 KItemListSelectionManager* selectionManager = controller->selectionManager();
1136 connect(selectionManager, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1137 connect(selectionManager, SIGNAL(selectionChanged(QSet<int>,QSet<int>)), this, SLOT(slotSelectionChanged(QSet<int>,QSet<int>)));
1138 }
1139
1140 onControllerChanged(controller, previous);
1141 }
1142 }
1143
1144 void KItemListView::setModel(KItemModelBase* model)
1145 {
1146 if (m_model == model) {
1147 return;
1148 }
1149
1150 KItemModelBase* previous = m_model;
1151
1152 if (m_model) {
1153 disconnect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
1154 this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
1155 disconnect(m_model, SIGNAL(itemsInserted(KItemRangeList)),
1156 this, SLOT(slotItemsInserted(KItemRangeList)));
1157 disconnect(m_model, SIGNAL(itemsRemoved(KItemRangeList)),
1158 this, SLOT(slotItemsRemoved(KItemRangeList)));
1159 disconnect(m_model, SIGNAL(itemsMoved(KItemRange,QList<int>)),
1160 this, SLOT(slotItemsMoved(KItemRange,QList<int>)));
1161 disconnect(m_model, SIGNAL(groupedSortingChanged(bool)),
1162 this, SLOT(slotGroupedSortingChanged(bool)));
1163 disconnect(m_model, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)),
1164 this, SLOT(slotSortOrderChanged(Qt::SortOrder,Qt::SortOrder)));
1165 disconnect(m_model, SIGNAL(sortRoleChanged(QByteArray,QByteArray)),
1166 this, SLOT(slotSortRoleChanged(QByteArray,QByteArray)));
1167 }
1168
1169 m_model = model;
1170 m_layouter->setModel(model);
1171 m_grouped = model->groupedSorting();
1172
1173 if (m_model) {
1174 connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
1175 this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
1176 connect(m_model, SIGNAL(itemsInserted(KItemRangeList)),
1177 this, SLOT(slotItemsInserted(KItemRangeList)));
1178 connect(m_model, SIGNAL(itemsRemoved(KItemRangeList)),
1179 this, SLOT(slotItemsRemoved(KItemRangeList)));
1180 connect(m_model, SIGNAL(itemsMoved(KItemRange,QList<int>)),
1181 this, SLOT(slotItemsMoved(KItemRange,QList<int>)));
1182 connect(m_model, SIGNAL(groupedSortingChanged(bool)),
1183 this, SLOT(slotGroupedSortingChanged(bool)));
1184 connect(m_model, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)),
1185 this, SLOT(slotSortOrderChanged(Qt::SortOrder,Qt::SortOrder)));
1186 connect(m_model, SIGNAL(sortRoleChanged(QByteArray,QByteArray)),
1187 this, SLOT(slotSortRoleChanged(QByteArray,QByteArray)));
1188 }
1189
1190 onModelChanged(model, previous);
1191 }
1192
1193 KItemListRubberBand* KItemListView::rubberBand() const
1194 {
1195 return m_rubberBand;
1196 }
1197
1198 void KItemListView::doLayout(LayoutAnimationHint hint, int changedIndex, int changedCount)
1199 {
1200 if (m_layoutTimer->isActive()) {
1201 kDebug() << "Stopping layout timer, synchronous layout requested";
1202 m_layoutTimer->stop();
1203 }
1204
1205 if (m_model->count() < 0 || m_activeTransactions > 0) {
1206 return;
1207 }
1208
1209 const int firstVisibleIndex = m_layouter->firstVisibleIndex();
1210 const int lastVisibleIndex = m_layouter->lastVisibleIndex();
1211 if (firstVisibleIndex < 0) {
1212 emitOffsetChanges();
1213 return;
1214 }
1215
1216 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1217 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1218 // is still shown if the maximum offset got decreased.
1219 const qreal visibleOffsetRange = (scrollOrientation() == Qt::Horizontal) ? size().width() : size().height();
1220 const qreal maxOffsetToShowFullRange = maximumScrollOffset() - visibleOffsetRange;
1221 if (scrollOffset() > maxOffsetToShowFullRange) {
1222 m_layouter->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange));
1223 }
1224
1225 // Determine all items that are completely invisible and might be
1226 // reused for items that just got (at least partly) visible.
1227 // Items that do e.g. an animated moving of their position are not
1228 // marked as invisible: This assures that a scrolling inside the view
1229 // can be done without breaking an animation.
1230 QList<int> reusableItems;
1231 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
1232 while (it.hasNext()) {
1233 it.next();
1234 KItemListWidget* widget = it.value();
1235 const int index = widget->index();
1236 const bool invisible = (index < firstVisibleIndex) || (index > lastVisibleIndex);
1237 if (invisible && !m_animation->isStarted(widget)) {
1238 widget->setVisible(false);
1239 reusableItems.append(index);
1240
1241 if (m_grouped) {
1242 recycleGroupHeaderForWidget(widget);
1243 }
1244 }
1245 }
1246
1247 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1248 // instances from invisible items are reused. If no reusable items are
1249 // found then new KItemListWidget instances get created.
1250 const bool animate = (hint == Animation);
1251 for (int i = firstVisibleIndex; i <= lastVisibleIndex; ++i) {
1252 bool applyNewPos = true;
1253 bool wasHidden = false;
1254
1255 const QRectF itemBounds = m_layouter->itemRect(i);
1256 const QPointF newPos = itemBounds.topLeft();
1257 KItemListWidget* widget = m_visibleItems.value(i);
1258 if (!widget) {
1259 wasHidden = true;
1260 if (!reusableItems.isEmpty()) {
1261 // Reuse a KItemListWidget instance from an invisible item
1262 const int oldIndex = reusableItems.takeLast();
1263 widget = m_visibleItems.value(oldIndex);
1264 setWidgetIndex(widget, i);
1265
1266 if (m_grouped) {
1267 updateGroupHeaderForWidget(widget);
1268 }
1269 } else {
1270 // No reusable KItemListWidget instance is available, create a new one
1271 widget = createWidget(i);
1272 }
1273 widget->resize(itemBounds.size());
1274
1275 if (animate && changedCount < 0) {
1276 // Items have been deleted, move the created item to the
1277 // imaginary old position.
1278 const QRectF itemRect = m_layouter->itemRect(i - changedCount);
1279 if (itemRect.isEmpty()) {
1280 const QPointF invisibleOldPos = (scrollOrientation() == Qt::Vertical)
1281 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1282 widget->setPos(invisibleOldPos);
1283 } else {
1284 widget->setPos(itemRect.topLeft());
1285 }
1286 applyNewPos = false;
1287 }
1288 } else if (m_animation->isStarted(widget, KItemListViewAnimation::MovingAnimation)) {
1289 applyNewPos = false;
1290 }
1291
1292 if (animate) {
1293 const bool itemsRemoved = (changedCount < 0);
1294 const bool itemsInserted = (changedCount > 0);
1295
1296 if (itemsRemoved && (i >= changedIndex + changedCount + 1)) {
1297 // The item is located after the removed items. Animate the moving of the position.
1298 m_animation->start(widget, KItemListViewAnimation::MovingAnimation, newPos);
1299 applyNewPos = false;
1300 } else if (itemsInserted && i >= changedIndex) {
1301 // The item is located after the first inserted item
1302 if (i <= changedIndex + changedCount - 1) {
1303 // The item is an inserted item. Animate the appearing of the item.
1304 // For performance reasons no animation is done when changedCount is equal
1305 // to all available items.
1306 if (changedCount < m_model->count()) {
1307 m_animation->start(widget, KItemListViewAnimation::CreateAnimation);
1308 }
1309 } else if (!m_animation->isStarted(widget, KItemListViewAnimation::CreateAnimation)) {
1310 // The item was already there before, so animate the moving of the position.
1311 // No moving animation is done if the item is animated by a create animation: This
1312 // prevents a "move animation mess" when inserting several ranges in parallel.
1313 m_animation->start(widget, KItemListViewAnimation::MovingAnimation, newPos);
1314 applyNewPos = false;
1315 }
1316 } else if (!itemsRemoved && !itemsInserted && !wasHidden) {
1317 // The size of the view might have been changed. Animate the moving of the position.
1318 m_animation->start(widget, KItemListViewAnimation::MovingAnimation, newPos);
1319 applyNewPos = false;
1320 }
1321 }
1322
1323 if (applyNewPos) {
1324 widget->setPos(newPos);
1325 }
1326
1327 Q_ASSERT(widget->index() == i);
1328 widget->setVisible(true);
1329
1330 if (widget->size() != itemBounds.size()) {
1331 m_animation->start(widget, KItemListViewAnimation::ResizeAnimation, itemBounds.size());
1332 }
1333 }
1334
1335 // Delete invisible KItemListWidget instances that have not been reused
1336 foreach (int index, reusableItems) {
1337 recycleWidget(m_visibleItems.value(index));
1338 }
1339
1340 if (m_grouped) {
1341 // Update the layout of all visible group headers
1342 QHashIterator<KItemListWidget*, KItemListGroupHeader*> it(m_visibleGroups);
1343 while (it.hasNext()) {
1344 it.next();
1345 updateGroupHeaderLayout(it.key());
1346 }
1347 }
1348
1349 emitOffsetChanges();
1350 }
1351
1352 void KItemListView::emitOffsetChanges()
1353 {
1354 const qreal newScrollOffset = m_layouter->scrollOffset();
1355 if (m_oldScrollOffset != newScrollOffset) {
1356 emit scrollOffsetChanged(newScrollOffset, m_oldScrollOffset);
1357 m_oldScrollOffset = newScrollOffset;
1358 }
1359
1360 const qreal newMaximumScrollOffset = m_layouter->maximumScrollOffset();
1361 if (m_oldMaximumScrollOffset != newMaximumScrollOffset) {
1362 emit maximumScrollOffsetChanged(newMaximumScrollOffset, m_oldMaximumScrollOffset);
1363 m_oldMaximumScrollOffset = newMaximumScrollOffset;
1364 }
1365
1366 const qreal newItemOffset = m_layouter->itemOffset();
1367 if (m_oldItemOffset != newItemOffset) {
1368 emit itemOffsetChanged(newItemOffset, m_oldItemOffset);
1369 m_oldItemOffset = newItemOffset;
1370 }
1371
1372 const qreal newMaximumItemOffset = m_layouter->maximumItemOffset();
1373 if (m_oldMaximumItemOffset != newMaximumItemOffset) {
1374 emit maximumItemOffsetChanged(newMaximumItemOffset, m_oldMaximumItemOffset);
1375 m_oldMaximumItemOffset = newMaximumItemOffset;
1376 }
1377 }
1378
1379 KItemListWidget* KItemListView::createWidget(int index)
1380 {
1381 KItemListWidget* widget = m_widgetCreator->create(this);
1382 widget->setFlag(QGraphicsItem::ItemStacksBehindParent);
1383
1384 updateWidgetProperties(widget, index);
1385 m_visibleItems.insert(index, widget);
1386
1387 if (m_grouped) {
1388 updateGroupHeaderForWidget(widget);
1389 }
1390
1391 initializeItemListWidget(widget);
1392 return widget;
1393 }
1394
1395 void KItemListView::recycleWidget(KItemListWidget* widget)
1396 {
1397 if (m_grouped) {
1398 recycleGroupHeaderForWidget(widget);
1399 }
1400
1401 m_visibleItems.remove(widget->index());
1402 m_widgetCreator->recycle(widget);
1403 }
1404
1405 void KItemListView::setWidgetIndex(KItemListWidget* widget, int index)
1406 {
1407 const int oldIndex = widget->index();
1408 m_visibleItems.remove(oldIndex);
1409 updateWidgetProperties(widget, index);
1410 m_visibleItems.insert(index, widget);
1411
1412 initializeItemListWidget(widget);
1413 }
1414
1415 void KItemListView::prepareLayoutForIncreasedItemCount(const QSizeF& size, SizeType sizeType)
1416 {
1417 // Calculate the first visible index and last visible index for the current size
1418 const int currentFirst = m_layouter->firstVisibleIndex();
1419 const int currentLast = m_layouter->lastVisibleIndex();
1420
1421 const QSizeF currentSize = (sizeType == LayouterSize) ? m_layouter->size() : m_layouter->itemSize();
1422
1423 // Calculate the first visible index and last visible index for the new size
1424 setLayouterSize(size, sizeType);
1425 const int newFirst = m_layouter->firstVisibleIndex();
1426 const int newLast = m_layouter->lastVisibleIndex();
1427
1428 if ((currentFirst != newFirst) || (currentLast != newLast)) {
1429 // At least one index has been changed. Assure that widgets for all possible
1430 // visible items get created so that a move-animation can be started later.
1431 const int maxVisibleItems = m_layouter->maximumVisibleItems();
1432 int minFirst = qMin(newFirst, currentFirst);
1433 const int maxLast = qMax(newLast, currentLast);
1434
1435 if (maxLast - minFirst + 1 < maxVisibleItems) {
1436 // Increasing the size might result in a smaller KItemListView::offset().
1437 // Decrease the first visible index in a way that at least the maximum
1438 // visible items are shown.
1439 minFirst = qMax(0, maxLast - maxVisibleItems + 1);
1440 }
1441
1442 if (maxLast - minFirst > maxVisibleItems + maxVisibleItems / 2) {
1443 // The creating of widgets is quite expensive. Assure that never more
1444 // than 50 % of the maximum visible items get created for the animations.
1445 return;
1446 }
1447
1448 setLayouterSize(currentSize, sizeType);
1449 for (int i = minFirst; i <= maxLast; ++i) {
1450 if (!m_visibleItems.contains(i)) {
1451 KItemListWidget* widget = createWidget(i);
1452 const QRectF itemRect = m_layouter->itemRect(i);
1453 widget->setPos(itemRect.topLeft());
1454 widget->resize(itemRect.size());
1455 }
1456 }
1457 setLayouterSize(size, sizeType);
1458 }
1459 }
1460
1461 void KItemListView::setLayouterSize(const QSizeF& size, SizeType sizeType)
1462 {
1463 switch (sizeType) {
1464 case LayouterSize: m_layouter->setSize(size); break;
1465 case ItemSize: m_layouter->setItemSize(size); break;
1466 default: break;
1467 }
1468 }
1469
1470 void KItemListView::updateWidgetProperties(KItemListWidget* widget, int index)
1471 {
1472 widget->setVisibleRoles(m_visibleRoles);
1473 widget->setVisibleRolesSizes(m_stretchedVisibleRolesSizes);
1474 widget->setStyleOption(m_styleOption);
1475
1476 const KItemListSelectionManager* selectionManager = m_controller->selectionManager();
1477 widget->setCurrent(index == selectionManager->currentItem());
1478 widget->setSelected(selectionManager->isSelected(index));
1479 widget->setHovered(false);
1480 widget->setAlternatingBackgroundColors(false);
1481 widget->setIndex(index);
1482 widget->setData(m_model->data(index));
1483 }
1484
1485 void KItemListView::updateGroupHeaderForWidget(KItemListWidget* widget)
1486 {
1487 const int index = widget->index();
1488 if (!m_layouter->isFirstGroupItem(index)) {
1489 // The widget does not represent the first item of a group
1490 // and hence requires no header
1491 recycleGroupHeaderForWidget(widget);
1492 return;
1493 }
1494
1495 const QList<QPair<int, QVariant> > groups = model()->groups();
1496 if (groups.isEmpty()) {
1497 return;
1498 }
1499
1500 KItemListGroupHeader* header = m_visibleGroups.value(widget);
1501 if (!header) {
1502 header = m_groupHeaderCreator->create(this);
1503 header->setParentItem(widget);
1504 m_visibleGroups.insert(widget, header);
1505 }
1506 Q_ASSERT(header->parentItem() == widget);
1507
1508 // Determine the shown data for the header by doing a binary
1509 // search in the groups-list
1510 int min = 0;
1511 int max = groups.count() - 1;
1512 int mid = 0;
1513 do {
1514 mid = (min + max) / 2;
1515 if (index > groups.at(mid).first) {
1516 min = mid + 1;
1517 } else {
1518 max = mid - 1;
1519 }
1520 } while (groups.at(mid).first != index && min <= max);
1521
1522 header->setData(groups.at(mid).second);
1523 header->setRole(model()->sortRole());
1524 header->setStyleOption(m_styleOption);
1525 header->setScrollOrientation(scrollOrientation());
1526
1527 header->show();
1528 }
1529
1530 void KItemListView::updateGroupHeaderLayout(KItemListWidget* widget)
1531 {
1532 KItemListGroupHeader* header = m_visibleGroups.value(widget);
1533 Q_ASSERT(header);
1534
1535 const int index = widget->index();
1536 const QRectF groupHeaderRect = m_layouter->groupHeaderRect(index);
1537 const QRectF itemRect = m_layouter->itemRect(index);
1538
1539 // The group-header is a child of the itemlist widget. Translate the
1540 // group header position to the relative position.
1541 const QPointF groupHeaderPos(groupHeaderRect.x() - itemRect.x(),
1542 - groupHeaderRect.height());
1543 header->setPos(groupHeaderPos);
1544 header->resize(groupHeaderRect.size());
1545 }
1546
1547 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget* widget)
1548 {
1549 KItemListGroupHeader* header = m_visibleGroups.value(widget);
1550 if (header) {
1551 header->setParentItem(0);
1552 m_groupHeaderCreator->recycle(header);
1553 m_visibleGroups.remove(widget);
1554 }
1555 }
1556
1557 void KItemListView::updateVisibleGroupHeaders()
1558 {
1559 Q_ASSERT(m_grouped);
1560 m_layouter->markAsDirty();
1561
1562 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
1563 while (it.hasNext()) {
1564 it.next();
1565 updateGroupHeaderForWidget(it.value());
1566 }
1567 }
1568
1569 QHash<QByteArray, qreal> KItemListView::headerRolesWidths() const
1570 {
1571 QHash<QByteArray, qreal> rolesWidths;
1572
1573 QHashIterator<QByteArray, QSizeF> it(m_stretchedVisibleRolesSizes);
1574 while (it.hasNext()) {
1575 it.next();
1576 rolesWidths.insert(it.key(), it.value().width());
1577 }
1578
1579 return rolesWidths;
1580 }
1581
1582 void KItemListView::updateVisibleRolesSizes(const KItemRangeList& itemRanges)
1583 {
1584 if (!m_itemSize.isEmpty() || m_useHeaderWidths) {
1585 return;
1586 }
1587
1588 const int itemCount = m_model->count();
1589 int rangesItemCount = 0;
1590 foreach (const KItemRange& range, itemRanges) {
1591 rangesItemCount += range.count;
1592 }
1593
1594 if (itemCount == rangesItemCount) {
1595 m_visibleRolesSizes = visibleRolesSizes(itemRanges);
1596 if (m_header) {
1597 // Assure the the sizes are not smaller than the minimum defined by the header
1598 // TODO: Currently only implemented for a top-aligned header
1599 const qreal minHeaderRoleWidth = m_header->minimumRoleWidth();
1600 QMutableHashIterator<QByteArray, QSizeF> it (m_visibleRolesSizes);
1601 while (it.hasNext()) {
1602 it.next();
1603 const QSizeF& size = it.value();
1604 if (size.width() < minHeaderRoleWidth) {
1605 const QSizeF newSize(minHeaderRoleWidth, size.height());
1606 m_visibleRolesSizes.insert(it.key(), newSize);
1607 }
1608 }
1609 }
1610 } else {
1611 // Only a sub range of the roles need to be determined.
1612 // The chances are good that the sizes of the sub ranges
1613 // already fit into the available sizes and hence no
1614 // expensive update might be required.
1615 bool updateRequired = false;
1616
1617 const QHash<QByteArray, QSizeF> updatedSizes = visibleRolesSizes(itemRanges);
1618 QHashIterator<QByteArray, QSizeF> it(updatedSizes);
1619 while (it.hasNext()) {
1620 it.next();
1621 const QByteArray& role = it.key();
1622 const QSizeF& updatedSize = it.value();
1623 const QSizeF currentSize = m_visibleRolesSizes.value(role);
1624 if (updatedSize.width() > currentSize.width() || updatedSize.height() > currentSize.height()) {
1625 m_visibleRolesSizes.insert(role, updatedSize);
1626 updateRequired = true;
1627 }
1628 }
1629
1630 if (!updateRequired) {
1631 // All the updated sizes are smaller than the current sizes and no change
1632 // of the stretched roles-widths is required
1633 return;
1634 }
1635 }
1636
1637 updateStretchedVisibleRolesSizes();
1638 }
1639
1640 void KItemListView::updateVisibleRolesSizes()
1641 {
1642 const int itemCount = m_model->count();
1643 if (itemCount > 0) {
1644 updateVisibleRolesSizes(KItemRangeList() << KItemRange(0, itemCount));
1645 }
1646 }
1647
1648 void KItemListView::updateStretchedVisibleRolesSizes()
1649 {
1650 if (!m_itemSize.isEmpty() || m_useHeaderWidths) {
1651 return;
1652 }
1653
1654 // Calculate the maximum size of an item by considering the
1655 // visible role sizes and apply them to the layouter. If the
1656 // size does not use the available view-size it the size of the
1657 // first role will get stretched.
1658 m_stretchedVisibleRolesSizes = m_visibleRolesSizes;
1659 const QByteArray role = visibleRoles().first();
1660 QSizeF firstRoleSize = m_stretchedVisibleRolesSizes.value(role);
1661
1662 QSizeF dynamicItemSize = m_itemSize;
1663
1664 if (dynamicItemSize.width() <= 0) {
1665 const qreal requiredWidth = visibleRolesSizesWidthSum();
1666 const qreal availableWidth = size().width();
1667 if (requiredWidth < availableWidth) {
1668 // Stretch the first role to use the whole width for the item
1669 firstRoleSize.rwidth() += availableWidth - requiredWidth;
1670 m_stretchedVisibleRolesSizes.insert(role, firstRoleSize);
1671 }
1672 dynamicItemSize.setWidth(qMax(requiredWidth, availableWidth));
1673 }
1674
1675 if (dynamicItemSize.height() <= 0) {
1676 const qreal requiredHeight = visibleRolesSizesHeightSum();
1677 const qreal availableHeight = size().height();
1678 if (requiredHeight < availableHeight) {
1679 // Stretch the first role to use the whole height for the item
1680 firstRoleSize.rheight() += availableHeight - requiredHeight;
1681 m_stretchedVisibleRolesSizes.insert(role, firstRoleSize);
1682 }
1683 dynamicItemSize.setHeight(qMax(requiredHeight, availableHeight));
1684 }
1685
1686 m_layouter->setItemSize(dynamicItemSize);
1687
1688 if (m_header) {
1689 m_header->setVisibleRolesWidths(headerRolesWidths());
1690 m_header->resize(dynamicItemSize.width(), m_header->size().height());
1691 }
1692
1693 // Update the role sizes for all visible widgets
1694 foreach (KItemListWidget* widget, visibleItemListWidgets()) {
1695 widget->setVisibleRolesSizes(m_stretchedVisibleRolesSizes);
1696 }
1697 }
1698
1699 qreal KItemListView::visibleRolesSizesWidthSum() const
1700 {
1701 qreal widthSum = 0;
1702 QHashIterator<QByteArray, QSizeF> it(m_visibleRolesSizes);
1703 while (it.hasNext()) {
1704 it.next();
1705 widthSum += it.value().width();
1706 }
1707 return widthSum;
1708 }
1709
1710 qreal KItemListView::visibleRolesSizesHeightSum() const
1711 {
1712 qreal heightSum = 0;
1713 QHashIterator<QByteArray, QSizeF> it(m_visibleRolesSizes);
1714 while (it.hasNext()) {
1715 it.next();
1716 heightSum += it.value().height();
1717 }
1718 return heightSum;
1719 }
1720
1721 QRectF KItemListView::headerBoundaries() const
1722 {
1723 return m_header ? m_header->geometry() : QRectF();
1724 }
1725
1726 int KItemListView::calculateAutoScrollingIncrement(int pos, int range, int oldInc)
1727 {
1728 int inc = 0;
1729
1730 const int minSpeed = 4;
1731 const int maxSpeed = 128;
1732 const int speedLimiter = 96;
1733 const int autoScrollBorder = 64;
1734
1735 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
1736 // This assures that the autoscrolling speed grows gradually.
1737 const int incLimiter = 1;
1738
1739 if (pos < autoScrollBorder) {
1740 inc = -minSpeed + qAbs(pos - autoScrollBorder) * (pos - autoScrollBorder) / speedLimiter;
1741 inc = qMax(inc, -maxSpeed);
1742 inc = qMax(inc, oldInc - incLimiter);
1743 } else if (pos > range - autoScrollBorder) {
1744 inc = minSpeed + qAbs(pos - range + autoScrollBorder) * (pos - range + autoScrollBorder) / speedLimiter;
1745 inc = qMin(inc, maxSpeed);
1746 inc = qMin(inc, oldInc + incLimiter);
1747 }
1748
1749 return inc;
1750 }
1751
1752
1753
1754 KItemListCreatorBase::~KItemListCreatorBase()
1755 {
1756 qDeleteAll(m_recycleableWidgets);
1757 qDeleteAll(m_createdWidgets);
1758 }
1759
1760 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget* widget)
1761 {
1762 m_createdWidgets.insert(widget);
1763 }
1764
1765 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget* widget)
1766 {
1767 Q_ASSERT(m_createdWidgets.contains(widget));
1768 m_createdWidgets.remove(widget);
1769
1770 if (m_recycleableWidgets.count() < 100) {
1771 m_recycleableWidgets.append(widget);
1772 widget->setVisible(false);
1773 } else {
1774 delete widget;
1775 }
1776 }
1777
1778 QGraphicsWidget* KItemListCreatorBase::popRecycleableWidget()
1779 {
1780 if (m_recycleableWidgets.isEmpty()) {
1781 return 0;
1782 }
1783
1784 QGraphicsWidget* widget = m_recycleableWidgets.takeLast();
1785 m_createdWidgets.insert(widget);
1786 return widget;
1787 }
1788
1789 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
1790 {
1791 }
1792
1793 void KItemListWidgetCreatorBase::recycle(KItemListWidget* widget)
1794 {
1795 widget->setParentItem(0);
1796 widget->setOpacity(1.0);
1797 pushRecycleableWidget(widget);
1798 }
1799
1800 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
1801 {
1802 }
1803
1804 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader* header)
1805 {
1806 header->setOpacity(1.0);
1807 pushRecycleableWidget(header);
1808 }
1809
1810 #include "kitemlistview.moc"