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