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