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