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