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