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