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