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