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