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