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