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