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