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