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