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