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