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