]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kitemlistview.cpp
Calculate all item size hints at once.
[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 <KDebug>
26 #include "kitemlistcontainer.h"
27 #include "kitemlistcontroller.h"
28 #include "kitemlistheader.h"
29 #include "kitemlistselectionmanager.h"
30 #include "kitemlistwidget.h"
31
32 #include "private/kitemlistheaderwidget.h"
33 #include "private/kitemlistrubberband.h"
34 #include "private/kitemlistsizehintresolver.h"
35 #include "private/kitemlistviewlayouter.h"
36 #include "private/kitemlistviewanimation.h"
37
38 #include <QCursor>
39 #include <QGraphicsSceneMouseEvent>
40 #include <QGraphicsView>
41 #include <QPainter>
42 #include <QPropertyAnimation>
43 #include <QStyle>
44 #include <QStyleOptionRubberBand>
45 #include <QTimer>
46
47 #include <algorithm>
48
49 #include "kitemlistviewaccessible.h"
50
51 namespace {
52 // Time in ms until reaching the autoscroll margin triggers
53 // an initial autoscrolling
54 const int InitialAutoScrollDelay = 700;
55
56 // Delay in ms for triggering the next autoscroll
57 const int RepeatingAutoScrollDelay = 1000 / 60;
58 }
59
60 #ifndef QT_NO_ACCESSIBILITY
61 QAccessibleInterface* accessibleInterfaceFactory(const QString &key, QObject *object)
62 {
63 Q_UNUSED(key)
64
65 if (KItemListContainer* container = qobject_cast<KItemListContainer*>(object)) {
66 return new KItemListContainerAccessible(container);
67 } else if (KItemListView* view = qobject_cast<KItemListView*>(object)) {
68 return new KItemListViewAccessible(view);
69 }
70
71 return 0;
72 }
73 #endif
74
75 KItemListView::KItemListView(QGraphicsWidget* parent) :
76 QGraphicsWidget(parent),
77 m_enabledSelectionToggles(false),
78 m_grouped(false),
79 m_supportsItemExpanding(false),
80 m_editingRole(false),
81 m_activeTransactions(0),
82 m_endTransactionAnimationHint(Animation),
83 m_itemSize(),
84 m_controller(0),
85 m_model(0),
86 m_visibleRoles(),
87 m_widgetCreator(0),
88 m_groupHeaderCreator(0),
89 m_styleOption(),
90 m_visibleItems(),
91 m_visibleGroups(),
92 m_visibleCells(),
93 m_sizeHintResolver(0),
94 m_layouter(0),
95 m_animation(0),
96 m_layoutTimer(0),
97 m_oldScrollOffset(0),
98 m_oldMaximumScrollOffset(0),
99 m_oldItemOffset(0),
100 m_oldMaximumItemOffset(0),
101 m_skipAutoScrollForRubberBand(false),
102 m_rubberBand(0),
103 m_mousePos(),
104 m_autoScrollIncrement(0),
105 m_autoScrollTimer(0),
106 m_header(0),
107 m_headerWidget(0),
108 m_dropIndicator()
109 {
110 setAcceptHoverEvents(true);
111
112 m_sizeHintResolver = new KItemListSizeHintResolver(this);
113
114 m_layouter = new KItemListViewLayouter(this);
115 m_layouter->setSizeHintResolver(m_sizeHintResolver);
116
117 m_animation = new KItemListViewAnimation(this);
118 connect(m_animation, SIGNAL(finished(QGraphicsWidget*,KItemListViewAnimation::AnimationType)),
119 this, SLOT(slotAnimationFinished(QGraphicsWidget*,KItemListViewAnimation::AnimationType)));
120
121 m_layoutTimer = new QTimer(this);
122 m_layoutTimer->setInterval(300);
123 m_layoutTimer->setSingleShot(true);
124 connect(m_layoutTimer, SIGNAL(timeout()), this, SLOT(slotLayoutTimerFinished()));
125
126 m_rubberBand = new KItemListRubberBand(this);
127 connect(m_rubberBand, SIGNAL(activationChanged(bool)), this, SLOT(slotRubberBandActivationChanged(bool)));
128
129 m_headerWidget = new KItemListHeaderWidget(this);
130 m_headerWidget->setVisible(false);
131
132 m_header = new KItemListHeader(this);
133
134 #ifndef QT_NO_ACCESSIBILITY
135 QAccessible::installFactory(accessibleInterfaceFactory);
136 #endif
137
138 }
139
140 KItemListView::~KItemListView()
141 {
142 // The group headers are children of the widgets created by
143 // widgetCreator(). So it is mandatory to delete the group headers
144 // first.
145 delete m_groupHeaderCreator;
146 m_groupHeaderCreator = 0;
147
148 delete m_widgetCreator;
149 m_widgetCreator = 0;
150
151 delete m_sizeHintResolver;
152 m_sizeHintResolver = 0;
153 }
154
155 void KItemListView::setScrollOffset(qreal offset)
156 {
157 if (offset < 0) {
158 offset = 0;
159 }
160
161 const qreal previousOffset = m_layouter->scrollOffset();
162 if (offset == previousOffset) {
163 return;
164 }
165
166 m_layouter->setScrollOffset(offset);
167 m_animation->setScrollOffset(offset);
168
169 // Don't check whether the m_layoutTimer is active: Changing the
170 // scroll offset must always trigger a synchronous layout, otherwise
171 // the smooth-scrolling might get jerky.
172 doLayout(NoAnimation);
173 onScrollOffsetChanged(offset, previousOffset);
174 }
175
176 qreal KItemListView::scrollOffset() const
177 {
178 return m_layouter->scrollOffset();
179 }
180
181 qreal KItemListView::maximumScrollOffset() const
182 {
183 return m_layouter->maximumScrollOffset();
184 }
185
186 void KItemListView::setItemOffset(qreal offset)
187 {
188 if (m_layouter->itemOffset() == offset) {
189 return;
190 }
191
192 m_layouter->setItemOffset(offset);
193 if (m_headerWidget->isVisible()) {
194 m_headerWidget->setOffset(offset);
195 }
196
197 // Don't check whether the m_layoutTimer is active: Changing the
198 // item offset must always trigger a synchronous layout, otherwise
199 // the smooth-scrolling might get jerky.
200 doLayout(NoAnimation);
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 int KItemListView::maximumVisibleItems() const
214 {
215 return m_layouter->maximumVisibleItems();
216 }
217
218 void KItemListView::setVisibleRoles(const QList<QByteArray>& roles)
219 {
220 const QList<QByteArray> previousRoles = m_visibleRoles;
221 m_visibleRoles = roles;
222 onVisibleRolesChanged(roles, previousRoles);
223
224 m_sizeHintResolver->clearCache();
225 m_layouter->markAsDirty();
226
227 if (m_itemSize.isEmpty()) {
228 m_headerWidget->setColumns(roles);
229 updatePreferredColumnWidths();
230 if (!m_headerWidget->automaticColumnResizing()) {
231 // The column-width of new roles are still 0. Apply the preferred
232 // column-width as default with.
233 foreach (const QByteArray& role, m_visibleRoles) {
234 if (m_headerWidget->columnWidth(role) == 0) {
235 const qreal width = m_headerWidget->preferredColumnWidth(role);
236 m_headerWidget->setColumnWidth(role, width);
237 }
238 }
239
240 applyColumnWidthsFromHeader();
241 }
242 }
243
244 const bool alternateBackgroundsChanged = m_itemSize.isEmpty() &&
245 ((roles.count() > 1 && previousRoles.count() <= 1) ||
246 (roles.count() <= 1 && previousRoles.count() > 1));
247
248 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
249 while (it.hasNext()) {
250 it.next();
251 KItemListWidget* widget = it.value();
252 widget->setVisibleRoles(roles);
253 if (alternateBackgroundsChanged) {
254 updateAlternateBackgroundForWidget(widget);
255 }
256 }
257
258 doLayout(NoAnimation);
259 }
260
261 QList<QByteArray> KItemListView::visibleRoles() const
262 {
263 return m_visibleRoles;
264 }
265
266 void KItemListView::setAutoScroll(bool enabled)
267 {
268 if (enabled && !m_autoScrollTimer) {
269 m_autoScrollTimer = new QTimer(this);
270 m_autoScrollTimer->setSingleShot(true);
271 connect(m_autoScrollTimer, SIGNAL(timeout()), this, SLOT(triggerAutoScrolling()));
272 m_autoScrollTimer->start(InitialAutoScrollDelay);
273 } else if (!enabled && m_autoScrollTimer) {
274 delete m_autoScrollTimer;
275 m_autoScrollTimer = 0;
276 }
277 }
278
279 bool KItemListView::autoScroll() const
280 {
281 return m_autoScrollTimer != 0;
282 }
283
284 void KItemListView::setEnabledSelectionToggles(bool enabled)
285 {
286 if (m_enabledSelectionToggles != enabled) {
287 m_enabledSelectionToggles = enabled;
288
289 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
290 while (it.hasNext()) {
291 it.next();
292 it.value()->setEnabledSelectionToggle(enabled);
293 }
294 }
295 }
296
297 bool KItemListView::enabledSelectionToggles() const
298 {
299 return m_enabledSelectionToggles;
300 }
301
302 KItemListController* KItemListView::controller() const
303 {
304 return m_controller;
305 }
306
307 KItemModelBase* KItemListView::model() const
308 {
309 return m_model;
310 }
311
312 void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase* widgetCreator)
313 {
314 if (m_widgetCreator) {
315 delete m_widgetCreator;
316 }
317 m_widgetCreator = widgetCreator;
318 }
319
320 KItemListWidgetCreatorBase* KItemListView::widgetCreator() const
321 {
322 if (!m_widgetCreator) {
323 m_widgetCreator = defaultWidgetCreator();
324 }
325 return m_widgetCreator;
326 }
327
328 void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase* groupHeaderCreator)
329 {
330 if (m_groupHeaderCreator) {
331 delete m_groupHeaderCreator;
332 }
333 m_groupHeaderCreator = groupHeaderCreator;
334 }
335
336 KItemListGroupHeaderCreatorBase* KItemListView::groupHeaderCreator() const
337 {
338 if (!m_groupHeaderCreator) {
339 m_groupHeaderCreator = defaultGroupHeaderCreator();
340 }
341 return m_groupHeaderCreator;
342 }
343
344 QSizeF KItemListView::itemSize() const
345 {
346 return m_itemSize;
347 }
348
349 const KItemListStyleOption& KItemListView::styleOption() const
350 {
351 return m_styleOption;
352 }
353
354 void KItemListView::setGeometry(const QRectF& rect)
355 {
356 QGraphicsWidget::setGeometry(rect);
357
358 if (!m_model) {
359 return;
360 }
361
362 const QSizeF newSize = rect.size();
363 if (m_itemSize.isEmpty()) {
364 m_headerWidget->resize(rect.width(), m_headerWidget->size().height());
365 if (m_headerWidget->automaticColumnResizing()) {
366 applyAutomaticColumnWidths();
367 } else {
368 const qreal requiredWidth = columnWidthsSum();
369 const QSizeF dynamicItemSize(qMax(newSize.width(), requiredWidth),
370 m_itemSize.height());
371 m_layouter->setItemSize(dynamicItemSize);
372 }
373
374 // Triggering a synchronous layout is fine from a performance point of view,
375 // as with dynamic item sizes no moving animation must be done.
376 m_layouter->setSize(newSize);
377 doLayout(NoAnimation);
378 } else {
379 const bool animate = !changesItemGridLayout(newSize,
380 m_layouter->itemSize(),
381 m_layouter->itemMargin());
382 m_layouter->setSize(newSize);
383
384 if (animate) {
385 // Trigger an asynchronous relayout with m_layoutTimer to prevent
386 // performance bottlenecks. If the timer is exceeded, an animated layout
387 // will be triggered.
388 if (!m_layoutTimer->isActive()) {
389 m_layoutTimer->start();
390 }
391 } else {
392 m_layoutTimer->stop();
393 doLayout(NoAnimation);
394 }
395 }
396 }
397
398 qreal KItemListView::verticalPageStep() const
399 {
400 qreal headerHeight = 0;
401 if (m_headerWidget->isVisible()) {
402 headerHeight = m_headerWidget->size().height();
403 }
404 return size().height() - headerHeight;
405 }
406
407 int KItemListView::itemAt(const QPointF& pos) const
408 {
409 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
410 while (it.hasNext()) {
411 it.next();
412
413 const KItemListWidget* widget = it.value();
414 const QPointF mappedPos = widget->mapFromItem(this, pos);
415 if (widget->contains(mappedPos)) {
416 return it.key();
417 }
418 }
419
420 return -1;
421 }
422
423 bool KItemListView::isAboveSelectionToggle(int index, const QPointF& pos) const
424 {
425 if (!m_enabledSelectionToggles) {
426 return false;
427 }
428
429 const KItemListWidget* widget = m_visibleItems.value(index);
430 if (widget) {
431 const QRectF selectionToggleRect = widget->selectionToggleRect();
432 if (!selectionToggleRect.isEmpty()) {
433 const QPointF mappedPos = widget->mapFromItem(this, pos);
434 return selectionToggleRect.contains(mappedPos);
435 }
436 }
437 return false;
438 }
439
440 bool KItemListView::isAboveExpansionToggle(int index, const QPointF& pos) const
441 {
442 const KItemListWidget* widget = m_visibleItems.value(index);
443 if (widget) {
444 const QRectF expansionToggleRect = widget->expansionToggleRect();
445 if (!expansionToggleRect.isEmpty()) {
446 const QPointF mappedPos = widget->mapFromItem(this, pos);
447 return expansionToggleRect.contains(mappedPos);
448 }
449 }
450 return false;
451 }
452
453 int KItemListView::firstVisibleIndex() const
454 {
455 return m_layouter->firstVisibleIndex();
456 }
457
458 int KItemListView::lastVisibleIndex() const
459 {
460 return m_layouter->lastVisibleIndex();
461 }
462
463 void KItemListView::calculateItemSizeHints(QVector<QSizeF>& sizeHints) const
464 {
465 widgetCreator()->calculateItemSizeHints(sizeHints, this);
466 }
467
468 void KItemListView::setSupportsItemExpanding(bool supportsExpanding)
469 {
470 if (m_supportsItemExpanding != supportsExpanding) {
471 m_supportsItemExpanding = supportsExpanding;
472 updateSiblingsInformation();
473 onSupportsItemExpandingChanged(supportsExpanding);
474 }
475 }
476
477 bool KItemListView::supportsItemExpanding() const
478 {
479 return m_supportsItemExpanding;
480 }
481
482 QRectF KItemListView::itemRect(int index) const
483 {
484 return m_layouter->itemRect(index);
485 }
486
487 QRectF KItemListView::itemContextRect(int index) const
488 {
489 QRectF contextRect;
490
491 const KItemListWidget* widget = m_visibleItems.value(index);
492 if (widget) {
493 contextRect = widget->iconRect() | widget->textRect();
494 contextRect.translate(itemRect(index).topLeft());
495 }
496
497 return contextRect;
498 }
499
500 void KItemListView::scrollToItem(int index)
501 {
502 QRectF viewGeometry = geometry();
503 if (m_headerWidget->isVisible()) {
504 const qreal headerHeight = m_headerWidget->size().height();
505 viewGeometry.adjust(0, headerHeight, 0, 0);
506 }
507 QRectF currentRect = itemRect(index);
508
509 // Fix for Bug 311099 - View the underscore when using Ctrl + PagDown
510 currentRect.adjust(-m_styleOption.horizontalMargin, -m_styleOption.verticalMargin,
511 m_styleOption.horizontalMargin, m_styleOption.verticalMargin);
512
513 if (!viewGeometry.contains(currentRect)) {
514 qreal newOffset = scrollOffset();
515 if (scrollOrientation() == Qt::Vertical) {
516 if (currentRect.top() < viewGeometry.top()) {
517 newOffset += currentRect.top() - viewGeometry.top();
518 } else if (currentRect.bottom() > viewGeometry.bottom()) {
519 newOffset += currentRect.bottom() - viewGeometry.bottom();
520 }
521 } else {
522 if (currentRect.left() < viewGeometry.left()) {
523 newOffset += currentRect.left() - viewGeometry.left();
524 } else if (currentRect.right() > viewGeometry.right()) {
525 newOffset += currentRect.right() - viewGeometry.right();
526 }
527 }
528
529 if (newOffset != scrollOffset()) {
530 emit scrollTo(newOffset);
531 }
532 }
533 }
534
535 void KItemListView::beginTransaction()
536 {
537 ++m_activeTransactions;
538 if (m_activeTransactions == 1) {
539 onTransactionBegin();
540 }
541 }
542
543 void KItemListView::endTransaction()
544 {
545 --m_activeTransactions;
546 if (m_activeTransactions < 0) {
547 m_activeTransactions = 0;
548 kWarning() << "Mismatch between beginTransaction()/endTransaction()";
549 }
550
551 if (m_activeTransactions == 0) {
552 onTransactionEnd();
553 doLayout(m_endTransactionAnimationHint);
554 m_endTransactionAnimationHint = Animation;
555 }
556 }
557
558 bool KItemListView::isTransactionActive() const
559 {
560 return m_activeTransactions > 0;
561 }
562
563 void KItemListView::setHeaderVisible(bool visible)
564 {
565 if (visible && !m_headerWidget->isVisible()) {
566 QStyleOptionHeader option;
567 const QSize headerSize = style()->sizeFromContents(QStyle::CT_HeaderSection,
568 &option, QSize());
569
570 m_headerWidget->setPos(0, 0);
571 m_headerWidget->resize(size().width(), headerSize.height());
572 m_headerWidget->setModel(m_model);
573 m_headerWidget->setColumns(m_visibleRoles);
574 m_headerWidget->setZValue(1);
575
576 connect(m_headerWidget, SIGNAL(columnWidthChanged(QByteArray,qreal,qreal)),
577 this, SLOT(slotHeaderColumnWidthChanged(QByteArray,qreal,qreal)));
578 connect(m_headerWidget, SIGNAL(columnMoved(QByteArray,int,int)),
579 this, SLOT(slotHeaderColumnMoved(QByteArray,int,int)));
580 connect(m_headerWidget, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)),
581 this, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)));
582 connect(m_headerWidget, SIGNAL(sortRoleChanged(QByteArray,QByteArray)),
583 this, SIGNAL(sortRoleChanged(QByteArray,QByteArray)));
584
585 m_layouter->setHeaderHeight(headerSize.height());
586 m_headerWidget->setVisible(true);
587 } else if (!visible && m_headerWidget->isVisible()) {
588 disconnect(m_headerWidget, SIGNAL(columnWidthChanged(QByteArray,qreal,qreal)),
589 this, SLOT(slotHeaderColumnWidthChanged(QByteArray,qreal,qreal)));
590 disconnect(m_headerWidget, SIGNAL(columnMoved(QByteArray,int,int)),
591 this, SLOT(slotHeaderColumnMoved(QByteArray,int,int)));
592 disconnect(m_headerWidget, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)),
593 this, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)));
594 disconnect(m_headerWidget, SIGNAL(sortRoleChanged(QByteArray,QByteArray)),
595 this, SIGNAL(sortRoleChanged(QByteArray,QByteArray)));
596
597 m_layouter->setHeaderHeight(0);
598 m_headerWidget->setVisible(false);
599 }
600 }
601
602 bool KItemListView::isHeaderVisible() const
603 {
604 return m_headerWidget->isVisible();
605 }
606
607 KItemListHeader* KItemListView::header() const
608 {
609 return m_header;
610 }
611
612 QPixmap KItemListView::createDragPixmap(const KItemSet& indexes) const
613 {
614 QPixmap pixmap;
615
616 if (indexes.count() == 1) {
617 KItemListWidget* item = m_visibleItems.value(indexes.first());
618 QGraphicsView* graphicsView = scene()->views()[0];
619 if (item && graphicsView) {
620 pixmap = item->createDragPixmap(0, graphicsView);
621 }
622 } else {
623 // TODO: Not implemented yet. Probably extend the interface
624 // from KItemListWidget::createDragPixmap() to return a pixmap
625 // that can be used for multiple indexes.
626 }
627
628 return pixmap;
629 }
630
631 void KItemListView::editRole(int index, const QByteArray& role)
632 {
633 KItemListWidget* widget = m_visibleItems.value(index);
634 if (!widget || m_editingRole) {
635 return;
636 }
637
638 m_editingRole = true;
639 widget->setEditedRole(role);
640
641 connect(widget, SIGNAL(roleEditingCanceled(int,QByteArray,QVariant)),
642 this, SLOT(slotRoleEditingCanceled(int,QByteArray,QVariant)));
643 connect(widget, SIGNAL(roleEditingFinished(int,QByteArray,QVariant)),
644 this, SLOT(slotRoleEditingFinished(int,QByteArray,QVariant)));
645 }
646
647 void KItemListView::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
648 {
649 QGraphicsWidget::paint(painter, option, widget);
650
651 if (m_rubberBand->isActive()) {
652 QRectF rubberBandRect = QRectF(m_rubberBand->startPosition(),
653 m_rubberBand->endPosition()).normalized();
654
655 const QPointF topLeft = rubberBandRect.topLeft();
656 if (scrollOrientation() == Qt::Vertical) {
657 rubberBandRect.moveTo(topLeft.x(), topLeft.y() - scrollOffset());
658 } else {
659 rubberBandRect.moveTo(topLeft.x() - scrollOffset(), topLeft.y());
660 }
661
662 QStyleOptionRubberBand opt;
663 opt.initFrom(widget);
664 opt.shape = QRubberBand::Rectangle;
665 opt.opaque = false;
666 opt.rect = rubberBandRect.toRect();
667 style()->drawControl(QStyle::CE_RubberBand, &opt, painter);
668 }
669
670 if (!m_dropIndicator.isEmpty()) {
671 const QRectF r = m_dropIndicator.toRect();
672
673 QColor color = palette().brush(QPalette::Normal, QPalette::Highlight).color();
674 painter->setPen(color);
675
676 // TODO: The following implementation works only for a vertical scroll-orientation
677 // and assumes a height of the m_draggingInsertIndicator of 1.
678 Q_ASSERT(r.height() == 1);
679 painter->drawLine(r.left() + 1, r.top(), r.right() - 1, r.top());
680
681 color.setAlpha(128);
682 painter->setPen(color);
683 painter->drawRect(r.left(), r.top() - 1, r.width() - 1, 2);
684 }
685 }
686
687 QVariant KItemListView::itemChange(GraphicsItemChange change, const QVariant &value)
688 {
689 if (change == QGraphicsItem::ItemSceneHasChanged && scene()) {
690 if (!scene()->views().isEmpty()) {
691 m_styleOption.palette = scene()->views().at(0)->palette();
692 }
693 }
694 return QGraphicsItem::itemChange(change, value);
695 }
696
697 void KItemListView::setItemSize(const QSizeF& size)
698 {
699 const QSizeF previousSize = m_itemSize;
700 if (size == previousSize) {
701 return;
702 }
703
704 // Skip animations when the number of rows or columns
705 // are changed in the grid layout. Although the animation
706 // engine can handle this usecase, it looks obtrusive.
707 const bool animate = !changesItemGridLayout(m_layouter->size(),
708 size,
709 m_layouter->itemMargin());
710
711 const bool alternateBackgroundsChanged = (m_visibleRoles.count() > 1) &&
712 (( m_itemSize.isEmpty() && !size.isEmpty()) ||
713 (!m_itemSize.isEmpty() && size.isEmpty()));
714
715 m_itemSize = size;
716
717 if (alternateBackgroundsChanged) {
718 // For an empty item size alternate backgrounds are drawn if more than
719 // one role is shown. Assure that the backgrounds for visible items are
720 // updated when changing the size in this context.
721 updateAlternateBackgrounds();
722 }
723
724 if (size.isEmpty()) {
725 if (m_headerWidget->automaticColumnResizing()) {
726 updatePreferredColumnWidths();
727 } else {
728 // Only apply the changed height and respect the header widths
729 // set by the user
730 const qreal currentWidth = m_layouter->itemSize().width();
731 const QSizeF newSize(currentWidth, size.height());
732 m_layouter->setItemSize(newSize);
733 }
734 } else {
735 m_layouter->setItemSize(size);
736 }
737
738 m_sizeHintResolver->clearCache();
739 doLayout(animate ? Animation : NoAnimation);
740 onItemSizeChanged(size, previousSize);
741 }
742
743 void KItemListView::setStyleOption(const KItemListStyleOption& option)
744 {
745 const KItemListStyleOption previousOption = m_styleOption;
746 m_styleOption = option;
747
748 bool animate = true;
749 const QSizeF margin(option.horizontalMargin, option.verticalMargin);
750 if (margin != m_layouter->itemMargin()) {
751 // Skip animations when the number of rows or columns
752 // are changed in the grid layout. Although the animation
753 // engine can handle this usecase, it looks obtrusive.
754 animate = !changesItemGridLayout(m_layouter->size(),
755 m_layouter->itemSize(),
756 margin);
757 m_layouter->setItemMargin(margin);
758 }
759
760 if (m_grouped) {
761 updateGroupHeaderHeight();
762 }
763
764 if (animate && previousOption.maxTextSize != option.maxTextSize) {
765 // Animating a change of the maximum text size just results in expensive
766 // temporary eliding and clipping operations and does not look good visually.
767 animate = false;
768 }
769
770 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
771 while (it.hasNext()) {
772 it.next();
773 it.value()->setStyleOption(option);
774 }
775
776 m_sizeHintResolver->clearCache();
777 m_layouter->markAsDirty();
778 doLayout(animate ? Animation : NoAnimation);
779
780 if (m_itemSize.isEmpty()) {
781 updatePreferredColumnWidths();
782 }
783
784 onStyleOptionChanged(option, previousOption);
785 }
786
787 void KItemListView::setScrollOrientation(Qt::Orientation orientation)
788 {
789 const Qt::Orientation previousOrientation = m_layouter->scrollOrientation();
790 if (orientation == previousOrientation) {
791 return;
792 }
793
794 m_layouter->setScrollOrientation(orientation);
795 m_animation->setScrollOrientation(orientation);
796 m_sizeHintResolver->clearCache();
797
798 if (m_grouped) {
799 QMutableHashIterator<KItemListWidget*, KItemListGroupHeader*> it (m_visibleGroups);
800 while (it.hasNext()) {
801 it.next();
802 it.value()->setScrollOrientation(orientation);
803 }
804 updateGroupHeaderHeight();
805
806 }
807
808 doLayout(NoAnimation);
809
810 onScrollOrientationChanged(orientation, previousOrientation);
811 emit scrollOrientationChanged(orientation, previousOrientation);
812 }
813
814 Qt::Orientation KItemListView::scrollOrientation() const
815 {
816 return m_layouter->scrollOrientation();
817 }
818
819 KItemListWidgetCreatorBase* KItemListView::defaultWidgetCreator() const
820 {
821 return 0;
822 }
823
824 KItemListGroupHeaderCreatorBase* KItemListView::defaultGroupHeaderCreator() const
825 {
826 return 0;
827 }
828
829 void KItemListView::initializeItemListWidget(KItemListWidget* item)
830 {
831 Q_UNUSED(item);
832 }
833
834 bool KItemListView::itemSizeHintUpdateRequired(const QSet<QByteArray>& changedRoles) const
835 {
836 Q_UNUSED(changedRoles);
837 return true;
838 }
839
840 void KItemListView::onControllerChanged(KItemListController* current, KItemListController* previous)
841 {
842 Q_UNUSED(current);
843 Q_UNUSED(previous);
844 }
845
846 void KItemListView::onModelChanged(KItemModelBase* current, KItemModelBase* previous)
847 {
848 Q_UNUSED(current);
849 Q_UNUSED(previous);
850 }
851
852 void KItemListView::onScrollOrientationChanged(Qt::Orientation current, Qt::Orientation previous)
853 {
854 Q_UNUSED(current);
855 Q_UNUSED(previous);
856 }
857
858 void KItemListView::onItemSizeChanged(const QSizeF& current, const QSizeF& previous)
859 {
860 Q_UNUSED(current);
861 Q_UNUSED(previous);
862 }
863
864 void KItemListView::onScrollOffsetChanged(qreal current, qreal previous)
865 {
866 Q_UNUSED(current);
867 Q_UNUSED(previous);
868 }
869
870 void KItemListView::onVisibleRolesChanged(const QList<QByteArray>& current, const QList<QByteArray>& previous)
871 {
872 Q_UNUSED(current);
873 Q_UNUSED(previous);
874 }
875
876 void KItemListView::onStyleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous)
877 {
878 Q_UNUSED(current);
879 Q_UNUSED(previous);
880 }
881
882 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding)
883 {
884 Q_UNUSED(supportsExpanding);
885 }
886
887 void KItemListView::onTransactionBegin()
888 {
889 }
890
891 void KItemListView::onTransactionEnd()
892 {
893 }
894
895 bool KItemListView::event(QEvent* event)
896 {
897 // Forward all events to the controller and handle them there
898 if (!m_editingRole && m_controller && m_controller->processEvent(event, transform())) {
899 event->accept();
900 return true;
901 }
902 return QGraphicsWidget::event(event);
903 }
904
905 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent* event)
906 {
907 m_mousePos = transform().map(event->pos());
908 event->accept();
909 }
910
911 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
912 {
913 QGraphicsWidget::mouseMoveEvent(event);
914
915 m_mousePos = transform().map(event->pos());
916 if (m_autoScrollTimer && !m_autoScrollTimer->isActive()) {
917 m_autoScrollTimer->start(InitialAutoScrollDelay);
918 }
919 }
920
921 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent* event)
922 {
923 event->setAccepted(true);
924 setAutoScroll(true);
925 }
926
927 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent *event)
928 {
929 QGraphicsWidget::dragMoveEvent(event);
930
931 m_mousePos = transform().map(event->pos());
932 if (m_autoScrollTimer && !m_autoScrollTimer->isActive()) {
933 m_autoScrollTimer->start(InitialAutoScrollDelay);
934 }
935 }
936
937 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
938 {
939 QGraphicsWidget::dragLeaveEvent(event);
940 setAutoScroll(false);
941 }
942
943 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent* event)
944 {
945 QGraphicsWidget::dropEvent(event);
946 setAutoScroll(false);
947 }
948
949 QList<KItemListWidget*> KItemListView::visibleItemListWidgets() const
950 {
951 return m_visibleItems.values();
952 }
953
954 void KItemListView::slotItemsInserted(const KItemRangeList& itemRanges)
955 {
956 if (m_itemSize.isEmpty()) {
957 updatePreferredColumnWidths(itemRanges);
958 }
959
960 const bool hasMultipleRanges = (itemRanges.count() > 1);
961 if (hasMultipleRanges) {
962 beginTransaction();
963 }
964
965 m_layouter->markAsDirty();
966
967 m_sizeHintResolver->itemsInserted(itemRanges);
968
969 int previouslyInsertedCount = 0;
970 foreach (const KItemRange& range, itemRanges) {
971 // range.index is related to the model before anything has been inserted.
972 // As in each loop the current item-range gets inserted the index must
973 // be increased by the already previously inserted items.
974 const int index = range.index + previouslyInsertedCount;
975 const int count = range.count;
976 if (index < 0 || count <= 0) {
977 kWarning() << "Invalid item range (index:" << index << ", count:" << count << ")";
978 continue;
979 }
980 previouslyInsertedCount += count;
981
982 // Determine which visible items must be moved
983 QList<int> itemsToMove;
984 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
985 while (it.hasNext()) {
986 it.next();
987 const int visibleItemIndex = it.key();
988 if (visibleItemIndex >= index) {
989 itemsToMove.append(visibleItemIndex);
990 }
991 }
992
993 // Update the indexes of all KItemListWidget instances that are located
994 // after the inserted items. It is important to adjust the indexes in the order
995 // from the highest index to the lowest index to prevent overlaps when setting the new index.
996 qSort(itemsToMove);
997 for (int i = itemsToMove.count() - 1; i >= 0; --i) {
998 KItemListWidget* widget = m_visibleItems.value(itemsToMove[i]);
999 Q_ASSERT(widget);
1000 const int newIndex = widget->index() + count;
1001 if (hasMultipleRanges) {
1002 setWidgetIndex(widget, newIndex);
1003 } else {
1004 // Try to animate the moving of the item
1005 moveWidgetToIndex(widget, newIndex);
1006 }
1007 }
1008
1009 if (m_model->count() == count && m_activeTransactions == 0) {
1010 // Check whether a scrollbar is required to show the inserted items. In this case
1011 // the size of the layouter will be decreased before calling doLayout(): This prevents
1012 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
1013 const bool verticalScrollOrientation = (scrollOrientation() == Qt::Vertical);
1014 const bool decreaseLayouterSize = ( verticalScrollOrientation && maximumScrollOffset() > size().height()) ||
1015 (!verticalScrollOrientation && maximumScrollOffset() > size().width());
1016 if (decreaseLayouterSize) {
1017 const int scrollBarExtent = style()->pixelMetric(QStyle::PM_ScrollBarExtent);
1018 QSizeF layouterSize = m_layouter->size();
1019 if (verticalScrollOrientation) {
1020 layouterSize.rwidth() -= scrollBarExtent;
1021 } else {
1022 layouterSize.rheight() -= scrollBarExtent;
1023 }
1024 m_layouter->setSize(layouterSize);
1025 }
1026 }
1027
1028 if (!hasMultipleRanges) {
1029 doLayout(animateChangedItemCount(count) ? Animation : NoAnimation, index, count);
1030 updateSiblingsInformation();
1031 }
1032 }
1033
1034 if (m_controller) {
1035 m_controller->selectionManager()->itemsInserted(itemRanges);
1036 }
1037
1038 if (hasMultipleRanges) {
1039 m_endTransactionAnimationHint = NoAnimation;
1040 endTransaction();
1041
1042 updateSiblingsInformation();
1043 }
1044
1045 if (m_grouped && (hasMultipleRanges || itemRanges.first().count < m_model->count())) {
1046 // In case if items of the same group have been inserted before an item that
1047 // currently represents the first item of the group, the group header of
1048 // this item must be removed.
1049 updateVisibleGroupHeaders();
1050 }
1051
1052 if (useAlternateBackgrounds()) {
1053 updateAlternateBackgrounds();
1054 }
1055 }
1056
1057 void KItemListView::slotItemsRemoved(const KItemRangeList& itemRanges)
1058 {
1059 if (m_itemSize.isEmpty()) {
1060 // Don't pass the item-range: The preferred column-widths of
1061 // all items must be adjusted when removing items.
1062 updatePreferredColumnWidths();
1063 }
1064
1065 const bool hasMultipleRanges = (itemRanges.count() > 1);
1066 if (hasMultipleRanges) {
1067 beginTransaction();
1068 }
1069
1070 m_layouter->markAsDirty();
1071
1072 m_sizeHintResolver->itemsRemoved(itemRanges);
1073
1074 for (int i = itemRanges.count() - 1; i >= 0; --i) {
1075 const KItemRange& range = itemRanges[i];
1076 const int index = range.index;
1077 const int count = range.count;
1078 if (index < 0 || count <= 0) {
1079 kWarning() << "Invalid item range (index:" << index << ", count:" << count << ")";
1080 continue;
1081 }
1082
1083 const int firstRemovedIndex = index;
1084 const int lastRemovedIndex = index + count - 1;
1085
1086 // Remeber which items have to be moved because they are behind the removed range.
1087 QVector<int> itemsToMove;
1088
1089 // Remove all KItemListWidget instances that got deleted
1090 foreach (KItemListWidget* widget, m_visibleItems) {
1091 const int i = widget->index();
1092 if (i < firstRemovedIndex) {
1093 continue;
1094 } else if (i > lastRemovedIndex) {
1095 itemsToMove.append(i);
1096 continue;
1097 }
1098
1099 m_animation->stop(widget);
1100 // Stopping the animation might lead to recycling the widget if
1101 // it is invisible (see slotAnimationFinished()).
1102 // Check again whether it is still visible:
1103 if (!m_visibleItems.contains(i)) {
1104 continue;
1105 }
1106
1107 if (m_model->count() == 0 || hasMultipleRanges || !animateChangedItemCount(count)) {
1108 // Remove the widget without animation
1109 recycleWidget(widget);
1110 } else {
1111 // Animate the removing of the items. Special case: When removing an item there
1112 // is no valid model index available anymore. For the
1113 // remove-animation the item gets removed from m_visibleItems but the widget
1114 // will stay alive until the animation has been finished and will
1115 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1116 m_visibleItems.remove(i);
1117 widget->setIndex(-1);
1118 m_animation->start(widget, KItemListViewAnimation::DeleteAnimation);
1119 }
1120 }
1121
1122 // Update the indexes of all KItemListWidget instances that are located
1123 // after the deleted items. It is important to update them in ascending
1124 // order to prevent overlaps when setting the new index.
1125 std::sort(itemsToMove.begin(), itemsToMove.end());
1126 foreach (int i, itemsToMove) {
1127 KItemListWidget* widget = m_visibleItems.value(i);
1128 Q_ASSERT(widget);
1129 const int newIndex = i - count;
1130 if (hasMultipleRanges) {
1131 setWidgetIndex(widget, newIndex);
1132 } else {
1133 // Try to animate the moving of the item
1134 moveWidgetToIndex(widget, newIndex);
1135 }
1136 }
1137
1138 if (!hasMultipleRanges) {
1139 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1140 // assumes an updated geometry. If items are removed during an active transaction,
1141 // the transaction will be temporary deactivated so that doLayout() triggers a
1142 // geometry update if necessary.
1143 const int activeTransactions = m_activeTransactions;
1144 m_activeTransactions = 0;
1145 doLayout(animateChangedItemCount(count) ? Animation : NoAnimation, index, -count);
1146 m_activeTransactions = activeTransactions;
1147 updateSiblingsInformation();
1148 }
1149 }
1150
1151 if (m_controller) {
1152 m_controller->selectionManager()->itemsRemoved(itemRanges);
1153 }
1154
1155 if (hasMultipleRanges) {
1156 m_endTransactionAnimationHint = NoAnimation;
1157 endTransaction();
1158 updateSiblingsInformation();
1159 }
1160
1161 if (m_grouped && (hasMultipleRanges || m_model->count() > 0)) {
1162 // In case if the first item of a group has been removed, the group header
1163 // must be applied to the next visible item.
1164 updateVisibleGroupHeaders();
1165 }
1166
1167 if (useAlternateBackgrounds()) {
1168 updateAlternateBackgrounds();
1169 }
1170 }
1171
1172 void KItemListView::slotItemsMoved(const KItemRange& itemRange, const QList<int>& movedToIndexes)
1173 {
1174 m_sizeHintResolver->itemsMoved(itemRange, movedToIndexes);
1175 m_layouter->markAsDirty();
1176
1177 if (m_controller) {
1178 m_controller->selectionManager()->itemsMoved(itemRange, movedToIndexes);
1179 }
1180
1181 const int firstVisibleMovedIndex = qMax(firstVisibleIndex(), itemRange.index);
1182 const int lastVisibleMovedIndex = qMin(lastVisibleIndex(), itemRange.index + itemRange.count - 1);
1183
1184 for (int index = firstVisibleMovedIndex; index <= lastVisibleMovedIndex; ++index) {
1185 KItemListWidget* widget = m_visibleItems.value(index);
1186 if (widget) {
1187 updateWidgetProperties(widget, index);
1188 initializeItemListWidget(widget);
1189 }
1190 }
1191
1192 doLayout(NoAnimation);
1193 updateSiblingsInformation();
1194 }
1195
1196 void KItemListView::slotItemsChanged(const KItemRangeList& itemRanges,
1197 const QSet<QByteArray>& roles)
1198 {
1199 const bool updateSizeHints = itemSizeHintUpdateRequired(roles);
1200 if (updateSizeHints && m_itemSize.isEmpty()) {
1201 updatePreferredColumnWidths(itemRanges);
1202 }
1203
1204 foreach (const KItemRange& itemRange, itemRanges) {
1205 const int index = itemRange.index;
1206 const int count = itemRange.count;
1207
1208 if (updateSizeHints) {
1209 m_sizeHintResolver->itemsChanged(index, count, roles);
1210 m_layouter->markAsDirty();
1211
1212 if (!m_layoutTimer->isActive()) {
1213 m_layoutTimer->start();
1214 }
1215 }
1216
1217 // Apply the changed roles to the visible item-widgets
1218 const int lastIndex = index + count - 1;
1219 for (int i = index; i <= lastIndex; ++i) {
1220 KItemListWidget* widget = m_visibleItems.value(i);
1221 if (widget) {
1222 widget->setData(m_model->data(i), roles);
1223 }
1224 }
1225
1226 if (m_grouped && roles.contains(m_model->sortRole())) {
1227 // The sort-role has been changed which might result
1228 // in modified group headers
1229 updateVisibleGroupHeaders();
1230 doLayout(NoAnimation);
1231 }
1232 }
1233 QAccessible::updateAccessibility(this, 0, QAccessible::TableModelChanged);
1234 }
1235
1236 void KItemListView::slotGroupsChanged()
1237 {
1238 updateVisibleGroupHeaders();
1239 doLayout(NoAnimation);
1240 updateSiblingsInformation();
1241 }
1242
1243 void KItemListView::slotGroupedSortingChanged(bool current)
1244 {
1245 m_grouped = current;
1246 m_layouter->markAsDirty();
1247
1248 if (m_grouped) {
1249 updateGroupHeaderHeight();
1250 } else {
1251 // Clear all visible headers. Note that the QHashIterator takes a copy of
1252 // m_visibleGroups. Therefore, it remains valid even if items are removed
1253 // from m_visibleGroups in recycleGroupHeaderForWidget().
1254 QHashIterator<KItemListWidget*, KItemListGroupHeader*> it(m_visibleGroups);
1255 while (it.hasNext()) {
1256 it.next();
1257 recycleGroupHeaderForWidget(it.key());
1258 }
1259 Q_ASSERT(m_visibleGroups.isEmpty());
1260 }
1261
1262 if (useAlternateBackgrounds()) {
1263 // Changing the group mode requires to update the alternate backgrounds
1264 // as with the enabled group mode the altering is done on base of the first
1265 // group item.
1266 updateAlternateBackgrounds();
1267 }
1268 updateSiblingsInformation();
1269 doLayout(NoAnimation);
1270 }
1271
1272 void KItemListView::slotSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous)
1273 {
1274 Q_UNUSED(current);
1275 Q_UNUSED(previous);
1276 if (m_grouped) {
1277 updateVisibleGroupHeaders();
1278 doLayout(NoAnimation);
1279 }
1280 }
1281
1282 void KItemListView::slotSortRoleChanged(const QByteArray& current, const QByteArray& previous)
1283 {
1284 Q_UNUSED(current);
1285 Q_UNUSED(previous);
1286 if (m_grouped) {
1287 updateVisibleGroupHeaders();
1288 doLayout(NoAnimation);
1289 }
1290 }
1291
1292 void KItemListView::slotCurrentChanged(int current, int previous)
1293 {
1294 Q_UNUSED(previous);
1295
1296 KItemListWidget* previousWidget = m_visibleItems.value(previous, 0);
1297 if (previousWidget) {
1298 previousWidget->setCurrent(false);
1299 }
1300
1301 KItemListWidget* currentWidget = m_visibleItems.value(current, 0);
1302 if (currentWidget) {
1303 currentWidget->setCurrent(true);
1304 }
1305 QAccessible::updateAccessibility(this, current+1, QAccessible::Focus);
1306 }
1307
1308 void KItemListView::slotSelectionChanged(const KItemSet& current, const KItemSet& previous)
1309 {
1310 Q_UNUSED(previous);
1311
1312 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
1313 while (it.hasNext()) {
1314 it.next();
1315 const int index = it.key();
1316 KItemListWidget* widget = it.value();
1317 widget->setSelected(current.contains(index));
1318 }
1319 }
1320
1321 void KItemListView::slotAnimationFinished(QGraphicsWidget* widget,
1322 KItemListViewAnimation::AnimationType type)
1323 {
1324 KItemListWidget* itemListWidget = qobject_cast<KItemListWidget*>(widget);
1325 Q_ASSERT(itemListWidget);
1326
1327 switch (type) {
1328 case KItemListViewAnimation::DeleteAnimation: {
1329 // As we recycle the widget in this case it is important to assure that no
1330 // other animation has been started. This is a convention in KItemListView and
1331 // not a requirement defined by KItemListViewAnimation.
1332 Q_ASSERT(!m_animation->isStarted(itemListWidget));
1333
1334 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1335 // by m_visibleWidgets and must be deleted manually after the animation has
1336 // been finished.
1337 recycleGroupHeaderForWidget(itemListWidget);
1338 widgetCreator()->recycle(itemListWidget);
1339 break;
1340 }
1341
1342 case KItemListViewAnimation::CreateAnimation:
1343 case KItemListViewAnimation::MovingAnimation:
1344 case KItemListViewAnimation::ResizeAnimation: {
1345 const int index = itemListWidget->index();
1346 const bool invisible = (index < m_layouter->firstVisibleIndex()) ||
1347 (index > m_layouter->lastVisibleIndex());
1348 if (invisible && !m_animation->isStarted(itemListWidget)) {
1349 recycleWidget(itemListWidget);
1350 }
1351 break;
1352 }
1353
1354 default: break;
1355 }
1356 }
1357
1358 void KItemListView::slotLayoutTimerFinished()
1359 {
1360 m_layouter->setSize(geometry().size());
1361 doLayout(Animation);
1362 }
1363
1364 void KItemListView::slotRubberBandPosChanged()
1365 {
1366 update();
1367 }
1368
1369 void KItemListView::slotRubberBandActivationChanged(bool active)
1370 {
1371 if (active) {
1372 connect(m_rubberBand, SIGNAL(startPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1373 connect(m_rubberBand, SIGNAL(endPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1374 m_skipAutoScrollForRubberBand = true;
1375 } else {
1376 disconnect(m_rubberBand, SIGNAL(startPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1377 disconnect(m_rubberBand, SIGNAL(endPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1378 m_skipAutoScrollForRubberBand = false;
1379 }
1380
1381 update();
1382 }
1383
1384 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray& role,
1385 qreal currentWidth,
1386 qreal previousWidth)
1387 {
1388 Q_UNUSED(role);
1389 Q_UNUSED(currentWidth);
1390 Q_UNUSED(previousWidth);
1391
1392 m_headerWidget->setAutomaticColumnResizing(false);
1393 applyColumnWidthsFromHeader();
1394 doLayout(NoAnimation);
1395 }
1396
1397 void KItemListView::slotHeaderColumnMoved(const QByteArray& role,
1398 int currentIndex,
1399 int previousIndex)
1400 {
1401 Q_ASSERT(m_visibleRoles[previousIndex] == role);
1402
1403 const QList<QByteArray> previous = m_visibleRoles;
1404
1405 QList<QByteArray> current = m_visibleRoles;
1406 current.removeAt(previousIndex);
1407 current.insert(currentIndex, role);
1408
1409 setVisibleRoles(current);
1410
1411 emit visibleRolesChanged(current, previous);
1412 }
1413
1414 void KItemListView::triggerAutoScrolling()
1415 {
1416 if (!m_autoScrollTimer) {
1417 return;
1418 }
1419
1420 int pos = 0;
1421 int visibleSize = 0;
1422 if (scrollOrientation() == Qt::Vertical) {
1423 pos = m_mousePos.y();
1424 visibleSize = size().height();
1425 } else {
1426 pos = m_mousePos.x();
1427 visibleSize = size().width();
1428 }
1429
1430 if (m_autoScrollTimer->interval() == InitialAutoScrollDelay) {
1431 m_autoScrollIncrement = 0;
1432 }
1433
1434 m_autoScrollIncrement = calculateAutoScrollingIncrement(pos, visibleSize, m_autoScrollIncrement);
1435 if (m_autoScrollIncrement == 0) {
1436 // The mouse position is not above an autoscroll margin (the autoscroll timer
1437 // will be restarted in mouseMoveEvent())
1438 m_autoScrollTimer->stop();
1439 return;
1440 }
1441
1442 if (m_rubberBand->isActive() && m_skipAutoScrollForRubberBand) {
1443 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1444 // if the direction of the rubberband is similar to the autoscroll direction. This
1445 // prevents that starting to create a rubberband within the autoscroll margins starts
1446 // an autoscrolling.
1447
1448 const qreal minDiff = 4; // Ignore any autoscrolling if the rubberband is very small
1449 const qreal diff = (scrollOrientation() == Qt::Vertical)
1450 ? m_rubberBand->endPosition().y() - m_rubberBand->startPosition().y()
1451 : m_rubberBand->endPosition().x() - m_rubberBand->startPosition().x();
1452 if (qAbs(diff) < minDiff || (m_autoScrollIncrement < 0 && diff > 0) || (m_autoScrollIncrement > 0 && diff < 0)) {
1453 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1454 // been moved up although the autoscroll direction might be down)
1455 m_autoScrollTimer->stop();
1456 return;
1457 }
1458 }
1459
1460 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1461 // the autoscrolling may not get skipped anymore until a new rubberband is created
1462 m_skipAutoScrollForRubberBand = false;
1463
1464 const qreal maxVisibleOffset = qMax(qreal(0), maximumScrollOffset() - visibleSize);
1465 const qreal newScrollOffset = qMin(scrollOffset() + m_autoScrollIncrement, maxVisibleOffset);
1466 setScrollOffset(newScrollOffset);
1467
1468 // Trigger the autoscroll timer which will periodically call
1469 // triggerAutoScrolling()
1470 m_autoScrollTimer->start(RepeatingAutoScrollDelay);
1471 }
1472
1473 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1474 {
1475 KItemListWidget* widget = qobject_cast<KItemListWidget*>(sender());
1476 Q_ASSERT(widget);
1477 KItemListGroupHeader* groupHeader = m_visibleGroups.value(widget);
1478 Q_ASSERT(groupHeader);
1479 updateGroupHeaderLayout(widget);
1480 }
1481
1482 void KItemListView::slotRoleEditingCanceled(int index, const QByteArray& role, const QVariant& value)
1483 {
1484 disconnectRoleEditingSignals(index);
1485
1486 emit roleEditingCanceled(index, role, value);
1487 m_editingRole = false;
1488 }
1489
1490 void KItemListView::slotRoleEditingFinished(int index, const QByteArray& role, const QVariant& value)
1491 {
1492 disconnectRoleEditingSignals(index);
1493
1494 emit roleEditingFinished(index, role, value);
1495 m_editingRole = false;
1496 }
1497
1498 void KItemListView::setController(KItemListController* controller)
1499 {
1500 if (m_controller != controller) {
1501 KItemListController* previous = m_controller;
1502 if (previous) {
1503 KItemListSelectionManager* selectionManager = previous->selectionManager();
1504 disconnect(selectionManager, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1505 disconnect(selectionManager, SIGNAL(selectionChanged(KItemSet,KItemSet)), this, SLOT(slotSelectionChanged(KItemSet,KItemSet)));
1506 }
1507
1508 m_controller = controller;
1509
1510 if (controller) {
1511 KItemListSelectionManager* selectionManager = controller->selectionManager();
1512 connect(selectionManager, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1513 connect(selectionManager, SIGNAL(selectionChanged(KItemSet,KItemSet)), this, SLOT(slotSelectionChanged(KItemSet,KItemSet)));
1514 }
1515
1516 onControllerChanged(controller, previous);
1517 }
1518 }
1519
1520 void KItemListView::setModel(KItemModelBase* model)
1521 {
1522 if (m_model == model) {
1523 return;
1524 }
1525
1526 KItemModelBase* previous = m_model;
1527
1528 if (m_model) {
1529 disconnect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
1530 this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
1531 disconnect(m_model, SIGNAL(itemsInserted(KItemRangeList)),
1532 this, SLOT(slotItemsInserted(KItemRangeList)));
1533 disconnect(m_model, SIGNAL(itemsRemoved(KItemRangeList)),
1534 this, SLOT(slotItemsRemoved(KItemRangeList)));
1535 disconnect(m_model, SIGNAL(itemsMoved(KItemRange,QList<int>)),
1536 this, SLOT(slotItemsMoved(KItemRange,QList<int>)));
1537 disconnect(m_model, SIGNAL(groupsChanged()),
1538 this, SLOT(slotGroupsChanged()));
1539 disconnect(m_model, SIGNAL(groupedSortingChanged(bool)),
1540 this, SLOT(slotGroupedSortingChanged(bool)));
1541 disconnect(m_model, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)),
1542 this, SLOT(slotSortOrderChanged(Qt::SortOrder,Qt::SortOrder)));
1543 disconnect(m_model, SIGNAL(sortRoleChanged(QByteArray,QByteArray)),
1544 this, SLOT(slotSortRoleChanged(QByteArray,QByteArray)));
1545
1546 m_sizeHintResolver->itemsRemoved(KItemRangeList() << KItemRange(0, m_model->count()));
1547 }
1548
1549 m_model = model;
1550 m_layouter->setModel(model);
1551 m_grouped = model->groupedSorting();
1552
1553 if (m_model) {
1554 connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
1555 this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
1556 connect(m_model, SIGNAL(itemsInserted(KItemRangeList)),
1557 this, SLOT(slotItemsInserted(KItemRangeList)));
1558 connect(m_model, SIGNAL(itemsRemoved(KItemRangeList)),
1559 this, SLOT(slotItemsRemoved(KItemRangeList)));
1560 connect(m_model, SIGNAL(itemsMoved(KItemRange,QList<int>)),
1561 this, SLOT(slotItemsMoved(KItemRange,QList<int>)));
1562 connect(m_model, SIGNAL(groupsChanged()),
1563 this, SLOT(slotGroupsChanged()));
1564 connect(m_model, SIGNAL(groupedSortingChanged(bool)),
1565 this, SLOT(slotGroupedSortingChanged(bool)));
1566 connect(m_model, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)),
1567 this, SLOT(slotSortOrderChanged(Qt::SortOrder,Qt::SortOrder)));
1568 connect(m_model, SIGNAL(sortRoleChanged(QByteArray,QByteArray)),
1569 this, SLOT(slotSortRoleChanged(QByteArray,QByteArray)));
1570
1571 const int itemCount = m_model->count();
1572 if (itemCount > 0) {
1573 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount));
1574 }
1575 }
1576
1577 onModelChanged(model, previous);
1578 }
1579
1580 KItemListRubberBand* KItemListView::rubberBand() const
1581 {
1582 return m_rubberBand;
1583 }
1584
1585 void KItemListView::doLayout(LayoutAnimationHint hint, int changedIndex, int changedCount)
1586 {
1587 if (m_layoutTimer->isActive()) {
1588 m_layoutTimer->stop();
1589 }
1590
1591 if (m_activeTransactions > 0) {
1592 if (hint == NoAnimation) {
1593 // As soon as at least one property change should be done without animation,
1594 // the whole transaction will be marked as not animated.
1595 m_endTransactionAnimationHint = NoAnimation;
1596 }
1597 return;
1598 }
1599
1600 if (!m_model || m_model->count() < 0) {
1601 return;
1602 }
1603
1604 int firstVisibleIndex = m_layouter->firstVisibleIndex();
1605 if (firstVisibleIndex < 0) {
1606 emitOffsetChanges();
1607 return;
1608 }
1609
1610 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1611 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1612 // is still shown if the maximum offset got decreased.
1613 const qreal visibleOffsetRange = (scrollOrientation() == Qt::Horizontal) ? size().width() : size().height();
1614 const qreal maxOffsetToShowFullRange = maximumScrollOffset() - visibleOffsetRange;
1615 if (scrollOffset() > maxOffsetToShowFullRange) {
1616 m_layouter->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange));
1617 firstVisibleIndex = m_layouter->firstVisibleIndex();
1618 }
1619
1620 const int lastVisibleIndex = m_layouter->lastVisibleIndex();
1621
1622 int firstSibblingIndex = -1;
1623 int lastSibblingIndex = -1;
1624 const bool supportsExpanding = supportsItemExpanding();
1625
1626 QList<int> reusableItems = recycleInvisibleItems(firstVisibleIndex, lastVisibleIndex, hint);
1627
1628 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1629 // instances from invisible items are reused. If no reusable items are
1630 // found then new KItemListWidget instances get created.
1631 const bool animate = (hint == Animation);
1632 for (int i = firstVisibleIndex; i <= lastVisibleIndex; ++i) {
1633 bool applyNewPos = true;
1634 bool wasHidden = false;
1635
1636 const QRectF itemBounds = m_layouter->itemRect(i);
1637 const QPointF newPos = itemBounds.topLeft();
1638 KItemListWidget* widget = m_visibleItems.value(i);
1639 if (!widget) {
1640 wasHidden = true;
1641 if (!reusableItems.isEmpty()) {
1642 // Reuse a KItemListWidget instance from an invisible item
1643 const int oldIndex = reusableItems.takeLast();
1644 widget = m_visibleItems.value(oldIndex);
1645 setWidgetIndex(widget, i);
1646 updateWidgetProperties(widget, i);
1647 initializeItemListWidget(widget);
1648 } else {
1649 // No reusable KItemListWidget instance is available, create a new one
1650 widget = createWidget(i);
1651 }
1652 widget->resize(itemBounds.size());
1653
1654 if (animate && changedCount < 0) {
1655 // Items have been deleted.
1656 if (i >= changedIndex) {
1657 // The item is located behind the removed range. Move the
1658 // created item to the imaginary old position outside the
1659 // view. It will get animated to the new position later.
1660 const int previousIndex = i - changedCount;
1661 const QRectF itemRect = m_layouter->itemRect(previousIndex);
1662 if (itemRect.isEmpty()) {
1663 const QPointF invisibleOldPos = (scrollOrientation() == Qt::Vertical)
1664 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1665 widget->setPos(invisibleOldPos);
1666 } else {
1667 widget->setPos(itemRect.topLeft());
1668 }
1669 applyNewPos = false;
1670 }
1671 }
1672
1673 if (supportsExpanding && changedCount == 0) {
1674 if (firstSibblingIndex < 0) {
1675 firstSibblingIndex = i;
1676 }
1677 lastSibblingIndex = i;
1678 }
1679 }
1680
1681 if (animate) {
1682 if (m_animation->isStarted(widget, KItemListViewAnimation::MovingAnimation)) {
1683 m_animation->start(widget, KItemListViewAnimation::MovingAnimation, newPos);
1684 applyNewPos = false;
1685 }
1686
1687 const bool itemsRemoved = (changedCount < 0);
1688 const bool itemsInserted = (changedCount > 0);
1689 if (itemsRemoved && (i >= changedIndex)) {
1690 // The item is located after the removed items. Animate the moving of the position.
1691 applyNewPos = !moveWidget(widget, newPos);
1692 } else if (itemsInserted && i >= changedIndex) {
1693 // The item is located after the first inserted item
1694 if (i <= changedIndex + changedCount - 1) {
1695 // The item is an inserted item. Animate the appearing of the item.
1696 // For performance reasons no animation is done when changedCount is equal
1697 // to all available items.
1698 if (changedCount < m_model->count()) {
1699 m_animation->start(widget, KItemListViewAnimation::CreateAnimation);
1700 }
1701 } else if (!m_animation->isStarted(widget, KItemListViewAnimation::CreateAnimation)) {
1702 // The item was already there before, so animate the moving of the position.
1703 // No moving animation is done if the item is animated by a create animation: This
1704 // prevents a "move animation mess" when inserting several ranges in parallel.
1705 applyNewPos = !moveWidget(widget, newPos);
1706 }
1707 } else if (!itemsRemoved && !itemsInserted && !wasHidden) {
1708 // The size of the view might have been changed. Animate the moving of the position.
1709 applyNewPos = !moveWidget(widget, newPos);
1710 }
1711 } else {
1712 m_animation->stop(widget);
1713 }
1714
1715 if (applyNewPos) {
1716 widget->setPos(newPos);
1717 }
1718
1719 Q_ASSERT(widget->index() == i);
1720 widget->setVisible(true);
1721
1722 if (widget->size() != itemBounds.size()) {
1723 // Resize the widget for the item to the changed size.
1724 if (animate) {
1725 // If a dynamic item size is used then no animation is done in the direction
1726 // of the dynamic size.
1727 if (m_itemSize.width() <= 0) {
1728 // The width is dynamic, apply the new width without animation.
1729 widget->resize(itemBounds.width(), widget->size().height());
1730 } else if (m_itemSize.height() <= 0) {
1731 // The height is dynamic, apply the new height without animation.
1732 widget->resize(widget->size().width(), itemBounds.height());
1733 }
1734 m_animation->start(widget, KItemListViewAnimation::ResizeAnimation, itemBounds.size());
1735 } else {
1736 widget->resize(itemBounds.size());
1737 }
1738 }
1739
1740 // Updating the cell-information must be done as last step: The decision whether the
1741 // moving-animation should be started at all is based on the previous cell-information.
1742 const Cell cell(m_layouter->itemColumn(i), m_layouter->itemRow(i));
1743 m_visibleCells.insert(i, cell);
1744 }
1745
1746 // Delete invisible KItemListWidget instances that have not been reused
1747 foreach (int index, reusableItems) {
1748 recycleWidget(m_visibleItems.value(index));
1749 }
1750
1751 if (supportsExpanding && firstSibblingIndex >= 0) {
1752 Q_ASSERT(lastSibblingIndex >= 0);
1753 updateSiblingsInformation(firstSibblingIndex, lastSibblingIndex);
1754 }
1755
1756 if (m_grouped) {
1757 // Update the layout of all visible group headers
1758 QHashIterator<KItemListWidget*, KItemListGroupHeader*> it(m_visibleGroups);
1759 while (it.hasNext()) {
1760 it.next();
1761 updateGroupHeaderLayout(it.key());
1762 }
1763 }
1764
1765 emitOffsetChanges();
1766 }
1767
1768 QList<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex,
1769 int lastVisibleIndex,
1770 LayoutAnimationHint hint)
1771 {
1772 // Determine all items that are completely invisible and might be
1773 // reused for items that just got (at least partly) visible. If the
1774 // animation hint is set to 'Animation' items that do e.g. an animated
1775 // moving of their position are not marked as invisible: This assures
1776 // that a scrolling inside the view can be done without breaking an animation.
1777
1778 QList<int> items;
1779
1780 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
1781 while (it.hasNext()) {
1782 it.next();
1783
1784 KItemListWidget* widget = it.value();
1785 const int index = widget->index();
1786 const bool invisible = (index < firstVisibleIndex) || (index > lastVisibleIndex);
1787
1788 if (invisible) {
1789 if (m_animation->isStarted(widget)) {
1790 if (hint == NoAnimation) {
1791 // Stopping the animation will call KItemListView::slotAnimationFinished()
1792 // and the widget will be recycled if necessary there.
1793 m_animation->stop(widget);
1794 }
1795 } else {
1796 widget->setVisible(false);
1797 items.append(index);
1798
1799 if (m_grouped) {
1800 recycleGroupHeaderForWidget(widget);
1801 }
1802 }
1803 }
1804 }
1805
1806 return items;
1807 }
1808
1809 bool KItemListView::moveWidget(KItemListWidget* widget,const QPointF& newPos)
1810 {
1811 if (widget->pos() == newPos) {
1812 return false;
1813 }
1814
1815 bool startMovingAnim = false;
1816
1817 if (m_itemSize.isEmpty()) {
1818 // The items are not aligned in a grid but either as columns or rows.
1819 startMovingAnim = true;
1820 } else {
1821 // When having a grid the moving-animation should only be started, if it is done within
1822 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1823 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1824 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1825 const int index = widget->index();
1826 const Cell cell = m_visibleCells.value(index);
1827 if (cell.column >= 0 && cell.row >= 0) {
1828 if (scrollOrientation() == Qt::Vertical) {
1829 startMovingAnim = (cell.row == m_layouter->itemRow(index));
1830 } else {
1831 startMovingAnim = (cell.column == m_layouter->itemColumn(index));
1832 }
1833 }
1834 }
1835
1836 if (startMovingAnim) {
1837 m_animation->start(widget, KItemListViewAnimation::MovingAnimation, newPos);
1838 return true;
1839 }
1840
1841 m_animation->stop(widget);
1842 m_animation->start(widget, KItemListViewAnimation::CreateAnimation);
1843 return false;
1844 }
1845
1846 void KItemListView::emitOffsetChanges()
1847 {
1848 const qreal newScrollOffset = m_layouter->scrollOffset();
1849 if (m_oldScrollOffset != newScrollOffset) {
1850 emit scrollOffsetChanged(newScrollOffset, m_oldScrollOffset);
1851 m_oldScrollOffset = newScrollOffset;
1852 }
1853
1854 const qreal newMaximumScrollOffset = m_layouter->maximumScrollOffset();
1855 if (m_oldMaximumScrollOffset != newMaximumScrollOffset) {
1856 emit maximumScrollOffsetChanged(newMaximumScrollOffset, m_oldMaximumScrollOffset);
1857 m_oldMaximumScrollOffset = newMaximumScrollOffset;
1858 }
1859
1860 const qreal newItemOffset = m_layouter->itemOffset();
1861 if (m_oldItemOffset != newItemOffset) {
1862 emit itemOffsetChanged(newItemOffset, m_oldItemOffset);
1863 m_oldItemOffset = newItemOffset;
1864 }
1865
1866 const qreal newMaximumItemOffset = m_layouter->maximumItemOffset();
1867 if (m_oldMaximumItemOffset != newMaximumItemOffset) {
1868 emit maximumItemOffsetChanged(newMaximumItemOffset, m_oldMaximumItemOffset);
1869 m_oldMaximumItemOffset = newMaximumItemOffset;
1870 }
1871 }
1872
1873 KItemListWidget* KItemListView::createWidget(int index)
1874 {
1875 KItemListWidget* widget = widgetCreator()->create(this);
1876 widget->setFlag(QGraphicsItem::ItemStacksBehindParent);
1877
1878 m_visibleItems.insert(index, widget);
1879 m_visibleCells.insert(index, Cell());
1880 updateWidgetProperties(widget, index);
1881 initializeItemListWidget(widget);
1882 return widget;
1883 }
1884
1885 void KItemListView::recycleWidget(KItemListWidget* widget)
1886 {
1887 if (m_grouped) {
1888 recycleGroupHeaderForWidget(widget);
1889 }
1890
1891 const int index = widget->index();
1892 m_visibleItems.remove(index);
1893 m_visibleCells.remove(index);
1894
1895 widgetCreator()->recycle(widget);
1896 }
1897
1898 void KItemListView::setWidgetIndex(KItemListWidget* widget, int index)
1899 {
1900 const int oldIndex = widget->index();
1901 m_visibleItems.remove(oldIndex);
1902 m_visibleCells.remove(oldIndex);
1903
1904 m_visibleItems.insert(index, widget);
1905 m_visibleCells.insert(index, Cell());
1906
1907 widget->setIndex(index);
1908 }
1909
1910 void KItemListView::moveWidgetToIndex(KItemListWidget* widget, int index)
1911 {
1912 const int oldIndex = widget->index();
1913 const Cell oldCell = m_visibleCells.value(oldIndex);
1914
1915 setWidgetIndex(widget, index);
1916
1917 const Cell newCell(m_layouter->itemColumn(index), m_layouter->itemRow(index));
1918 const bool vertical = (scrollOrientation() == Qt::Vertical);
1919 const bool updateCell = (vertical && oldCell.row == newCell.row) ||
1920 (!vertical && oldCell.column == newCell.column);
1921 if (updateCell) {
1922 m_visibleCells.insert(index, newCell);
1923 }
1924 }
1925
1926 void KItemListView::setLayouterSize(const QSizeF& size, SizeType sizeType)
1927 {
1928 switch (sizeType) {
1929 case LayouterSize: m_layouter->setSize(size); break;
1930 case ItemSize: m_layouter->setItemSize(size); break;
1931 default: break;
1932 }
1933 }
1934
1935 void KItemListView::updateWidgetProperties(KItemListWidget* widget, int index)
1936 {
1937 widget->setVisibleRoles(m_visibleRoles);
1938 updateWidgetColumnWidths(widget);
1939 widget->setStyleOption(m_styleOption);
1940
1941 const KItemListSelectionManager* selectionManager = m_controller->selectionManager();
1942 widget->setCurrent(index == selectionManager->currentItem());
1943 widget->setSelected(selectionManager->isSelected(index));
1944 widget->setHovered(false);
1945 widget->setEnabledSelectionToggle(enabledSelectionToggles());
1946 widget->setIndex(index);
1947 widget->setData(m_model->data(index));
1948 widget->setSiblingsInformation(QBitArray());
1949 updateAlternateBackgroundForWidget(widget);
1950
1951 if (m_grouped) {
1952 updateGroupHeaderForWidget(widget);
1953 }
1954 }
1955
1956 void KItemListView::updateGroupHeaderForWidget(KItemListWidget* widget)
1957 {
1958 Q_ASSERT(m_grouped);
1959
1960 const int index = widget->index();
1961 if (!m_layouter->isFirstGroupItem(index)) {
1962 // The widget does not represent the first item of a group
1963 // and hence requires no header
1964 recycleGroupHeaderForWidget(widget);
1965 return;
1966 }
1967
1968 const QList<QPair<int, QVariant> > groups = model()->groups();
1969 if (groups.isEmpty() || !groupHeaderCreator()) {
1970 return;
1971 }
1972
1973 KItemListGroupHeader* groupHeader = m_visibleGroups.value(widget);
1974 if (!groupHeader) {
1975 groupHeader = groupHeaderCreator()->create(this);
1976 groupHeader->setParentItem(widget);
1977 m_visibleGroups.insert(widget, groupHeader);
1978 connect(widget, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1979 }
1980 Q_ASSERT(groupHeader->parentItem() == widget);
1981
1982 const int groupIndex = groupIndexForItem(index);
1983 Q_ASSERT(groupIndex >= 0);
1984 groupHeader->setData(groups.at(groupIndex).second);
1985 groupHeader->setRole(model()->sortRole());
1986 groupHeader->setStyleOption(m_styleOption);
1987 groupHeader->setScrollOrientation(scrollOrientation());
1988 groupHeader->setItemIndex(index);
1989
1990 groupHeader->show();
1991 }
1992
1993 void KItemListView::updateGroupHeaderLayout(KItemListWidget* widget)
1994 {
1995 KItemListGroupHeader* groupHeader = m_visibleGroups.value(widget);
1996 Q_ASSERT(groupHeader);
1997
1998 const int index = widget->index();
1999 const QRectF groupHeaderRect = m_layouter->groupHeaderRect(index);
2000 const QRectF itemRect = m_layouter->itemRect(index);
2001
2002 // The group-header is a child of the itemlist widget. Translate the
2003 // group header position to the relative position.
2004 if (scrollOrientation() == Qt::Vertical) {
2005 // In the vertical scroll orientation the group header should always span
2006 // the whole width no matter which temporary position the parent widget
2007 // has. In this case the x-position and width will be adjusted manually.
2008 const qreal x = -widget->x() - itemOffset();
2009 const qreal width = maximumItemOffset();
2010 groupHeader->setPos(x, -groupHeaderRect.height());
2011 groupHeader->resize(width, groupHeaderRect.size().height());
2012 } else {
2013 groupHeader->setPos(groupHeaderRect.x() - itemRect.x(), -widget->y());
2014 groupHeader->resize(groupHeaderRect.size());
2015 }
2016 }
2017
2018 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget* widget)
2019 {
2020 KItemListGroupHeader* header = m_visibleGroups.value(widget);
2021 if (header) {
2022 header->setParentItem(0);
2023 groupHeaderCreator()->recycle(header);
2024 m_visibleGroups.remove(widget);
2025 disconnect(widget, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
2026 }
2027 }
2028
2029 void KItemListView::updateVisibleGroupHeaders()
2030 {
2031 Q_ASSERT(m_grouped);
2032 m_layouter->markAsDirty();
2033
2034 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
2035 while (it.hasNext()) {
2036 it.next();
2037 updateGroupHeaderForWidget(it.value());
2038 }
2039 }
2040
2041 int KItemListView::groupIndexForItem(int index) const
2042 {
2043 Q_ASSERT(m_grouped);
2044
2045 const QList<QPair<int, QVariant> > groups = model()->groups();
2046 if (groups.isEmpty()) {
2047 return -1;
2048 }
2049
2050 int min = 0;
2051 int max = groups.count() - 1;
2052 int mid = 0;
2053 do {
2054 mid = (min + max) / 2;
2055 if (index > groups[mid].first) {
2056 min = mid + 1;
2057 } else {
2058 max = mid - 1;
2059 }
2060 } while (groups[mid].first != index && min <= max);
2061
2062 if (min > max) {
2063 while (groups[mid].first > index && mid > 0) {
2064 --mid;
2065 }
2066 }
2067
2068 return mid;
2069 }
2070
2071 void KItemListView::updateAlternateBackgrounds()
2072 {
2073 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
2074 while (it.hasNext()) {
2075 it.next();
2076 updateAlternateBackgroundForWidget(it.value());
2077 }
2078 }
2079
2080 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget* widget)
2081 {
2082 bool enabled = useAlternateBackgrounds();
2083 if (enabled) {
2084 const int index = widget->index();
2085 enabled = (index & 0x1) > 0;
2086 if (m_grouped) {
2087 const int groupIndex = groupIndexForItem(index);
2088 if (groupIndex >= 0) {
2089 const QList<QPair<int, QVariant> > groups = model()->groups();
2090 const int indexOfFirstGroupItem = groups[groupIndex].first;
2091 const int relativeIndex = index - indexOfFirstGroupItem;
2092 enabled = (relativeIndex & 0x1) > 0;
2093 }
2094 }
2095 }
2096 widget->setAlternateBackground(enabled);
2097 }
2098
2099 bool KItemListView::useAlternateBackgrounds() const
2100 {
2101 return m_itemSize.isEmpty() && m_visibleRoles.count() > 1;
2102 }
2103
2104 QHash<QByteArray, qreal> KItemListView::preferredColumnWidths(const KItemRangeList& itemRanges) const
2105 {
2106 QElapsedTimer timer;
2107 timer.start();
2108
2109 QHash<QByteArray, qreal> widths;
2110
2111 // Calculate the minimum width for each column that is required
2112 // to show the headline unclipped.
2113 const QFontMetricsF fontMetrics(m_headerWidget->font());
2114 const int gripMargin = m_headerWidget->style()->pixelMetric(QStyle::PM_HeaderGripMargin);
2115 const int headerMargin = m_headerWidget->style()->pixelMetric(QStyle::PM_HeaderMargin);
2116 foreach (const QByteArray& visibleRole, visibleRoles()) {
2117 const QString headerText = m_model->roleDescription(visibleRole);
2118 const qreal headerWidth = fontMetrics.width(headerText) + gripMargin + headerMargin * 2;
2119 widths.insert(visibleRole, headerWidth);
2120 }
2121
2122 // Calculate the preferred column withs for each item and ignore values
2123 // smaller than the width for showing the headline unclipped.
2124 const KItemListWidgetCreatorBase* creator = widgetCreator();
2125 int calculatedItemCount = 0;
2126 bool maxTimeExceeded = false;
2127 foreach (const KItemRange& itemRange, itemRanges) {
2128 const int startIndex = itemRange.index;
2129 const int endIndex = startIndex + itemRange.count - 1;
2130
2131 for (int i = startIndex; i <= endIndex; ++i) {
2132 foreach (const QByteArray& visibleRole, visibleRoles()) {
2133 qreal maxWidth = widths.value(visibleRole, 0);
2134 const qreal width = creator->preferredRoleColumnWidth(visibleRole, i, this);
2135 maxWidth = qMax(width, maxWidth);
2136 widths.insert(visibleRole, maxWidth);
2137 }
2138
2139 if (calculatedItemCount > 100 && timer.elapsed() > 200) {
2140 // When having several thousands of items calculating the sizes can get
2141 // very expensive. We accept a possibly too small role-size in favour
2142 // of having no blocking user interface.
2143 maxTimeExceeded = true;
2144 break;
2145 }
2146 ++calculatedItemCount;
2147 }
2148 if (maxTimeExceeded) {
2149 break;
2150 }
2151 }
2152
2153 return widths;
2154 }
2155
2156 void KItemListView::applyColumnWidthsFromHeader()
2157 {
2158 // Apply the new size to the layouter
2159 const qreal requiredWidth = columnWidthsSum();
2160 const QSizeF dynamicItemSize(qMax(size().width(), requiredWidth),
2161 m_itemSize.height());
2162 m_layouter->setItemSize(dynamicItemSize);
2163
2164 // Update the role sizes for all visible widgets
2165 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
2166 while (it.hasNext()) {
2167 it.next();
2168 updateWidgetColumnWidths(it.value());
2169 }
2170 }
2171
2172 void KItemListView::updateWidgetColumnWidths(KItemListWidget* widget)
2173 {
2174 foreach (const QByteArray& role, m_visibleRoles) {
2175 widget->setColumnWidth(role, m_headerWidget->columnWidth(role));
2176 }
2177 }
2178
2179 void KItemListView::updatePreferredColumnWidths(const KItemRangeList& itemRanges)
2180 {
2181 Q_ASSERT(m_itemSize.isEmpty());
2182 const int itemCount = m_model->count();
2183 int rangesItemCount = 0;
2184 foreach (const KItemRange& range, itemRanges) {
2185 rangesItemCount += range.count;
2186 }
2187
2188 if (itemCount == rangesItemCount) {
2189 const QHash<QByteArray, qreal> preferredWidths = preferredColumnWidths(itemRanges);
2190 foreach (const QByteArray& role, m_visibleRoles) {
2191 m_headerWidget->setPreferredColumnWidth(role, preferredWidths.value(role));
2192 }
2193 } else {
2194 // Only a sub range of the roles need to be determined.
2195 // The chances are good that the widths of the sub ranges
2196 // already fit into the available widths and hence no
2197 // expensive update might be required.
2198 bool changed = false;
2199
2200 const QHash<QByteArray, qreal> updatedWidths = preferredColumnWidths(itemRanges);
2201 QHashIterator<QByteArray, qreal> it(updatedWidths);
2202 while (it.hasNext()) {
2203 it.next();
2204 const QByteArray& role = it.key();
2205 const qreal updatedWidth = it.value();
2206 const qreal currentWidth = m_headerWidget->preferredColumnWidth(role);
2207 if (updatedWidth > currentWidth) {
2208 m_headerWidget->setPreferredColumnWidth(role, updatedWidth);
2209 changed = true;
2210 }
2211 }
2212
2213 if (!changed) {
2214 // All the updated sizes are smaller than the current sizes and no change
2215 // of the stretched roles-widths is required
2216 return;
2217 }
2218 }
2219
2220 if (m_headerWidget->automaticColumnResizing()) {
2221 applyAutomaticColumnWidths();
2222 }
2223 }
2224
2225 void KItemListView::updatePreferredColumnWidths()
2226 {
2227 if (m_model) {
2228 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model->count()));
2229 }
2230 }
2231
2232 void KItemListView::applyAutomaticColumnWidths()
2233 {
2234 Q_ASSERT(m_itemSize.isEmpty());
2235 Q_ASSERT(m_headerWidget->automaticColumnResizing());
2236 if (m_visibleRoles.isEmpty()) {
2237 return;
2238 }
2239
2240 // Calculate the maximum size of an item by considering the
2241 // visible role sizes and apply them to the layouter. If the
2242 // size does not use the available view-size the size of the
2243 // first role will get stretched.
2244
2245 foreach (const QByteArray& role, m_visibleRoles) {
2246 const qreal preferredWidth = m_headerWidget->preferredColumnWidth(role);
2247 m_headerWidget->setColumnWidth(role, preferredWidth);
2248 }
2249
2250 const QByteArray firstRole = m_visibleRoles.first();
2251 qreal firstColumnWidth = m_headerWidget->columnWidth(firstRole);
2252 QSizeF dynamicItemSize = m_itemSize;
2253
2254 qreal requiredWidth = columnWidthsSum();
2255 const qreal availableWidth = size().width();
2256 if (requiredWidth < availableWidth) {
2257 // Stretch the first column to use the whole remaining width
2258 firstColumnWidth += availableWidth - requiredWidth;
2259 m_headerWidget->setColumnWidth(firstRole, firstColumnWidth);
2260 } else if (requiredWidth > availableWidth && m_visibleRoles.count() > 1) {
2261 // Shrink the first column to be able to show as much other
2262 // columns as possible
2263 qreal shrinkedFirstColumnWidth = firstColumnWidth - requiredWidth + availableWidth;
2264
2265 // TODO: A proper calculation of the minimum width depends on the implementation
2266 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2267 // later.
2268 const qreal minWidth = qMin(firstColumnWidth, qreal(m_styleOption.iconSize * 2 + 200));
2269 if (shrinkedFirstColumnWidth < minWidth) {
2270 shrinkedFirstColumnWidth = minWidth;
2271 }
2272
2273 m_headerWidget->setColumnWidth(firstRole, shrinkedFirstColumnWidth);
2274 requiredWidth -= firstColumnWidth - shrinkedFirstColumnWidth;
2275 }
2276
2277 dynamicItemSize.rwidth() = qMax(requiredWidth, availableWidth);
2278
2279 m_layouter->setItemSize(dynamicItemSize);
2280
2281 // Update the role sizes for all visible widgets
2282 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
2283 while (it.hasNext()) {
2284 it.next();
2285 updateWidgetColumnWidths(it.value());
2286 }
2287 }
2288
2289 qreal KItemListView::columnWidthsSum() const
2290 {
2291 qreal widthsSum = 0;
2292 foreach (const QByteArray& role, m_visibleRoles) {
2293 widthsSum += m_headerWidget->columnWidth(role);
2294 }
2295 return widthsSum;
2296 }
2297
2298 QRectF KItemListView::headerBoundaries() const
2299 {
2300 return m_headerWidget->isVisible() ? m_headerWidget->geometry() : QRectF();
2301 }
2302
2303 bool KItemListView::changesItemGridLayout(const QSizeF& newGridSize,
2304 const QSizeF& newItemSize,
2305 const QSizeF& newItemMargin) const
2306 {
2307 if (newItemSize.isEmpty() || newGridSize.isEmpty()) {
2308 return false;
2309 }
2310
2311 if (m_layouter->scrollOrientation() == Qt::Vertical) {
2312 const qreal itemWidth = m_layouter->itemSize().width();
2313 if (itemWidth > 0) {
2314 const int newColumnCount = itemsPerSize(newGridSize.width(),
2315 newItemSize.width(),
2316 newItemMargin.width());
2317 if (m_model->count() > newColumnCount) {
2318 const int oldColumnCount = itemsPerSize(m_layouter->size().width(),
2319 itemWidth,
2320 m_layouter->itemMargin().width());
2321 return oldColumnCount != newColumnCount;
2322 }
2323 }
2324 } else {
2325 const qreal itemHeight = m_layouter->itemSize().height();
2326 if (itemHeight > 0) {
2327 const int newRowCount = itemsPerSize(newGridSize.height(),
2328 newItemSize.height(),
2329 newItemMargin.height());
2330 if (m_model->count() > newRowCount) {
2331 const int oldRowCount = itemsPerSize(m_layouter->size().height(),
2332 itemHeight,
2333 m_layouter->itemMargin().height());
2334 return oldRowCount != newRowCount;
2335 }
2336 }
2337 }
2338
2339 return false;
2340 }
2341
2342 bool KItemListView::animateChangedItemCount(int changedItemCount) const
2343 {
2344 if (m_itemSize.isEmpty()) {
2345 // We have only columns or only rows, but no grid: An animation is usually
2346 // welcome when inserting or removing items.
2347 return !supportsItemExpanding();
2348 }
2349
2350 if (m_layouter->size().isEmpty() || m_layouter->itemSize().isEmpty()) {
2351 return false;
2352 }
2353
2354 const int maximum = (scrollOrientation() == Qt::Vertical)
2355 ? m_layouter->size().width() / m_layouter->itemSize().width()
2356 : m_layouter->size().height() / m_layouter->itemSize().height();
2357 // Only animate if up to 2/3 of a row or column are inserted or removed
2358 return changedItemCount <= maximum * 2 / 3;
2359 }
2360
2361
2362 bool KItemListView::scrollBarRequired(const QSizeF& size) const
2363 {
2364 const QSizeF oldSize = m_layouter->size();
2365
2366 m_layouter->setSize(size);
2367 const qreal maxOffset = m_layouter->maximumScrollOffset();
2368 m_layouter->setSize(oldSize);
2369
2370 return m_layouter->scrollOrientation() == Qt::Vertical ? maxOffset > size.height()
2371 : maxOffset > size.width();
2372 }
2373
2374 int KItemListView::showDropIndicator(const QPointF& pos)
2375 {
2376 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
2377 while (it.hasNext()) {
2378 it.next();
2379 const KItemListWidget* widget = it.value();
2380
2381 const QPointF mappedPos = widget->mapFromItem(this, pos);
2382 const QRectF rect = itemRect(widget->index());
2383 if (mappedPos.y() >= 0 && mappedPos.y() <= rect.height()) {
2384 if (m_model->supportsDropping(widget->index())) {
2385 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2386 const int gap = qMax(4.0, 0.3 * rect.height());
2387 if (mappedPos.y() >= gap && mappedPos.y() <= rect.height() - gap) {
2388 return -1;
2389 }
2390 }
2391
2392 const bool isAboveItem = (mappedPos.y () < rect.height() / 2);
2393 const qreal y = isAboveItem ? rect.top() : rect.bottom();
2394
2395 const QRectF draggingInsertIndicator(rect.left(), y, rect.width(), 1);
2396 if (m_dropIndicator != draggingInsertIndicator) {
2397 m_dropIndicator = draggingInsertIndicator;
2398 update();
2399 }
2400
2401 int index = widget->index();
2402 if (!isAboveItem) {
2403 ++index;
2404 }
2405 return index;
2406 }
2407 }
2408
2409 const QRectF firstItemRect = itemRect(firstVisibleIndex());
2410 return (pos.y() <= firstItemRect.top()) ? 0 : -1;
2411 }
2412
2413 void KItemListView::hideDropIndicator()
2414 {
2415 if (!m_dropIndicator.isNull()) {
2416 m_dropIndicator = QRectF();
2417 update();
2418 }
2419 }
2420
2421 void KItemListView::updateGroupHeaderHeight()
2422 {
2423 qreal groupHeaderHeight = m_styleOption.fontMetrics.height();
2424 qreal groupHeaderMargin = 0;
2425
2426 if (scrollOrientation() == Qt::Horizontal) {
2427 // The vertical margin above and below the header should be
2428 // equal to the horizontal margin, not the vertical margin
2429 // from m_styleOption.
2430 groupHeaderHeight += 2 * m_styleOption.horizontalMargin;
2431 groupHeaderMargin = m_styleOption.horizontalMargin;
2432 } else if (m_itemSize.isEmpty()){
2433 groupHeaderHeight += 4 * m_styleOption.padding;
2434 groupHeaderMargin = m_styleOption.iconSize / 2;
2435 } else {
2436 groupHeaderHeight += 2 * m_styleOption.padding + m_styleOption.verticalMargin;
2437 groupHeaderMargin = m_styleOption.iconSize / 4;
2438 }
2439 m_layouter->setGroupHeaderHeight(groupHeaderHeight);
2440 m_layouter->setGroupHeaderMargin(groupHeaderMargin);
2441
2442 updateVisibleGroupHeaders();
2443 }
2444
2445 void KItemListView::updateSiblingsInformation(int firstIndex, int lastIndex)
2446 {
2447 if (!supportsItemExpanding() || !m_model) {
2448 return;
2449 }
2450
2451 if (firstIndex < 0 || lastIndex < 0) {
2452 firstIndex = m_layouter->firstVisibleIndex();
2453 lastIndex = m_layouter->lastVisibleIndex();
2454 } else {
2455 const bool isRangeVisible = (firstIndex <= m_layouter->lastVisibleIndex() &&
2456 lastIndex >= m_layouter->firstVisibleIndex());
2457 if (!isRangeVisible) {
2458 return;
2459 }
2460 }
2461
2462 int previousParents = 0;
2463 QBitArray previousSiblings;
2464
2465 // The rootIndex describes the first index where the siblings get
2466 // calculated from. For the calculation the upper most parent item
2467 // is required. For performance reasons it is checked first whether
2468 // the visible items before or after the current range already
2469 // contain a siblings information which can be used as base.
2470 int rootIndex = firstIndex;
2471
2472 KItemListWidget* widget = m_visibleItems.value(firstIndex - 1);
2473 if (!widget) {
2474 // There is no visible widget before the range, check whether there
2475 // is one after the range:
2476 widget = m_visibleItems.value(lastIndex + 1);
2477 if (widget) {
2478 // The sibling information of the widget may only be used if
2479 // all items of the range have the same number of parents.
2480 const int parents = m_model->expandedParentsCount(lastIndex + 1);
2481 for (int i = lastIndex; i >= firstIndex; --i) {
2482 if (m_model->expandedParentsCount(i) != parents) {
2483 widget = 0;
2484 break;
2485 }
2486 }
2487 }
2488 }
2489
2490 if (widget) {
2491 // Performance optimization: Use the sibling information of the visible
2492 // widget beside the given range.
2493 previousSiblings = widget->siblingsInformation();
2494 if (previousSiblings.isEmpty()) {
2495 return;
2496 }
2497 previousParents = previousSiblings.count() - 1;
2498 previousSiblings.truncate(previousParents);
2499 } else {
2500 // Potentially slow path: Go back to the upper most parent of firstIndex
2501 // to be able to calculate the initial value for the siblings.
2502 while (rootIndex > 0 && m_model->expandedParentsCount(rootIndex) > 0) {
2503 --rootIndex;
2504 }
2505 }
2506
2507 Q_ASSERT(previousParents >= 0);
2508 for (int i = rootIndex; i <= lastIndex; ++i) {
2509 // Update the parent-siblings in case if the current item represents
2510 // a child or an upper parent.
2511 const int currentParents = m_model->expandedParentsCount(i);
2512 Q_ASSERT(currentParents >= 0);
2513 if (previousParents < currentParents) {
2514 previousParents = currentParents;
2515 previousSiblings.resize(currentParents);
2516 previousSiblings.setBit(currentParents - 1, hasSiblingSuccessor(i - 1));
2517 } else if (previousParents > currentParents) {
2518 previousParents = currentParents;
2519 previousSiblings.truncate(currentParents);
2520 }
2521
2522 if (i >= firstIndex) {
2523 // The index represents a visible item. Apply the parent-siblings
2524 // and update the sibling of the current item.
2525 KItemListWidget* widget = m_visibleItems.value(i);
2526 if (!widget) {
2527 continue;
2528 }
2529
2530 QBitArray siblings = previousSiblings;
2531 siblings.resize(siblings.count() + 1);
2532 siblings.setBit(siblings.count() - 1, hasSiblingSuccessor(i));
2533
2534 widget->setSiblingsInformation(siblings);
2535 }
2536 }
2537 }
2538
2539 bool KItemListView::hasSiblingSuccessor(int index) const
2540 {
2541 bool hasSuccessor = false;
2542 const int parentsCount = m_model->expandedParentsCount(index);
2543 int successorIndex = index + 1;
2544
2545 // Search the next sibling
2546 const int itemCount = m_model->count();
2547 while (successorIndex < itemCount) {
2548 const int currentParentsCount = m_model->expandedParentsCount(successorIndex);
2549 if (currentParentsCount == parentsCount) {
2550 hasSuccessor = true;
2551 break;
2552 } else if (currentParentsCount < parentsCount) {
2553 break;
2554 }
2555 ++successorIndex;
2556 }
2557
2558 if (m_grouped && hasSuccessor) {
2559 // If the sibling is part of another group, don't mark it as
2560 // successor as the group header is between the sibling connections.
2561 for (int i = index + 1; i <= successorIndex; ++i) {
2562 if (m_layouter->isFirstGroupItem(i)) {
2563 hasSuccessor = false;
2564 break;
2565 }
2566 }
2567 }
2568
2569 return hasSuccessor;
2570 }
2571
2572 void KItemListView::disconnectRoleEditingSignals(int index)
2573 {
2574 KItemListWidget* widget = m_visibleItems.value(index);
2575 if (!widget) {
2576 return;
2577 }
2578
2579 widget->disconnect(SIGNAL(roleEditingCanceled(int,QByteArray,QVariant)), this);
2580 widget->disconnect(SIGNAL(roleEditingFinished(int,QByteArray,QVariant)), this);
2581 }
2582
2583 int KItemListView::calculateAutoScrollingIncrement(int pos, int range, int oldInc)
2584 {
2585 int inc = 0;
2586
2587 const int minSpeed = 4;
2588 const int maxSpeed = 128;
2589 const int speedLimiter = 96;
2590 const int autoScrollBorder = 64;
2591
2592 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2593 // This assures that the autoscrolling speed grows gradually.
2594 const int incLimiter = 1;
2595
2596 if (pos < autoScrollBorder) {
2597 inc = -minSpeed + qAbs(pos - autoScrollBorder) * (pos - autoScrollBorder) / speedLimiter;
2598 inc = qMax(inc, -maxSpeed);
2599 inc = qMax(inc, oldInc - incLimiter);
2600 } else if (pos > range - autoScrollBorder) {
2601 inc = minSpeed + qAbs(pos - range + autoScrollBorder) * (pos - range + autoScrollBorder) / speedLimiter;
2602 inc = qMin(inc, maxSpeed);
2603 inc = qMin(inc, oldInc + incLimiter);
2604 }
2605
2606 return inc;
2607 }
2608
2609 int KItemListView::itemsPerSize(qreal size, qreal itemSize, qreal itemMargin)
2610 {
2611 const qreal availableSize = size - itemMargin;
2612 const int count = availableSize / (itemSize + itemMargin);
2613 return count;
2614 }
2615
2616
2617
2618 KItemListCreatorBase::~KItemListCreatorBase()
2619 {
2620 qDeleteAll(m_recycleableWidgets);
2621 qDeleteAll(m_createdWidgets);
2622 }
2623
2624 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget* widget)
2625 {
2626 m_createdWidgets.insert(widget);
2627 }
2628
2629 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget* widget)
2630 {
2631 Q_ASSERT(m_createdWidgets.contains(widget));
2632 m_createdWidgets.remove(widget);
2633
2634 if (m_recycleableWidgets.count() < 100) {
2635 m_recycleableWidgets.append(widget);
2636 widget->setVisible(false);
2637 } else {
2638 delete widget;
2639 }
2640 }
2641
2642 QGraphicsWidget* KItemListCreatorBase::popRecycleableWidget()
2643 {
2644 if (m_recycleableWidgets.isEmpty()) {
2645 return 0;
2646 }
2647
2648 QGraphicsWidget* widget = m_recycleableWidgets.takeLast();
2649 m_createdWidgets.insert(widget);
2650 return widget;
2651 }
2652
2653 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2654 {
2655 }
2656
2657 void KItemListWidgetCreatorBase::recycle(KItemListWidget* widget)
2658 {
2659 widget->setParentItem(0);
2660 widget->setOpacity(1.0);
2661 pushRecycleableWidget(widget);
2662 }
2663
2664 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2665 {
2666 }
2667
2668 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader* header)
2669 {
2670 header->setOpacity(1.0);
2671 pushRecycleableWidget(header);
2672 }
2673
2674 #include "kitemlistview.moc"