]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kitemlistview.cpp
Merge remote-tracking branch 'fork/work/zakharafoniam/useful-groups'
[dolphin.git] / src / kitemviews / kitemlistview.cpp
1 /*
2 * SPDX-FileCopyrightText: 2011 Peter Penz <peter.penz19@gmail.com>
3 *
4 * Based on the Itemviews NG project from Trolltech Labs
5 *
6 * SPDX-License-Identifier: GPL-2.0-or-later
7 */
8
9 #include "kitemlistview.h"
10
11 #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) {
754 return;
755 }
756 if (m_editingRole || m_animation->isStarted(widget)) {
757 Q_EMIT widget->roleEditingCanceled(index, role, QVariant());
758 return;
759 }
760
761 m_editingRole = true;
762 m_controller->selectionManager()->setCurrentItem(index);
763 widget->setEditedRole(role);
764
765 connect(widget, &KItemListWidget::roleEditingCanceled, this, &KItemListView::slotRoleEditingCanceled);
766 connect(widget, &KItemListWidget::roleEditingFinished, this, &KItemListView::slotRoleEditingFinished);
767
768 connect(this, &KItemListView::scrollOffsetChanged, widget, &KStandardItemListWidget::finishRoleEditing);
769 }
770
771 void KItemListView::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
772 {
773 QGraphicsWidget::paint(painter, option, widget);
774
775 for (auto animation : std::as_const(m_rubberBandAnimations)) {
776 QRectF rubberBandRect = animation->property(RubberPropertyName).toRectF();
777
778 const QPointF topLeft = rubberBandRect.topLeft();
779 if (scrollOrientation() == Qt::Vertical) {
780 rubberBandRect.moveTo(topLeft.x(), topLeft.y() - scrollOffset());
781 } else {
782 rubberBandRect.moveTo(topLeft.x() - scrollOffset(), topLeft.y());
783 }
784
785 QStyleOptionRubberBand opt;
786 initStyleOption(&opt);
787 opt.shape = QRubberBand::Rectangle;
788 opt.opaque = false;
789 opt.rect = rubberBandRect.toRect();
790
791 painter->save();
792
793 painter->setOpacity(animation->currentValue().toReal());
794 style()->drawControl(QStyle::CE_RubberBand, &opt, painter);
795
796 painter->restore();
797 }
798
799 if (m_rubberBand->isActive()) {
800 QRectF rubberBandRect = QRectF(m_rubberBand->startPosition(), m_rubberBand->endPosition()).normalized();
801
802 const QPointF topLeft = rubberBandRect.topLeft();
803 if (scrollOrientation() == Qt::Vertical) {
804 rubberBandRect.moveTo(topLeft.x(), topLeft.y() - scrollOffset());
805 } else {
806 rubberBandRect.moveTo(topLeft.x() - scrollOffset(), topLeft.y());
807 }
808
809 QStyleOptionRubberBand opt;
810 initStyleOption(&opt);
811 opt.shape = QRubberBand::Rectangle;
812 opt.opaque = false;
813 opt.rect = rubberBandRect.toRect();
814 style()->drawControl(QStyle::CE_RubberBand, &opt, painter);
815 }
816
817 if (m_tapAndHoldIndicator->isActive()) {
818 const QPointF indicatorSize = m_tapAndHoldIndicator->endPosition();
819 const QRectF rubberBandRect =
820 QRectF(m_tapAndHoldIndicator->startPosition() - indicatorSize, (m_tapAndHoldIndicator->startPosition()) + indicatorSize).normalized();
821 QStyleOptionRubberBand opt;
822 initStyleOption(&opt);
823 opt.shape = QRubberBand::Rectangle;
824 opt.opaque = false;
825 opt.rect = rubberBandRect.toRect();
826 style()->drawControl(QStyle::CE_RubberBand, &opt, painter);
827 }
828
829 if (!m_dropIndicator.isEmpty()) {
830 const QRectF r = m_dropIndicator.toRect();
831
832 QColor color = palette().brush(QPalette::Normal, QPalette::Text).color();
833 painter->setPen(color);
834
835 // TODO: The following implementation works only for a vertical scroll-orientation
836 // and assumes a height of the m_draggingInsertIndicator of 1.
837 Q_ASSERT(r.height() == 1);
838 painter->drawLine(r.left() + 1, r.top(), r.right() - 1, r.top());
839
840 color.setAlpha(128);
841 painter->setPen(color);
842 painter->drawRect(r.left(), r.top() - 1, r.width() - 1, 2);
843 }
844 }
845
846 void KItemListView::setStatusBarOffset(int offset)
847 {
848 if (m_statusBarOffset != offset) {
849 m_statusBarOffset = offset;
850 if (m_layouter) {
851 m_layouter->setStatusBarOffset(offset);
852 }
853 }
854 }
855
856 QVariant KItemListView::itemChange(GraphicsItemChange change, const QVariant &value)
857 {
858 if (change == QGraphicsItem::ItemSceneHasChanged && scene()) {
859 if (!scene()->views().isEmpty()) {
860 m_styleOption.palette = scene()->views().at(0)->palette();
861 }
862 }
863 return QGraphicsItem::itemChange(change, value);
864 }
865
866 void KItemListView::setItemSize(const QSizeF &size)
867 {
868 const QSizeF previousSize = m_itemSize;
869 if (size == previousSize) {
870 return;
871 }
872
873 // Skip animations when the number of rows or columns
874 // are changed in the grid layout. Although the animation
875 // engine can handle this usecase, it looks obtrusive.
876 const bool animate = !changesItemGridLayout(m_layouter->size(), size, m_layouter->itemMargin());
877
878 const bool alternateBackgroundsChanged = m_alternateBackgrounds && ((m_itemSize.isEmpty() && !size.isEmpty()) || (!m_itemSize.isEmpty() && size.isEmpty()));
879
880 m_itemSize = size;
881
882 if (alternateBackgroundsChanged) {
883 // For an empty item size alternate backgrounds are drawn if more than
884 // one role is shown. Assure that the backgrounds for visible items are
885 // updated when changing the size in this context.
886 updateAlternateBackgrounds();
887 }
888
889 if (size.isEmpty()) {
890 if (m_headerWidget->automaticColumnResizing()) {
891 updatePreferredColumnWidths();
892 } else {
893 // Only apply the changed height and respect the header widths
894 // set by the user
895 const qreal currentWidth = m_layouter->itemSize().width();
896 const QSizeF newSize(currentWidth, size.height());
897 m_layouter->setItemSize(newSize);
898 }
899 } else {
900 m_layouter->setItemSize(size);
901 }
902
903 m_sizeHintResolver->clearCache();
904 doLayout(animate ? Animation : NoAnimation);
905 onItemSizeChanged(size, previousSize);
906 }
907
908 void KItemListView::setStyleOption(const KItemListStyleOption &option)
909 {
910 if (m_styleOption == option) {
911 return;
912 }
913
914 const KItemListStyleOption previousOption = m_styleOption;
915 m_styleOption = option;
916
917 bool animate = true;
918 const QSizeF margin(option.horizontalMargin, option.verticalMargin);
919 if (margin != m_layouter->itemMargin()) {
920 // Skip animations when the number of rows or columns
921 // are changed in the grid layout. Although the animation
922 // engine can handle this usecase, it looks obtrusive.
923 animate = !changesItemGridLayout(m_layouter->size(), m_layouter->itemSize(), margin);
924 m_layouter->setItemMargin(margin);
925 }
926
927 if (m_grouped) {
928 updateGroupHeaderHeight();
929 }
930
931 if (animate && (previousOption.maxTextLines != option.maxTextLines || previousOption.maxTextWidth != option.maxTextWidth)) {
932 // Animating a change of the maximum text size just results in expensive
933 // temporary eliding and clipping operations and does not look good visually.
934 animate = false;
935 }
936
937 QHashIterator<int, KItemListWidget *> it(m_visibleItems);
938 while (it.hasNext()) {
939 it.next();
940 it.value()->setStyleOption(option);
941 }
942
943 m_sizeHintResolver->clearCache();
944 m_layouter->markAsDirty();
945 doLayout(animate ? Animation : NoAnimation);
946
947 if (m_itemSize.isEmpty()) {
948 updatePreferredColumnWidths();
949 }
950
951 onStyleOptionChanged(option, previousOption);
952 }
953
954 void KItemListView::setScrollOrientation(Qt::Orientation orientation)
955 {
956 const Qt::Orientation previousOrientation = m_layouter->scrollOrientation();
957 if (orientation == previousOrientation) {
958 return;
959 }
960
961 m_layouter->setScrollOrientation(orientation);
962 m_animation->setScrollOrientation(orientation);
963 m_sizeHintResolver->clearCache();
964
965 if (m_grouped) {
966 QMutableHashIterator<KItemListWidget *, KItemListGroupHeader *> it(m_visibleGroups);
967 while (it.hasNext()) {
968 it.next();
969 it.value()->setScrollOrientation(orientation);
970 }
971 updateGroupHeaderHeight();
972 }
973
974 doLayout(NoAnimation);
975
976 onScrollOrientationChanged(orientation, previousOrientation);
977 Q_EMIT scrollOrientationChanged(orientation, previousOrientation);
978 }
979
980 Qt::Orientation KItemListView::scrollOrientation() const
981 {
982 return m_layouter->scrollOrientation();
983 }
984
985 KItemListWidgetCreatorBase *KItemListView::defaultWidgetCreator() const
986 {
987 return nullptr;
988 }
989
990 KItemListGroupHeaderCreatorBase *KItemListView::defaultGroupHeaderCreator() const
991 {
992 return nullptr;
993 }
994
995 void KItemListView::initializeItemListWidget(KItemListWidget *item)
996 {
997 Q_UNUSED(item)
998 }
999
1000 bool KItemListView::itemSizeHintUpdateRequired(const QSet<QByteArray> &changedRoles) const
1001 {
1002 Q_UNUSED(changedRoles)
1003 return true;
1004 }
1005
1006 void KItemListView::onControllerChanged(KItemListController *current, KItemListController *previous)
1007 {
1008 Q_UNUSED(current)
1009 Q_UNUSED(previous)
1010 }
1011
1012 void KItemListView::onModelChanged(KItemModelBase *current, KItemModelBase *previous)
1013 {
1014 Q_UNUSED(current)
1015 Q_UNUSED(previous)
1016 }
1017
1018 void KItemListView::onScrollOrientationChanged(Qt::Orientation current, Qt::Orientation previous)
1019 {
1020 Q_UNUSED(current)
1021 Q_UNUSED(previous)
1022 }
1023
1024 void KItemListView::onItemSizeChanged(const QSizeF &current, const QSizeF &previous)
1025 {
1026 Q_UNUSED(current)
1027 Q_UNUSED(previous)
1028 }
1029
1030 void KItemListView::onScrollOffsetChanged(qreal current, qreal previous)
1031 {
1032 Q_UNUSED(current)
1033 Q_UNUSED(previous)
1034 }
1035
1036 void KItemListView::onVisibleRolesChanged(const QList<QByteArray> &current, const QList<QByteArray> &previous)
1037 {
1038 Q_UNUSED(current)
1039 Q_UNUSED(previous)
1040 }
1041
1042 void KItemListView::onStyleOptionChanged(const KItemListStyleOption &current, const KItemListStyleOption &previous)
1043 {
1044 Q_UNUSED(current)
1045 Q_UNUSED(previous)
1046 }
1047
1048 void KItemListView::onHighlightEntireRowChanged(bool highlightEntireRow)
1049 {
1050 Q_UNUSED(highlightEntireRow)
1051 }
1052
1053 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding)
1054 {
1055 Q_UNUSED(supportsExpanding)
1056 }
1057
1058 void KItemListView::onTransactionBegin()
1059 {
1060 }
1061
1062 void KItemListView::onTransactionEnd()
1063 {
1064 }
1065
1066 bool KItemListView::event(QEvent *event)
1067 {
1068 switch (event->type()) {
1069 case QEvent::PaletteChange:
1070 updatePalette();
1071 break;
1072
1073 case QEvent::FontChange:
1074 updateFont();
1075 break;
1076
1077 case QEvent::FocusIn:
1078 focusInEvent(static_cast<QFocusEvent *>(event));
1079 event->accept();
1080 return true;
1081 break;
1082
1083 case QEvent::FocusOut:
1084 focusOutEvent(static_cast<QFocusEvent *>(event));
1085 event->accept();
1086 return true;
1087 break;
1088
1089 default:
1090 // Forward all other events to the controller and handle them there
1091 if (!m_editingRole && m_controller && m_controller->processEvent(event, transform())) {
1092 event->accept();
1093 return true;
1094 }
1095 }
1096
1097 return QGraphicsWidget::event(event);
1098 }
1099
1100 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent *event)
1101 {
1102 m_mousePos = transform().map(event->pos());
1103 event->accept();
1104 }
1105
1106 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
1107 {
1108 QGraphicsWidget::mouseMoveEvent(event);
1109
1110 m_mousePos = transform().map(event->pos());
1111 if (m_autoScrollTimer && !m_autoScrollTimer->isActive()) {
1112 m_autoScrollTimer->start(InitialAutoScrollDelay);
1113 }
1114 }
1115
1116 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
1117 {
1118 event->setAccepted(true);
1119 setAutoScroll(true);
1120 }
1121
1122 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent *event)
1123 {
1124 QGraphicsWidget::dragMoveEvent(event);
1125
1126 m_mousePos = transform().map(event->pos());
1127 if (m_autoScrollTimer && !m_autoScrollTimer->isActive()) {
1128 m_autoScrollTimer->start(InitialAutoScrollDelay);
1129 }
1130 }
1131
1132 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
1133 {
1134 QGraphicsWidget::dragLeaveEvent(event);
1135 setAutoScroll(false);
1136 }
1137
1138 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent *event)
1139 {
1140 QGraphicsWidget::dropEvent(event);
1141 setAutoScroll(false);
1142 }
1143
1144 QList<KItemListWidget *> KItemListView::visibleItemListWidgets() const
1145 {
1146 return m_visibleItems.values();
1147 }
1148
1149 void KItemListView::updateFont()
1150 {
1151 if (scene() && !scene()->views().isEmpty()) {
1152 KItemListStyleOption option = styleOption();
1153 option.font = scene()->views().first()->font();
1154 option.fontMetrics = QFontMetrics(option.font);
1155
1156 setStyleOption(option);
1157 }
1158 }
1159
1160 void KItemListView::updatePalette()
1161 {
1162 KItemListStyleOption option = styleOption();
1163 option.palette = palette();
1164 setStyleOption(option);
1165 }
1166
1167 void KItemListView::slotItemsInserted(const KItemRangeList &itemRanges)
1168 {
1169 if (m_itemSize.isEmpty()) {
1170 updatePreferredColumnWidths(itemRanges);
1171 }
1172
1173 const bool hasMultipleRanges = (itemRanges.count() > 1);
1174 if (hasMultipleRanges) {
1175 beginTransaction();
1176 }
1177
1178 m_layouter->markAsDirty();
1179
1180 m_sizeHintResolver->itemsInserted(itemRanges);
1181
1182 int previouslyInsertedCount = 0;
1183 for (const KItemRange &range : itemRanges) {
1184 // range.index is related to the model before anything has been inserted.
1185 // As in each loop the current item-range gets inserted the index must
1186 // be increased by the already previously inserted items.
1187 const int index = range.index + previouslyInsertedCount;
1188 const int count = range.count;
1189 if (index < 0 || count <= 0) {
1190 qCWarning(DolphinDebug) << "Invalid item range (index:" << index << ", count:" << count << ")";
1191 continue;
1192 }
1193 previouslyInsertedCount += count;
1194
1195 // Determine which visible items must be moved
1196 QList<int> itemsToMove;
1197 QHashIterator<int, KItemListWidget *> it(m_visibleItems);
1198 while (it.hasNext()) {
1199 it.next();
1200 const int visibleItemIndex = it.key();
1201 if (visibleItemIndex >= index) {
1202 itemsToMove.append(visibleItemIndex);
1203 }
1204 }
1205
1206 // Update the indexes of all KItemListWidget instances that are located
1207 // after the inserted items. It is important to adjust the indexes in the order
1208 // from the highest index to the lowest index to prevent overlaps when setting the new index.
1209 std::sort(itemsToMove.begin(), itemsToMove.end());
1210 for (int i = itemsToMove.count() - 1; i >= 0; --i) {
1211 KItemListWidget *widget = m_visibleItems.value(itemsToMove[i]);
1212 Q_ASSERT(widget);
1213 const int newIndex = widget->index() + count;
1214 if (hasMultipleRanges) {
1215 setWidgetIndex(widget, newIndex);
1216 } else {
1217 // Try to animate the moving of the item
1218 moveWidgetToIndex(widget, newIndex);
1219 }
1220 }
1221
1222 if (m_model->count() == count && m_activeTransactions == 0) {
1223 // Check whether a scrollbar is required to show the inserted items. In this case
1224 // the size of the layouter will be decreased before calling doLayout(): This prevents
1225 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
1226 const bool verticalScrollOrientation = (scrollOrientation() == Qt::Vertical);
1227 const bool decreaseLayouterSize = (verticalScrollOrientation && maximumScrollOffset() > size().height())
1228 || (!verticalScrollOrientation && maximumScrollOffset() > size().width());
1229 if (decreaseLayouterSize) {
1230 const int scrollBarExtent = style()->pixelMetric(QStyle::PM_ScrollBarExtent);
1231
1232 int scrollbarSpacing = 0;
1233 if (style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents)) {
1234 scrollbarSpacing = style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing);
1235 }
1236
1237 QSizeF layouterSize = m_layouter->size();
1238 if (verticalScrollOrientation) {
1239 layouterSize.rwidth() -= scrollBarExtent + scrollbarSpacing;
1240 } else {
1241 layouterSize.rheight() -= scrollBarExtent + scrollbarSpacing;
1242 }
1243 m_layouter->setSize(layouterSize);
1244 }
1245 }
1246
1247 if (!hasMultipleRanges) {
1248 doLayout(animateChangedItemCount(count) ? Animation : NoAnimation, index, count);
1249 updateSiblingsInformation();
1250 }
1251 }
1252
1253 if (m_controller) {
1254 m_controller->selectionManager()->itemsInserted(itemRanges);
1255 }
1256
1257 if (hasMultipleRanges) {
1258 m_endTransactionAnimationHint = NoAnimation;
1259 endTransaction();
1260
1261 updateSiblingsInformation();
1262 }
1263
1264 if (m_grouped && (hasMultipleRanges || itemRanges.first().count < m_model->count())) {
1265 // In case if items of the same group have been inserted before an item that
1266 // currently represents the first item of the group, the group header of
1267 // this item must be removed.
1268 updateVisibleGroupHeaders();
1269 }
1270
1271 if (useAlternateBackgrounds()) {
1272 updateAlternateBackgrounds();
1273 }
1274 }
1275
1276 void KItemListView::slotItemsRemoved(const KItemRangeList &itemRanges)
1277 {
1278 if (m_itemSize.isEmpty()) {
1279 // Don't pass the item-range: The preferred column-widths of
1280 // all items must be adjusted when removing items.
1281 updatePreferredColumnWidths();
1282 }
1283
1284 const bool hasMultipleRanges = (itemRanges.count() > 1);
1285 if (hasMultipleRanges) {
1286 beginTransaction();
1287 }
1288
1289 m_layouter->markAsDirty();
1290
1291 m_sizeHintResolver->itemsRemoved(itemRanges);
1292
1293 for (int i = itemRanges.count() - 1; i >= 0; --i) {
1294 const KItemRange &range = itemRanges[i];
1295 const int index = range.index;
1296 const int count = range.count;
1297 if (index < 0 || count <= 0) {
1298 qCWarning(DolphinDebug) << "Invalid item range (index:" << index << ", count:" << count << ")";
1299 continue;
1300 }
1301
1302 const int firstRemovedIndex = index;
1303 const int lastRemovedIndex = index + count - 1;
1304
1305 // Remember which items have to be moved because they are behind the removed range.
1306 QVector<int> itemsToMove;
1307
1308 // Remove all KItemListWidget instances that got deleted
1309 // Iterate over a const copy because the container is mutated within the loop
1310 // directly and in `recycleWidget()` (https://bugs.kde.org/show_bug.cgi?id=428374)
1311 const auto visibleItems = m_visibleItems;
1312 for (KItemListWidget *widget : visibleItems) {
1313 const int i = widget->index();
1314 if (i < firstRemovedIndex) {
1315 continue;
1316 } else if (i > lastRemovedIndex) {
1317 itemsToMove.append(i);
1318 continue;
1319 }
1320
1321 m_animation->stop(widget);
1322 // Stopping the animation might lead to recycling the widget if
1323 // it is invisible (see slotAnimationFinished()).
1324 // Check again whether it is still visible:
1325 if (!m_visibleItems.contains(i)) {
1326 continue;
1327 }
1328
1329 if (m_model->count() == 0 || hasMultipleRanges || !animateChangedItemCount(count)) {
1330 // Remove the widget without animation
1331 recycleWidget(widget);
1332 } else {
1333 // Animate the removing of the items. Special case: When removing an item there
1334 // is no valid model index available anymore. For the
1335 // remove-animation the item gets removed from m_visibleItems but the widget
1336 // will stay alive until the animation has been finished and will
1337 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1338 m_visibleItems.remove(i);
1339 widget->setIndex(-1);
1340 m_animation->start(widget, KItemListViewAnimation::DeleteAnimation);
1341 }
1342 }
1343
1344 // Update the indexes of all KItemListWidget instances that are located
1345 // after the deleted items. It is important to update them in ascending
1346 // order to prevent overlaps when setting the new index.
1347 std::sort(itemsToMove.begin(), itemsToMove.end());
1348 for (int i : std::as_const(itemsToMove)) {
1349 KItemListWidget *widget = m_visibleItems.value(i);
1350 Q_ASSERT(widget);
1351 const int newIndex = i - count;
1352 if (hasMultipleRanges) {
1353 setWidgetIndex(widget, newIndex);
1354 } else {
1355 // Try to animate the moving of the item
1356 moveWidgetToIndex(widget, newIndex);
1357 }
1358 }
1359
1360 if (!hasMultipleRanges) {
1361 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1362 // assumes an updated geometry. If items are removed during an active transaction,
1363 // the transaction will be temporary deactivated so that doLayout() triggers a
1364 // geometry update if necessary.
1365 const int activeTransactions = m_activeTransactions;
1366 m_activeTransactions = 0;
1367 doLayout(animateChangedItemCount(count) ? Animation : NoAnimation, index, -count);
1368 m_activeTransactions = activeTransactions;
1369 updateSiblingsInformation();
1370 }
1371 }
1372
1373 if (m_controller) {
1374 m_controller->selectionManager()->itemsRemoved(itemRanges);
1375 }
1376
1377 if (hasMultipleRanges) {
1378 m_endTransactionAnimationHint = NoAnimation;
1379 endTransaction();
1380 updateSiblingsInformation();
1381 }
1382
1383 if (m_grouped && (hasMultipleRanges || m_model->count() > 0)) {
1384 // In case if the first item of a group has been removed, the group header
1385 // must be applied to the next visible item.
1386 updateVisibleGroupHeaders();
1387 }
1388
1389 if (useAlternateBackgrounds()) {
1390 updateAlternateBackgrounds();
1391 }
1392 }
1393
1394 void KItemListView::slotItemsMoved(const KItemRange &itemRange, const QList<int> &movedToIndexes)
1395 {
1396 m_sizeHintResolver->itemsMoved(itemRange, movedToIndexes);
1397 m_layouter->markAsDirty();
1398
1399 if (m_controller) {
1400 m_controller->selectionManager()->itemsMoved(itemRange, movedToIndexes);
1401 }
1402
1403 const int firstVisibleMovedIndex = qMax(firstVisibleIndex(), itemRange.index);
1404 const int lastVisibleMovedIndex = qMin(lastVisibleIndex(), itemRange.index + itemRange.count - 1);
1405
1406 /// Represents an item that was moved while being edited.
1407 struct MovedEditedItem {
1408 int movedToIndex;
1409 QByteArray editedRole;
1410 };
1411 std::optional<MovedEditedItem> movedEditedItem;
1412 for (int index = firstVisibleMovedIndex; index <= lastVisibleMovedIndex; ++index) {
1413 KItemListWidget *widget = m_visibleItems.value(index);
1414 if (widget) {
1415 if (m_editingRole && !widget->editedRole().isEmpty()) {
1416 movedEditedItem = {movedToIndexes[index - itemRange.index], widget->editedRole()};
1417 disconnectRoleEditingSignals(index);
1418 m_editingRole = false;
1419 }
1420 updateWidgetProperties(widget, index);
1421 initializeItemListWidget(widget);
1422 }
1423 }
1424
1425 doLayout(NoAnimation);
1426 updateSiblingsInformation();
1427
1428 if (movedEditedItem) {
1429 editRole(movedEditedItem->movedToIndex, movedEditedItem->editedRole);
1430 }
1431 }
1432
1433 void KItemListView::slotItemsChanged(const KItemRangeList &itemRanges, const QSet<QByteArray> &roles)
1434 {
1435 const bool updateSizeHints = itemSizeHintUpdateRequired(roles);
1436 if (updateSizeHints && m_itemSize.isEmpty()) {
1437 updatePreferredColumnWidths(itemRanges);
1438 }
1439
1440 for (const KItemRange &itemRange : itemRanges) {
1441 const int index = itemRange.index;
1442 const int count = itemRange.count;
1443
1444 if (updateSizeHints) {
1445 m_sizeHintResolver->itemsChanged(index, count, roles);
1446 m_layouter->markAsDirty();
1447 }
1448
1449 // Apply the changed roles to the visible item-widgets
1450 const int lastIndex = index + count - 1;
1451 for (int i = index; i <= lastIndex; ++i) {
1452 KItemListWidget *widget = m_visibleItems.value(i);
1453 if (widget) {
1454 widget->setData(m_model->data(i), roles);
1455 }
1456 }
1457
1458 if (m_grouped && roles.contains(m_model->sortRole())) {
1459 // The sort-role has been changed which might result
1460 // in modified group headers
1461 updateVisibleGroupHeaders();
1462 doLayout(NoAnimation);
1463 }
1464 }
1465 doLayout(NoAnimation);
1466 }
1467
1468 void KItemListView::slotGroupsChanged()
1469 {
1470 updateVisibleGroupHeaders();
1471 doLayout(NoAnimation);
1472 updateSiblingsInformation();
1473 }
1474
1475 void KItemListView::slotGroupedSortingChanged(bool current)
1476 {
1477 m_grouped = current;
1478 m_layouter->markAsDirty();
1479
1480 if (m_grouped) {
1481 updateGroupHeaderHeight();
1482 } else {
1483 // Clear all visible headers. Note that the QHashIterator takes a copy of
1484 // m_visibleGroups. Therefore, it remains valid even if items are removed
1485 // from m_visibleGroups in recycleGroupHeaderForWidget().
1486 QHashIterator<KItemListWidget *, KItemListGroupHeader *> it(m_visibleGroups);
1487 while (it.hasNext()) {
1488 it.next();
1489 recycleGroupHeaderForWidget(it.key());
1490 }
1491 Q_ASSERT(m_visibleGroups.isEmpty());
1492 }
1493
1494 if (useAlternateBackgrounds()) {
1495 // Changing the group mode requires to update the alternate backgrounds
1496 // as with the enabled group mode the altering is done on base of the first
1497 // group item.
1498 updateAlternateBackgrounds();
1499 }
1500 updateSiblingsInformation();
1501 doLayout(NoAnimation);
1502 }
1503
1504 void KItemListView::slotSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous)
1505 {
1506 Q_UNUSED(current)
1507 Q_UNUSED(previous)
1508 if (m_grouped) {
1509 updateVisibleGroupHeaders();
1510 doLayout(NoAnimation);
1511 }
1512 }
1513
1514 void KItemListView::slotSortRoleChanged(const QByteArray &current, const QByteArray &previous)
1515 {
1516 Q_UNUSED(current)
1517 Q_UNUSED(previous)
1518 if (m_grouped) {
1519 updateVisibleGroupHeaders();
1520 doLayout(NoAnimation);
1521 }
1522 }
1523
1524 void KItemListView::slotGroupOrderChanged(Qt::SortOrder current, Qt::SortOrder previous)
1525 {
1526 Q_UNUSED(current)
1527 Q_UNUSED(previous)
1528 if (m_grouped) {
1529 updateVisibleGroupHeaders();
1530 doLayout(NoAnimation);
1531 }
1532 }
1533
1534 void KItemListView::slotGroupRoleChanged(const QByteArray &current, const QByteArray &previous)
1535 {
1536 Q_UNUSED(current)
1537 Q_UNUSED(previous)
1538 if (m_grouped) {
1539 updateVisibleGroupHeaders();
1540 doLayout(NoAnimation);
1541 }
1542 }
1543
1544 void KItemListView::slotCurrentChanged(int current, int previous)
1545 {
1546 // In SingleSelection mode (e.g., in the Places Panel), the current item is
1547 // always the selected item. It is not necessary to highlight the current item then.
1548 if (m_controller->selectionBehavior() != KItemListController::SingleSelection) {
1549 KItemListWidget *previousWidget = m_visibleItems.value(previous, nullptr);
1550 if (previousWidget) {
1551 previousWidget->setCurrent(false);
1552 }
1553
1554 KItemListWidget *currentWidget = m_visibleItems.value(current, nullptr);
1555 if (currentWidget) {
1556 currentWidget->setCurrent(true);
1557 }
1558 }
1559 #ifndef QT_NO_ACCESSIBILITY
1560 if (current != previous && QAccessible::isActive()) {
1561 static_cast<KItemListViewAccessible *>(QAccessible::queryAccessibleInterface(this))->announceCurrentItem();
1562 }
1563 #endif
1564 }
1565
1566 void KItemListView::slotSelectionChanged(const KItemSet &current, const KItemSet &previous)
1567 {
1568 QHashIterator<int, KItemListWidget *> it(m_visibleItems);
1569 while (it.hasNext()) {
1570 it.next();
1571 const int index = it.key();
1572 KItemListWidget *widget = it.value();
1573 const bool isSelected(current.contains(index));
1574 widget->setSelected(isSelected);
1575
1576 #ifndef QT_NO_ACCESSIBILITY
1577 if (!QAccessible::isActive()) {
1578 continue;
1579 }
1580 // Let the screen reader announce "selected" or "not selected" for the active item.
1581 const bool wasSelected(previous.contains(index));
1582 if (isSelected != wasSelected) {
1583 QAccessibleEvent accessibleSelectionChangedEvent(this, QAccessible::SelectionAdd);
1584 accessibleSelectionChangedEvent.setChild(index);
1585 QAccessible::updateAccessibility(&accessibleSelectionChangedEvent);
1586 }
1587 }
1588 #else
1589 }
1590 Q_UNUSED(previous)
1591 #endif
1592 }
1593
1594 void KItemListView::slotAnimationFinished(QGraphicsWidget *widget, KItemListViewAnimation::AnimationType type)
1595 {
1596 KItemListWidget *itemListWidget = qobject_cast<KItemListWidget *>(widget);
1597 Q_ASSERT(itemListWidget);
1598
1599 if (type == KItemListViewAnimation::DeleteAnimation) {
1600 // As we recycle the widget in this case it is important to assure that no
1601 // other animation has been started. This is a convention in KItemListView and
1602 // not a requirement defined by KItemListViewAnimation.
1603 Q_ASSERT(!m_animation->isStarted(itemListWidget));
1604
1605 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1606 // by m_visibleWidgets and must be deleted manually after the animation has
1607 // been finished.
1608 recycleGroupHeaderForWidget(itemListWidget);
1609 widgetCreator()->recycle(itemListWidget);
1610 } else {
1611 const int index = itemListWidget->index();
1612 const bool invisible = (index < m_layouter->firstVisibleIndex()) || (index > m_layouter->lastVisibleIndex());
1613 if (invisible && !m_animation->isStarted(itemListWidget)) {
1614 recycleWidget(itemListWidget);
1615 }
1616 }
1617 }
1618
1619 void KItemListView::slotRubberBandPosChanged()
1620 {
1621 update();
1622 }
1623
1624 void KItemListView::slotRubberBandActivationChanged(bool active)
1625 {
1626 if (active) {
1627 connect(m_rubberBand, &KItemListRubberBand::startPositionChanged, this, &KItemListView::slotRubberBandPosChanged);
1628 connect(m_rubberBand, &KItemListRubberBand::endPositionChanged, this, &KItemListView::slotRubberBandPosChanged);
1629 m_skipAutoScrollForRubberBand = true;
1630 } else {
1631 QRectF rubberBandRect = QRectF(m_rubberBand->startPosition(), m_rubberBand->endPosition()).normalized();
1632
1633 auto animation = new QVariantAnimation(this);
1634 animation->setStartValue(1.0);
1635 animation->setEndValue(0.0);
1636 animation->setDuration(RubberFadeSpeed);
1637 animation->setProperty(RubberPropertyName, rubberBandRect);
1638
1639 QEasingCurve curve;
1640 curve.setType(QEasingCurve::BezierSpline);
1641 curve.addCubicBezierSegment(QPointF(0.4, 0.0), QPointF(1.0, 1.0), QPointF(1.0, 1.0));
1642 animation->setEasingCurve(curve);
1643
1644 connect(animation, &QVariantAnimation::valueChanged, this, [=, this](const QVariant &) {
1645 update();
1646 });
1647 connect(animation, &QVariantAnimation::finished, this, [=, this]() {
1648 m_rubberBandAnimations.removeAll(animation);
1649 delete animation;
1650 });
1651 animation->start();
1652 m_rubberBandAnimations << animation;
1653
1654 disconnect(m_rubberBand, &KItemListRubberBand::startPositionChanged, this, &KItemListView::slotRubberBandPosChanged);
1655 disconnect(m_rubberBand, &KItemListRubberBand::endPositionChanged, this, &KItemListView::slotRubberBandPosChanged);
1656 m_skipAutoScrollForRubberBand = false;
1657 }
1658
1659 update();
1660 }
1661
1662 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray &role, qreal currentWidth, qreal previousWidth)
1663 {
1664 Q_UNUSED(role)
1665 Q_UNUSED(currentWidth)
1666 Q_UNUSED(previousWidth)
1667
1668 m_headerWidget->setAutomaticColumnResizing(false);
1669 applyColumnWidthsFromHeader();
1670 doLayout(NoAnimation);
1671 }
1672
1673 void KItemListView::slotSidePaddingChanged(qreal width)
1674 {
1675 Q_UNUSED(width)
1676 if (m_headerWidget->automaticColumnResizing()) {
1677 applyAutomaticColumnWidths();
1678 }
1679 applyColumnWidthsFromHeader();
1680 doLayout(NoAnimation);
1681 }
1682
1683 void KItemListView::slotHeaderColumnMoved(const QByteArray &role, int currentIndex, int previousIndex)
1684 {
1685 Q_ASSERT(m_visibleRoles[previousIndex] == role);
1686
1687 const QList<QByteArray> previous = m_visibleRoles;
1688
1689 QList<QByteArray> current = m_visibleRoles;
1690 current.removeAt(previousIndex);
1691 current.insert(currentIndex, role);
1692
1693 setVisibleRoles(current);
1694
1695 Q_EMIT visibleRolesChanged(current, previous);
1696 }
1697
1698 void KItemListView::triggerAutoScrolling()
1699 {
1700 if (!m_autoScrollTimer) {
1701 return;
1702 }
1703
1704 int pos = 0;
1705 int visibleSize = 0;
1706 if (scrollOrientation() == Qt::Vertical) {
1707 pos = m_mousePos.y();
1708 visibleSize = size().height();
1709 } else {
1710 pos = m_mousePos.x();
1711 visibleSize = size().width();
1712 }
1713
1714 if (m_autoScrollTimer->interval() == InitialAutoScrollDelay) {
1715 m_autoScrollIncrement = 0;
1716 }
1717
1718 m_autoScrollIncrement = calculateAutoScrollingIncrement(pos, visibleSize, m_autoScrollIncrement);
1719 if (m_autoScrollIncrement == 0) {
1720 // The mouse position is not above an autoscroll margin (the autoscroll timer
1721 // will be restarted in mouseMoveEvent())
1722 m_autoScrollTimer->stop();
1723 return;
1724 }
1725
1726 if (m_rubberBand->isActive() && m_skipAutoScrollForRubberBand) {
1727 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1728 // if the direction of the rubberband is similar to the autoscroll direction. This
1729 // prevents that starting to create a rubberband within the autoscroll margins starts
1730 // an autoscrolling.
1731
1732 const qreal minDiff = 4; // Ignore any autoscrolling if the rubberband is very small
1733 const qreal diff = (scrollOrientation() == Qt::Vertical) ? m_rubberBand->endPosition().y() - m_rubberBand->startPosition().y()
1734 : m_rubberBand->endPosition().x() - m_rubberBand->startPosition().x();
1735 if (qAbs(diff) < minDiff || (m_autoScrollIncrement < 0 && diff > 0) || (m_autoScrollIncrement > 0 && diff < 0)) {
1736 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1737 // been moved up although the autoscroll direction might be down)
1738 m_autoScrollTimer->stop();
1739 return;
1740 }
1741 }
1742
1743 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1744 // the autoscrolling may not get skipped anymore until a new rubberband is created
1745 m_skipAutoScrollForRubberBand = false;
1746
1747 const qreal maxVisibleOffset = qMax(qreal(0), maximumScrollOffset() - visibleSize);
1748 const qreal newScrollOffset = qMin(scrollOffset() + m_autoScrollIncrement, maxVisibleOffset);
1749 setScrollOffset(newScrollOffset);
1750
1751 // Trigger the autoscroll timer which will periodically call
1752 // triggerAutoScrolling()
1753 m_autoScrollTimer->start(RepeatingAutoScrollDelay);
1754 }
1755
1756 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1757 {
1758 KItemListWidget *widget = qobject_cast<KItemListWidget *>(sender());
1759 Q_ASSERT(widget);
1760 KItemListGroupHeader *groupHeader = m_visibleGroups.value(widget);
1761 Q_ASSERT(groupHeader);
1762 updateGroupHeaderLayout(widget);
1763 }
1764
1765 void KItemListView::slotRoleEditingCanceled(int index, const QByteArray &role, const QVariant &value)
1766 {
1767 disconnectRoleEditingSignals(index);
1768
1769 m_editingRole = false;
1770 Q_EMIT roleEditingCanceled(index, role, value);
1771 }
1772
1773 void KItemListView::slotRoleEditingFinished(int index, const QByteArray &role, const QVariant &value)
1774 {
1775 disconnectRoleEditingSignals(index);
1776
1777 m_editingRole = false;
1778 Q_EMIT roleEditingFinished(index, role, value);
1779 }
1780
1781 void KItemListView::setController(KItemListController *controller)
1782 {
1783 if (m_controller != controller) {
1784 KItemListController *previous = m_controller;
1785 if (previous) {
1786 KItemListSelectionManager *selectionManager = previous->selectionManager();
1787 disconnect(selectionManager, &KItemListSelectionManager::currentChanged, this, &KItemListView::slotCurrentChanged);
1788 disconnect(selectionManager, &KItemListSelectionManager::selectionChanged, this, &KItemListView::slotSelectionChanged);
1789 }
1790
1791 m_controller = controller;
1792
1793 if (controller) {
1794 KItemListSelectionManager *selectionManager = controller->selectionManager();
1795 connect(selectionManager, &KItemListSelectionManager::currentChanged, this, &KItemListView::slotCurrentChanged);
1796 connect(selectionManager, &KItemListSelectionManager::selectionChanged, this, &KItemListView::slotSelectionChanged);
1797 }
1798
1799 onControllerChanged(controller, previous);
1800 }
1801 }
1802
1803 void KItemListView::setModel(KItemModelBase *model)
1804 {
1805 if (m_model == model) {
1806 return;
1807 }
1808
1809 KItemModelBase *previous = m_model;
1810
1811 if (m_model) {
1812 disconnect(m_model, &KItemModelBase::itemsChanged, this, &KItemListView::slotItemsChanged);
1813 disconnect(m_model, &KItemModelBase::itemsInserted, this, &KItemListView::slotItemsInserted);
1814 disconnect(m_model, &KItemModelBase::itemsRemoved, this, &KItemListView::slotItemsRemoved);
1815 disconnect(m_model, &KItemModelBase::itemsMoved, this, &KItemListView::slotItemsMoved);
1816 disconnect(m_model, &KItemModelBase::groupsChanged, this, &KItemListView::slotGroupsChanged);
1817 disconnect(m_model, &KItemModelBase::groupedSortingChanged, this, &KItemListView::slotGroupedSortingChanged);
1818 disconnect(m_model, &KItemModelBase::sortOrderChanged, this, &KItemListView::slotSortOrderChanged);
1819 disconnect(m_model, &KItemModelBase::sortRoleChanged, this, &KItemListView::slotSortRoleChanged);
1820 disconnect(m_model, &KItemModelBase::groupOrderChanged, this, &KItemListView::slotGroupOrderChanged);
1821 disconnect(m_model, &KItemModelBase::groupRoleChanged, this, &KItemListView::slotGroupRoleChanged);
1822
1823 m_sizeHintResolver->itemsRemoved(KItemRangeList() << KItemRange(0, m_model->count()));
1824 }
1825
1826 m_model = model;
1827 m_layouter->setModel(model);
1828 m_grouped = model->groupedSorting();
1829
1830 if (m_model) {
1831 connect(m_model, &KItemModelBase::itemsChanged, this, &KItemListView::slotItemsChanged);
1832 connect(m_model, &KItemModelBase::itemsInserted, this, &KItemListView::slotItemsInserted);
1833 connect(m_model, &KItemModelBase::itemsRemoved, this, &KItemListView::slotItemsRemoved);
1834 connect(m_model, &KItemModelBase::itemsMoved, this, &KItemListView::slotItemsMoved);
1835 connect(m_model, &KItemModelBase::groupsChanged, this, &KItemListView::slotGroupsChanged);
1836 connect(m_model, &KItemModelBase::groupedSortingChanged, this, &KItemListView::slotGroupedSortingChanged);
1837 connect(m_model, &KItemModelBase::sortOrderChanged, this, &KItemListView::slotSortOrderChanged);
1838 connect(m_model, &KItemModelBase::sortRoleChanged, this, &KItemListView::slotSortRoleChanged);
1839
1840 const int itemCount = m_model->count();
1841 if (itemCount > 0) {
1842 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount));
1843 }
1844 }
1845
1846 onModelChanged(model, previous);
1847 }
1848
1849 KItemListRubberBand *KItemListView::rubberBand() const
1850 {
1851 return m_rubberBand;
1852 }
1853
1854 void KItemListView::doLayout(LayoutAnimationHint hint, int changedIndex, int changedCount)
1855 {
1856 if (m_activeTransactions > 0) {
1857 if (hint == NoAnimation) {
1858 // As soon as at least one property change should be done without animation,
1859 // the whole transaction will be marked as not animated.
1860 m_endTransactionAnimationHint = NoAnimation;
1861 }
1862 return;
1863 }
1864
1865 if (!m_model || m_model->count() < 0) {
1866 return;
1867 }
1868
1869 int firstVisibleIndex = m_layouter->firstVisibleIndex();
1870 if (firstVisibleIndex < 0) {
1871 emitOffsetChanges();
1872 return;
1873 }
1874
1875 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1876 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1877 // is still shown if the maximum offset got decreased.
1878 const qreal visibleOffsetRange = (scrollOrientation() == Qt::Horizontal) ? size().width() : size().height();
1879 const qreal maxOffsetToShowFullRange = maximumScrollOffset() - visibleOffsetRange;
1880 if (scrollOffset() > maxOffsetToShowFullRange) {
1881 m_layouter->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange));
1882 firstVisibleIndex = m_layouter->firstVisibleIndex();
1883 }
1884
1885 const int lastVisibleIndex = m_layouter->lastVisibleIndex();
1886
1887 int firstSibblingIndex = -1;
1888 int lastSibblingIndex = -1;
1889 const bool supportsExpanding = supportsItemExpanding();
1890
1891 QList<int> reusableItems = recycleInvisibleItems(firstVisibleIndex, lastVisibleIndex, hint);
1892
1893 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1894 // instances from invisible items are reused. If no reusable items are
1895 // found then new KItemListWidget instances get created.
1896 const bool animate = (hint == Animation);
1897 for (int i = firstVisibleIndex; i <= lastVisibleIndex; ++i) {
1898 bool applyNewPos = true;
1899
1900 const QRectF itemBounds = m_layouter->itemRect(i);
1901 const QPointF newPos = itemBounds.topLeft();
1902 KItemListWidget *widget = m_visibleItems.value(i);
1903 if (!widget) {
1904 if (!reusableItems.isEmpty()) {
1905 // Reuse a KItemListWidget instance from an invisible item
1906 const int oldIndex = reusableItems.takeLast();
1907 widget = m_visibleItems.value(oldIndex);
1908 setWidgetIndex(widget, i);
1909 updateWidgetProperties(widget, i);
1910 initializeItemListWidget(widget);
1911 } else {
1912 // No reusable KItemListWidget instance is available, create a new one
1913 widget = createWidget(i);
1914 }
1915 widget->resize(itemBounds.size());
1916
1917 if (animate && changedCount < 0) {
1918 // Items have been deleted.
1919 if (i >= changedIndex) {
1920 // The item is located behind the removed range. Move the
1921 // created item to the imaginary old position outside the
1922 // view. It will get animated to the new position later.
1923 const int previousIndex = i - changedCount;
1924 const QRectF itemRect = m_layouter->itemRect(previousIndex);
1925 if (itemRect.isEmpty()) {
1926 const QPointF invisibleOldPos = (scrollOrientation() == Qt::Vertical) ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1927 widget->setPos(invisibleOldPos);
1928 } else {
1929 widget->setPos(itemRect.topLeft());
1930 }
1931 applyNewPos = false;
1932 }
1933 }
1934
1935 if (supportsExpanding && changedCount == 0) {
1936 if (firstSibblingIndex < 0) {
1937 firstSibblingIndex = i;
1938 }
1939 lastSibblingIndex = i;
1940 }
1941 }
1942
1943 if (animate) {
1944 if (m_animation->isStarted(widget, KItemListViewAnimation::MovingAnimation)) {
1945 if (m_editingRole) {
1946 Q_EMIT widget->roleEditingCanceled(widget->index(), QByteArray(), QVariant());
1947 }
1948 m_animation->start(widget, KItemListViewAnimation::MovingAnimation, newPos);
1949 applyNewPos = false;
1950 }
1951
1952 const bool itemsRemoved = (changedCount < 0);
1953 const bool itemsInserted = (changedCount > 0);
1954 if (itemsRemoved && (i >= changedIndex)) {
1955 // The item is located after the removed items. Animate the moving of the position.
1956 applyNewPos = !moveWidget(widget, newPos);
1957 } else if (itemsInserted && i >= changedIndex) {
1958 // The item is located after the first inserted item
1959 if (i <= changedIndex + changedCount - 1) {
1960 // The item is an inserted item. Animate the appearing of the item.
1961 // For performance reasons no animation is done when changedCount is equal
1962 // to all available items.
1963 if (changedCount < m_model->count()) {
1964 m_animation->start(widget, KItemListViewAnimation::CreateAnimation);
1965 }
1966 } else if (!m_animation->isStarted(widget, KItemListViewAnimation::CreateAnimation)) {
1967 // The item was already there before, so animate the moving of the position.
1968 // No moving animation is done if the item is animated by a create animation: This
1969 // prevents a "move animation mess" when inserting several ranges in parallel.
1970 applyNewPos = !moveWidget(widget, newPos);
1971 }
1972 }
1973 } else {
1974 m_animation->stop(widget);
1975 }
1976
1977 if (applyNewPos) {
1978 widget->setPos(newPos);
1979 }
1980
1981 Q_ASSERT(widget->index() == i);
1982 widget->setVisible(true);
1983
1984 bool animateIconResizing = animate;
1985
1986 if (widget->size() != itemBounds.size()) {
1987 // Resize the widget for the item to the changed size.
1988 if (animate) {
1989 // If a dynamic item size is used then no animation is done in the direction
1990 // of the dynamic size.
1991 if (m_itemSize.width() <= 0) {
1992 // The width is dynamic, apply the new width without animation.
1993 widget->resize(itemBounds.width(), widget->size().height());
1994 } else if (m_itemSize.height() <= 0) {
1995 // The height is dynamic, apply the new height without animation.
1996 widget->resize(widget->size().width(), itemBounds.height());
1997 }
1998 m_animation->start(widget, KItemListViewAnimation::ResizeAnimation, itemBounds.size());
1999 } else {
2000 widget->resize(itemBounds.size());
2001 }
2002 } else {
2003 animateIconResizing = false;
2004 }
2005
2006 const int newIconSize = widget->styleOption().iconSize;
2007 if (widget->iconSize() != newIconSize) {
2008 if (animateIconResizing) {
2009 m_animation->start(widget, KItemListViewAnimation::IconResizeAnimation, newIconSize);
2010 } else {
2011 widget->setIconSize(newIconSize);
2012 }
2013 }
2014
2015 // Updating the cell-information must be done as last step: The decision whether the
2016 // moving-animation should be started at all is based on the previous cell-information.
2017 const Cell cell(m_layouter->itemColumn(i), m_layouter->itemRow(i));
2018 m_visibleCells.insert(i, cell);
2019 }
2020
2021 // Delete invisible KItemListWidget instances that have not been reused
2022 for (int index : std::as_const(reusableItems)) {
2023 recycleWidget(m_visibleItems.value(index));
2024 }
2025
2026 if (supportsExpanding && firstSibblingIndex >= 0) {
2027 Q_ASSERT(lastSibblingIndex >= 0);
2028 updateSiblingsInformation(firstSibblingIndex, lastSibblingIndex);
2029 }
2030
2031 if (m_grouped) {
2032 // Update the layout of all visible group headers
2033 QHashIterator<KItemListWidget *, KItemListGroupHeader *> it(m_visibleGroups);
2034 while (it.hasNext()) {
2035 it.next();
2036 updateGroupHeaderLayout(it.key());
2037 }
2038 }
2039
2040 emitOffsetChanges();
2041 }
2042
2043 QList<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex, int lastVisibleIndex, LayoutAnimationHint hint)
2044 {
2045 // Determine all items that are completely invisible and might be
2046 // reused for items that just got (at least partly) visible. If the
2047 // animation hint is set to 'Animation' items that do e.g. an animated
2048 // moving of their position are not marked as invisible: This assures
2049 // that a scrolling inside the view can be done without breaking an animation.
2050
2051 QList<int> items;
2052
2053 QHashIterator<int, KItemListWidget *> it(m_visibleItems);
2054 while (it.hasNext()) {
2055 it.next();
2056
2057 KItemListWidget *widget = it.value();
2058 const int index = widget->index();
2059 const bool invisible = (index < firstVisibleIndex) || (index > lastVisibleIndex);
2060
2061 if (invisible) {
2062 if (m_animation->isStarted(widget)) {
2063 if (hint == NoAnimation) {
2064 // Stopping the animation will call KItemListView::slotAnimationFinished()
2065 // and the widget will be recycled if necessary there.
2066 m_animation->stop(widget);
2067 }
2068 } else {
2069 widget->setVisible(false);
2070 items.append(index);
2071
2072 if (m_grouped) {
2073 recycleGroupHeaderForWidget(widget);
2074 }
2075 }
2076 }
2077 }
2078
2079 return items;
2080 }
2081
2082 bool KItemListView::moveWidget(KItemListWidget *widget, const QPointF &newPos)
2083 {
2084 if (widget->pos() == newPos) {
2085 return false;
2086 }
2087
2088 bool startMovingAnim = false;
2089
2090 if (m_itemSize.isEmpty()) {
2091 // The items are not aligned in a grid but either as columns or rows.
2092 startMovingAnim = true;
2093 } else {
2094 // When having a grid the moving-animation should only be started, if it is done within
2095 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
2096 // Otherwise instead of a moving-animation a create-animation on the new position will be used
2097 // instead. This is done to prevent overlapping (and confusing) moving-animations.
2098 const int index = widget->index();
2099 const Cell cell = m_visibleCells.value(index);
2100 if (cell.column >= 0 && cell.row >= 0) {
2101 if (scrollOrientation() == Qt::Vertical) {
2102 startMovingAnim = (cell.row == m_layouter->itemRow(index));
2103 } else {
2104 startMovingAnim = (cell.column == m_layouter->itemColumn(index));
2105 }
2106 }
2107 }
2108
2109 if (startMovingAnim) {
2110 m_animation->start(widget, KItemListViewAnimation::MovingAnimation, newPos);
2111 return true;
2112 }
2113
2114 m_animation->stop(widget);
2115 m_animation->start(widget, KItemListViewAnimation::CreateAnimation);
2116 return false;
2117 }
2118
2119 void KItemListView::emitOffsetChanges()
2120 {
2121 const qreal newScrollOffset = m_layouter->scrollOffset();
2122 if (m_oldScrollOffset != newScrollOffset) {
2123 Q_EMIT scrollOffsetChanged(newScrollOffset, m_oldScrollOffset);
2124 m_oldScrollOffset = newScrollOffset;
2125 }
2126
2127 const qreal newMaximumScrollOffset = m_layouter->maximumScrollOffset();
2128 if (m_oldMaximumScrollOffset != newMaximumScrollOffset) {
2129 Q_EMIT maximumScrollOffsetChanged(newMaximumScrollOffset, m_oldMaximumScrollOffset);
2130 m_oldMaximumScrollOffset = newMaximumScrollOffset;
2131 }
2132
2133 const qreal newItemOffset = m_layouter->itemOffset();
2134 if (m_oldItemOffset != newItemOffset) {
2135 Q_EMIT itemOffsetChanged(newItemOffset, m_oldItemOffset);
2136 m_oldItemOffset = newItemOffset;
2137 }
2138
2139 const qreal newMaximumItemOffset = m_layouter->maximumItemOffset();
2140 if (m_oldMaximumItemOffset != newMaximumItemOffset) {
2141 Q_EMIT maximumItemOffsetChanged(newMaximumItemOffset, m_oldMaximumItemOffset);
2142 m_oldMaximumItemOffset = newMaximumItemOffset;
2143 }
2144 }
2145
2146 KItemListWidget *KItemListView::createWidget(int index)
2147 {
2148 KItemListWidget *widget = widgetCreator()->create(this);
2149 widget->setFlag(QGraphicsItem::ItemStacksBehindParent);
2150
2151 m_visibleItems.insert(index, widget);
2152 m_visibleCells.insert(index, Cell());
2153 updateWidgetProperties(widget, index);
2154 initializeItemListWidget(widget);
2155 return widget;
2156 }
2157
2158 void KItemListView::recycleWidget(KItemListWidget *widget)
2159 {
2160 if (m_grouped) {
2161 recycleGroupHeaderForWidget(widget);
2162 }
2163
2164 const int index = widget->index();
2165 m_visibleItems.remove(index);
2166 m_visibleCells.remove(index);
2167
2168 widgetCreator()->recycle(widget);
2169 }
2170
2171 void KItemListView::setWidgetIndex(KItemListWidget *widget, int index)
2172 {
2173 const int oldIndex = widget->index();
2174 m_visibleItems.remove(oldIndex);
2175 m_visibleCells.remove(oldIndex);
2176
2177 m_visibleItems.insert(index, widget);
2178 m_visibleCells.insert(index, Cell());
2179
2180 widget->setIndex(index);
2181 }
2182
2183 void KItemListView::moveWidgetToIndex(KItemListWidget *widget, int index)
2184 {
2185 const int oldIndex = widget->index();
2186 const Cell oldCell = m_visibleCells.value(oldIndex);
2187
2188 setWidgetIndex(widget, index);
2189
2190 const Cell newCell(m_layouter->itemColumn(index), m_layouter->itemRow(index));
2191 const bool vertical = (scrollOrientation() == Qt::Vertical);
2192 const bool updateCell = (vertical && oldCell.row == newCell.row) || (!vertical && oldCell.column == newCell.column);
2193 if (updateCell) {
2194 m_visibleCells.insert(index, newCell);
2195 }
2196 }
2197
2198 void KItemListView::setLayouterSize(const QSizeF &size, SizeType sizeType)
2199 {
2200 switch (sizeType) {
2201 case LayouterSize:
2202 m_layouter->setSize(size);
2203 break;
2204 case ItemSize:
2205 m_layouter->setItemSize(size);
2206 break;
2207 default:
2208 break;
2209 }
2210 }
2211
2212 void KItemListView::updateWidgetProperties(KItemListWidget *widget, int index)
2213 {
2214 widget->setVisibleRoles(m_visibleRoles);
2215 updateWidgetColumnWidths(widget);
2216 widget->setStyleOption(m_styleOption);
2217
2218 const KItemListSelectionManager *selectionManager = m_controller->selectionManager();
2219
2220 // In SingleSelection mode (e.g., in the Places Panel), the current item is
2221 // always the selected item. It is not necessary to highlight the current item then.
2222 if (m_controller->selectionBehavior() != KItemListController::SingleSelection) {
2223 widget->setCurrent(index == selectionManager->currentItem());
2224 }
2225 widget->setSelected(selectionManager->isSelected(index));
2226 widget->setHovered(false);
2227 widget->setEnabledSelectionToggle(enabledSelectionToggles());
2228 widget->setIndex(index);
2229 widget->setData(m_model->data(index));
2230 widget->setSiblingsInformation(QBitArray());
2231 updateAlternateBackgroundForWidget(widget);
2232
2233 if (m_grouped) {
2234 updateGroupHeaderForWidget(widget);
2235 }
2236 }
2237
2238 void KItemListView::updateGroupHeaderForWidget(KItemListWidget *widget)
2239 {
2240 Q_ASSERT(m_grouped);
2241
2242 const int index = widget->index();
2243 if (!m_layouter->isFirstGroupItem(index)) {
2244 // The widget does not represent the first item of a group
2245 // and hence requires no header
2246 recycleGroupHeaderForWidget(widget);
2247 return;
2248 }
2249
2250 const QList<QPair<int, QVariant>> groups = model()->groups();
2251 if (groups.isEmpty() || !groupHeaderCreator()) {
2252 return;
2253 }
2254
2255 KItemListGroupHeader *groupHeader = m_visibleGroups.value(widget);
2256 if (!groupHeader) {
2257 groupHeader = groupHeaderCreator()->create(this);
2258 groupHeader->setParentItem(widget);
2259 m_visibleGroups.insert(widget, groupHeader);
2260 connect(widget, &KItemListWidget::geometryChanged, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged);
2261 }
2262 Q_ASSERT(groupHeader->parentItem() == widget);
2263
2264 const int groupIndex = groupIndexForItem(index);
2265 Q_ASSERT(groupIndex >= 0);
2266 groupHeader->setData(groups.at(groupIndex).second);
2267 groupHeader->setRole(model()->groupRole());
2268 groupHeader->setStyleOption(m_styleOption);
2269 groupHeader->setScrollOrientation(scrollOrientation());
2270 groupHeader->setItemIndex(index);
2271
2272 groupHeader->show();
2273 }
2274
2275 void KItemListView::updateGroupHeaderLayout(KItemListWidget *widget)
2276 {
2277 KItemListGroupHeader *groupHeader = m_visibleGroups.value(widget);
2278 Q_ASSERT(groupHeader);
2279
2280 const int index = widget->index();
2281 const QRectF groupHeaderRect = m_layouter->groupHeaderRect(index);
2282 const QRectF itemRect = m_layouter->itemRect(index);
2283
2284 // The group-header is a child of the itemlist widget. Translate the
2285 // group header position to the relative position.
2286 if (scrollOrientation() == Qt::Vertical) {
2287 // In the vertical scroll orientation the group header should always span
2288 // the whole width no matter which temporary position the parent widget
2289 // has. In this case the x-position and width will be adjusted manually.
2290 const qreal x = -widget->x() - itemOffset();
2291 const qreal width = maximumItemOffset();
2292 groupHeader->setPos(x, -groupHeaderRect.height());
2293 groupHeader->resize(width, groupHeaderRect.size().height());
2294 } else {
2295 groupHeader->setPos(groupHeaderRect.x() - itemRect.x(), -widget->y());
2296 groupHeader->resize(groupHeaderRect.size());
2297 }
2298 }
2299
2300 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget *widget)
2301 {
2302 KItemListGroupHeader *header = m_visibleGroups.value(widget);
2303 if (header) {
2304 header->setParentItem(nullptr);
2305 groupHeaderCreator()->recycle(header);
2306 m_visibleGroups.remove(widget);
2307 disconnect(widget, &KItemListWidget::geometryChanged, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged);
2308 }
2309 }
2310
2311 void KItemListView::updateVisibleGroupHeaders()
2312 {
2313 Q_ASSERT(m_grouped);
2314 m_layouter->markAsDirty();
2315
2316 QHashIterator<int, KItemListWidget *> it(m_visibleItems);
2317 while (it.hasNext()) {
2318 it.next();
2319 updateGroupHeaderForWidget(it.value());
2320 }
2321 }
2322
2323 int KItemListView::groupIndexForItem(int index) const
2324 {
2325 Q_ASSERT(m_grouped);
2326
2327 const QList<QPair<int, QVariant>> groups = model()->groups();
2328 if (groups.isEmpty()) {
2329 return -1;
2330 }
2331
2332 int min = 0;
2333 int max = groups.count() - 1;
2334 int mid = 0;
2335 do {
2336 mid = (min + max) / 2;
2337 if (index > groups[mid].first) {
2338 min = mid + 1;
2339 } else {
2340 max = mid - 1;
2341 }
2342 } while (groups[mid].first != index && min <= max);
2343
2344 if (min > max) {
2345 while (groups[mid].first > index && mid > 0) {
2346 --mid;
2347 }
2348 }
2349
2350 return mid;
2351 }
2352
2353 void KItemListView::updateAlternateBackgrounds()
2354 {
2355 QHashIterator<int, KItemListWidget *> it(m_visibleItems);
2356 while (it.hasNext()) {
2357 it.next();
2358 updateAlternateBackgroundForWidget(it.value());
2359 }
2360 }
2361
2362 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget *widget)
2363 {
2364 bool enabled = useAlternateBackgrounds();
2365 if (enabled) {
2366 const int index = widget->index();
2367 enabled = (index & 0x1) > 0;
2368 if (m_grouped) {
2369 const int groupIndex = groupIndexForItem(index);
2370 if (groupIndex >= 0) {
2371 const QList<QPair<int, QVariant>> groups = model()->groups();
2372 const int indexOfFirstGroupItem = groups[groupIndex].first;
2373 const int relativeIndex = index - indexOfFirstGroupItem;
2374 enabled = (relativeIndex & 0x1) > 0;
2375 }
2376 }
2377 }
2378 widget->setAlternateBackground(enabled);
2379 }
2380
2381 bool KItemListView::useAlternateBackgrounds() const
2382 {
2383 return m_alternateBackgrounds && m_itemSize.isEmpty();
2384 }
2385
2386 QHash<QByteArray, qreal> KItemListView::preferredColumnWidths(const KItemRangeList &itemRanges) const
2387 {
2388 QElapsedTimer timer;
2389 timer.start();
2390
2391 QHash<QByteArray, qreal> widths;
2392
2393 // Calculate the minimum width for each column that is required
2394 // to show the headline unclipped.
2395 const QFontMetricsF fontMetrics(m_headerWidget->font());
2396 const int gripMargin = m_headerWidget->style()->pixelMetric(QStyle::PM_HeaderGripMargin);
2397 const int headerMargin = m_headerWidget->style()->pixelMetric(QStyle::PM_HeaderMargin);
2398 for (const QByteArray &visibleRole : std::as_const(m_visibleRoles)) {
2399 const QString headerText = m_model->roleDescription(visibleRole);
2400 const qreal headerWidth = fontMetrics.horizontalAdvance(headerText) + gripMargin + headerMargin * 2;
2401 widths.insert(visibleRole, headerWidth);
2402 }
2403
2404 // Calculate the preferred column widths for each item and ignore values
2405 // smaller than the width for showing the headline unclipped.
2406 const KItemListWidgetCreatorBase *creator = widgetCreator();
2407 int calculatedItemCount = 0;
2408 bool maxTimeExceeded = false;
2409 for (const KItemRange &itemRange : itemRanges) {
2410 const int startIndex = itemRange.index;
2411 const int endIndex = startIndex + itemRange.count - 1;
2412
2413 for (int i = startIndex; i <= endIndex; ++i) {
2414 for (const QByteArray &visibleRole : std::as_const(m_visibleRoles)) {
2415 qreal maxWidth = widths.value(visibleRole, 0);
2416 const qreal width = creator->preferredRoleColumnWidth(visibleRole, i, this);
2417 maxWidth = qMax(width, maxWidth);
2418 widths.insert(visibleRole, maxWidth);
2419 }
2420
2421 if (calculatedItemCount > 100 && timer.elapsed() > 200) {
2422 // When having several thousands of items calculating the sizes can get
2423 // very expensive. We accept a possibly too small role-size in favour
2424 // of having no blocking user interface.
2425 maxTimeExceeded = true;
2426 break;
2427 }
2428 ++calculatedItemCount;
2429 }
2430 if (maxTimeExceeded) {
2431 break;
2432 }
2433 }
2434
2435 return widths;
2436 }
2437
2438 void KItemListView::applyColumnWidthsFromHeader()
2439 {
2440 // Apply the new size to the layouter
2441 const qreal requiredWidth = m_headerWidget->leftPadding() + columnWidthsSum() + m_headerWidget->rightPadding();
2442 const QSizeF dynamicItemSize(qMax(size().width(), requiredWidth), m_itemSize.height());
2443 m_layouter->setItemSize(dynamicItemSize);
2444
2445 // Update the role sizes for all visible widgets
2446 QHashIterator<int, KItemListWidget *> it(m_visibleItems);
2447 while (it.hasNext()) {
2448 it.next();
2449 updateWidgetColumnWidths(it.value());
2450 }
2451 }
2452
2453 void KItemListView::updateWidgetColumnWidths(KItemListWidget *widget)
2454 {
2455 for (const QByteArray &role : std::as_const(m_visibleRoles)) {
2456 widget->setColumnWidth(role, m_headerWidget->columnWidth(role));
2457 }
2458 widget->setSidePadding(m_headerWidget->leftPadding(), m_headerWidget->rightPadding());
2459 }
2460
2461 void KItemListView::updatePreferredColumnWidths(const KItemRangeList &itemRanges)
2462 {
2463 Q_ASSERT(m_itemSize.isEmpty());
2464 const int itemCount = m_model->count();
2465 int rangesItemCount = 0;
2466 for (const KItemRange &range : itemRanges) {
2467 rangesItemCount += range.count;
2468 }
2469
2470 if (itemCount == rangesItemCount) {
2471 const QHash<QByteArray, qreal> preferredWidths = preferredColumnWidths(itemRanges);
2472 for (const QByteArray &role : std::as_const(m_visibleRoles)) {
2473 m_headerWidget->setPreferredColumnWidth(role, preferredWidths.value(role));
2474 }
2475 } else {
2476 // Only a sub range of the roles need to be determined.
2477 // The chances are good that the widths of the sub ranges
2478 // already fit into the available widths and hence no
2479 // expensive update might be required.
2480 bool changed = false;
2481
2482 const QHash<QByteArray, qreal> updatedWidths = preferredColumnWidths(itemRanges);
2483 QHashIterator<QByteArray, qreal> it(updatedWidths);
2484 while (it.hasNext()) {
2485 it.next();
2486 const QByteArray &role = it.key();
2487 const qreal updatedWidth = it.value();
2488 const qreal currentWidth = m_headerWidget->preferredColumnWidth(role);
2489 if (updatedWidth > currentWidth) {
2490 m_headerWidget->setPreferredColumnWidth(role, updatedWidth);
2491 changed = true;
2492 }
2493 }
2494
2495 if (!changed) {
2496 // All the updated sizes are smaller than the current sizes and no change
2497 // of the stretched roles-widths is required
2498 return;
2499 }
2500 }
2501
2502 if (m_headerWidget->automaticColumnResizing()) {
2503 applyAutomaticColumnWidths();
2504 }
2505 }
2506
2507 void KItemListView::updatePreferredColumnWidths()
2508 {
2509 if (m_model) {
2510 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model->count()));
2511 }
2512 }
2513
2514 void KItemListView::applyAutomaticColumnWidths()
2515 {
2516 Q_ASSERT(m_itemSize.isEmpty());
2517 Q_ASSERT(m_headerWidget->automaticColumnResizing());
2518 if (m_visibleRoles.isEmpty()) {
2519 return;
2520 }
2521
2522 // Calculate the maximum size of an item by considering the
2523 // visible role sizes and apply them to the layouter. If the
2524 // size does not use the available view-size the size of the
2525 // first role will get stretched.
2526
2527 for (const QByteArray &role : std::as_const(m_visibleRoles)) {
2528 const qreal preferredWidth = m_headerWidget->preferredColumnWidth(role);
2529 m_headerWidget->setColumnWidth(role, preferredWidth);
2530 }
2531
2532 const QByteArray firstRole = m_visibleRoles.first();
2533 qreal firstColumnWidth = m_headerWidget->columnWidth(firstRole);
2534 QSizeF dynamicItemSize = m_itemSize;
2535
2536 qreal requiredWidth = m_headerWidget->leftPadding() + columnWidthsSum() + m_headerWidget->rightPadding();
2537 // 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
2538 // out that the padding area can be used for deselecting and dropping files.
2539 const qreal availableWidth = size().width();
2540 if (requiredWidth < availableWidth) {
2541 // Stretch the first column to use the whole remaining width
2542 firstColumnWidth += availableWidth - requiredWidth;
2543 m_headerWidget->setColumnWidth(firstRole, firstColumnWidth);
2544 } else if (requiredWidth > availableWidth && m_visibleRoles.count() > 1) {
2545 // Shrink the first column to be able to show as much other
2546 // columns as possible
2547 qreal shrinkedFirstColumnWidth = firstColumnWidth - requiredWidth + availableWidth;
2548
2549 // TODO: A proper calculation of the minimum width depends on the implementation
2550 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2551 // later.
2552 const qreal minWidth = qMin(firstColumnWidth, qreal(m_styleOption.iconSize * 2 + 200));
2553 if (shrinkedFirstColumnWidth < minWidth) {
2554 shrinkedFirstColumnWidth = minWidth;
2555 }
2556
2557 m_headerWidget->setColumnWidth(firstRole, shrinkedFirstColumnWidth);
2558 requiredWidth -= firstColumnWidth - shrinkedFirstColumnWidth;
2559 }
2560
2561 dynamicItemSize.rwidth() = qMax(requiredWidth, availableWidth);
2562
2563 m_layouter->setItemSize(dynamicItemSize);
2564
2565 // Update the role sizes for all visible widgets
2566 QHashIterator<int, KItemListWidget *> it(m_visibleItems);
2567 while (it.hasNext()) {
2568 it.next();
2569 updateWidgetColumnWidths(it.value());
2570 }
2571 }
2572
2573 qreal KItemListView::columnWidthsSum() const
2574 {
2575 qreal widthsSum = 0;
2576 for (const QByteArray &role : std::as_const(m_visibleRoles)) {
2577 widthsSum += m_headerWidget->columnWidth(role);
2578 }
2579 return widthsSum;
2580 }
2581
2582 QRectF KItemListView::headerBoundaries() const
2583 {
2584 return m_headerWidget->isVisible() ? m_headerWidget->geometry() : QRectF();
2585 }
2586
2587 bool KItemListView::changesItemGridLayout(const QSizeF &newGridSize, const QSizeF &newItemSize, const QSizeF &newItemMargin) const
2588 {
2589 if (newItemSize.isEmpty() || newGridSize.isEmpty()) {
2590 return false;
2591 }
2592
2593 if (m_layouter->scrollOrientation() == Qt::Vertical) {
2594 const qreal itemWidth = m_layouter->itemSize().width();
2595 if (itemWidth > 0) {
2596 const int newColumnCount = itemsPerSize(newGridSize.width(), newItemSize.width(), newItemMargin.width());
2597 if (m_model->count() > newColumnCount) {
2598 const int oldColumnCount = itemsPerSize(m_layouter->size().width(), itemWidth, m_layouter->itemMargin().width());
2599 return oldColumnCount != newColumnCount;
2600 }
2601 }
2602 } else {
2603 const qreal itemHeight = m_layouter->itemSize().height();
2604 if (itemHeight > 0) {
2605 const int newRowCount = itemsPerSize(newGridSize.height(), newItemSize.height(), newItemMargin.height());
2606 if (m_model->count() > newRowCount) {
2607 const int oldRowCount = itemsPerSize(m_layouter->size().height(), itemHeight, m_layouter->itemMargin().height());
2608 return oldRowCount != newRowCount;
2609 }
2610 }
2611 }
2612
2613 return false;
2614 }
2615
2616 bool KItemListView::animateChangedItemCount(int changedItemCount) const
2617 {
2618 if (m_itemSize.isEmpty()) {
2619 // We have only columns or only rows, but no grid: An animation is usually
2620 // welcome when inserting or removing items.
2621 return !supportsItemExpanding();
2622 }
2623
2624 if (m_layouter->size().isEmpty() || m_layouter->itemSize().isEmpty()) {
2625 return false;
2626 }
2627
2628 const int maximum = (scrollOrientation() == Qt::Vertical) ? m_layouter->size().width() / m_layouter->itemSize().width()
2629 : m_layouter->size().height() / m_layouter->itemSize().height();
2630 // Only animate if up to 2/3 of a row or column are inserted or removed
2631 return changedItemCount <= maximum * 2 / 3;
2632 }
2633
2634 bool KItemListView::scrollBarRequired(const QSizeF &size) const
2635 {
2636 const QSizeF oldSize = m_layouter->size();
2637
2638 m_layouter->setSize(size);
2639 const qreal maxOffset = m_layouter->maximumScrollOffset();
2640 m_layouter->setSize(oldSize);
2641
2642 return m_layouter->scrollOrientation() == Qt::Vertical ? maxOffset > size.height() : maxOffset > size.width();
2643 }
2644
2645 int KItemListView::showDropIndicator(const QPointF &pos)
2646 {
2647 QHashIterator<int, KItemListWidget *> it(m_visibleItems);
2648 while (it.hasNext()) {
2649 it.next();
2650 const KItemListWidget *widget = it.value();
2651
2652 const QPointF mappedPos = widget->mapFromItem(this, pos);
2653 const QRectF rect = itemRect(widget->index());
2654 if (mappedPos.y() >= 0 && mappedPos.y() <= rect.height()) {
2655 if (m_model->supportsDropping(widget->index())) {
2656 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2657 const int gap = qMax(qreal(4.0), qreal(0.3) * rect.height());
2658 if (mappedPos.y() >= gap && mappedPos.y() <= rect.height() - gap) {
2659 return -1;
2660 }
2661 }
2662
2663 const bool isAboveItem = (mappedPos.y() < rect.height() / 2);
2664 const qreal y = isAboveItem ? rect.top() : rect.bottom();
2665
2666 const QRectF draggingInsertIndicator(rect.left(), y, rect.width(), 1);
2667 if (m_dropIndicator != draggingInsertIndicator) {
2668 m_dropIndicator = draggingInsertIndicator;
2669 update();
2670 }
2671
2672 int index = widget->index();
2673 if (!isAboveItem) {
2674 ++index;
2675 }
2676 return index;
2677 }
2678 }
2679
2680 const QRectF firstItemRect = itemRect(firstVisibleIndex());
2681 return (pos.y() <= firstItemRect.top()) ? 0 : -1;
2682 }
2683
2684 void KItemListView::hideDropIndicator()
2685 {
2686 if (!m_dropIndicator.isNull()) {
2687 m_dropIndicator = QRectF();
2688 update();
2689 }
2690 }
2691
2692 void KItemListView::updateGroupHeaderHeight()
2693 {
2694 qreal groupHeaderHeight = m_styleOption.fontMetrics.height();
2695 qreal groupHeaderMargin = 0;
2696
2697 if (scrollOrientation() == Qt::Horizontal) {
2698 // The vertical margin above and below the header should be
2699 // equal to the horizontal margin, not the vertical margin
2700 // from m_styleOption.
2701 groupHeaderHeight += 2 * m_styleOption.horizontalMargin;
2702 groupHeaderMargin = m_styleOption.horizontalMargin;
2703 } else if (m_itemSize.isEmpty()) {
2704 groupHeaderHeight += 4 * m_styleOption.padding;
2705 groupHeaderMargin = m_styleOption.iconSize / 2;
2706 } else {
2707 groupHeaderHeight += 2 * m_styleOption.padding + m_styleOption.verticalMargin;
2708 groupHeaderMargin = m_styleOption.iconSize / 4;
2709 }
2710 m_layouter->setGroupHeaderHeight(groupHeaderHeight);
2711 m_layouter->setGroupHeaderMargin(groupHeaderMargin);
2712
2713 updateVisibleGroupHeaders();
2714 }
2715
2716 void KItemListView::updateSiblingsInformation(int firstIndex, int lastIndex)
2717 {
2718 if (!supportsItemExpanding() || !m_model) {
2719 return;
2720 }
2721
2722 if (firstIndex < 0 || lastIndex < 0) {
2723 firstIndex = m_layouter->firstVisibleIndex();
2724 lastIndex = m_layouter->lastVisibleIndex();
2725 } else {
2726 const bool isRangeVisible = (firstIndex <= m_layouter->lastVisibleIndex() && lastIndex >= m_layouter->firstVisibleIndex());
2727 if (!isRangeVisible) {
2728 return;
2729 }
2730 }
2731
2732 int previousParents = 0;
2733 QBitArray previousSiblings;
2734
2735 // The rootIndex describes the first index where the siblings get
2736 // calculated from. For the calculation the upper most parent item
2737 // is required. For performance reasons it is checked first whether
2738 // the visible items before or after the current range already
2739 // contain a siblings information which can be used as base.
2740 int rootIndex = firstIndex;
2741
2742 KItemListWidget *widget = m_visibleItems.value(firstIndex - 1);
2743 if (!widget) {
2744 // There is no visible widget before the range, check whether there
2745 // is one after the range:
2746 widget = m_visibleItems.value(lastIndex + 1);
2747 if (widget) {
2748 // The sibling information of the widget may only be used if
2749 // all items of the range have the same number of parents.
2750 const int parents = m_model->expandedParentsCount(lastIndex + 1);
2751 for (int i = lastIndex; i >= firstIndex; --i) {
2752 if (m_model->expandedParentsCount(i) != parents) {
2753 widget = nullptr;
2754 break;
2755 }
2756 }
2757 }
2758 }
2759
2760 if (widget) {
2761 // Performance optimization: Use the sibling information of the visible
2762 // widget beside the given range.
2763 previousSiblings = widget->siblingsInformation();
2764 if (previousSiblings.isEmpty()) {
2765 return;
2766 }
2767 previousParents = previousSiblings.count() - 1;
2768 previousSiblings.truncate(previousParents);
2769 } else {
2770 // Potentially slow path: Go back to the upper most parent of firstIndex
2771 // to be able to calculate the initial value for the siblings.
2772 while (rootIndex > 0 && m_model->expandedParentsCount(rootIndex) > 0) {
2773 --rootIndex;
2774 }
2775 }
2776
2777 Q_ASSERT(previousParents >= 0);
2778 for (int i = rootIndex; i <= lastIndex; ++i) {
2779 // Update the parent-siblings in case if the current item represents
2780 // a child or an upper parent.
2781 const int currentParents = m_model->expandedParentsCount(i);
2782 Q_ASSERT(currentParents >= 0);
2783 if (previousParents < currentParents) {
2784 previousParents = currentParents;
2785 previousSiblings.resize(currentParents);
2786 previousSiblings.setBit(currentParents - 1, hasSiblingSuccessor(i - 1));
2787 } else if (previousParents > currentParents) {
2788 previousParents = currentParents;
2789 previousSiblings.truncate(currentParents);
2790 }
2791
2792 if (i >= firstIndex) {
2793 // The index represents a visible item. Apply the parent-siblings
2794 // and update the sibling of the current item.
2795 KItemListWidget *widget = m_visibleItems.value(i);
2796 if (!widget) {
2797 continue;
2798 }
2799
2800 QBitArray siblings = previousSiblings;
2801 siblings.resize(siblings.count() + 1);
2802 siblings.setBit(siblings.count() - 1, hasSiblingSuccessor(i));
2803
2804 widget->setSiblingsInformation(siblings);
2805 }
2806 }
2807 }
2808
2809 bool KItemListView::hasSiblingSuccessor(int index) const
2810 {
2811 bool hasSuccessor = false;
2812 const int parentsCount = m_model->expandedParentsCount(index);
2813 int successorIndex = index + 1;
2814
2815 // Search the next sibling
2816 const int itemCount = m_model->count();
2817 while (successorIndex < itemCount) {
2818 const int currentParentsCount = m_model->expandedParentsCount(successorIndex);
2819 if (currentParentsCount == parentsCount) {
2820 hasSuccessor = true;
2821 break;
2822 } else if (currentParentsCount < parentsCount) {
2823 break;
2824 }
2825 ++successorIndex;
2826 }
2827
2828 if (m_grouped && hasSuccessor) {
2829 // If the sibling is part of another group, don't mark it as
2830 // successor as the group header is between the sibling connections.
2831 for (int i = index + 1; i <= successorIndex; ++i) {
2832 if (m_layouter->isFirstGroupItem(i)) {
2833 hasSuccessor = false;
2834 break;
2835 }
2836 }
2837 }
2838
2839 return hasSuccessor;
2840 }
2841
2842 void KItemListView::disconnectRoleEditingSignals(int index)
2843 {
2844 KStandardItemListWidget *widget = qobject_cast<KStandardItemListWidget *>(m_visibleItems.value(index));
2845 if (!widget) {
2846 return;
2847 }
2848
2849 disconnect(widget, &KItemListWidget::roleEditingCanceled, this, nullptr);
2850 disconnect(widget, &KItemListWidget::roleEditingFinished, this, nullptr);
2851 disconnect(this, &KItemListView::scrollOffsetChanged, widget, nullptr);
2852 }
2853
2854 int KItemListView::calculateAutoScrollingIncrement(int pos, int range, int oldInc)
2855 {
2856 int inc = 0;
2857
2858 const int minSpeed = 4;
2859 const int maxSpeed = 128;
2860 const int speedLimiter = 96;
2861 const int autoScrollBorder = 64;
2862
2863 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2864 // This assures that the autoscrolling speed grows gradually.
2865 const int incLimiter = 1;
2866
2867 if (pos < autoScrollBorder) {
2868 inc = -minSpeed + qAbs(pos - autoScrollBorder) * (pos - autoScrollBorder) / speedLimiter;
2869 inc = qMax(inc, -maxSpeed);
2870 inc = qMax(inc, oldInc - incLimiter);
2871 } else if (pos > range - autoScrollBorder) {
2872 inc = minSpeed + qAbs(pos - range + autoScrollBorder) * (pos - range + autoScrollBorder) / speedLimiter;
2873 inc = qMin(inc, maxSpeed);
2874 inc = qMin(inc, oldInc + incLimiter);
2875 }
2876
2877 return inc;
2878 }
2879
2880 int KItemListView::itemsPerSize(qreal size, qreal itemSize, qreal itemMargin)
2881 {
2882 const qreal availableSize = size - itemMargin;
2883 const int count = availableSize / (itemSize + itemMargin);
2884 return count;
2885 }
2886
2887 KItemListCreatorBase::~KItemListCreatorBase()
2888 {
2889 qDeleteAll(m_recycleableWidgets);
2890 qDeleteAll(m_createdWidgets);
2891 }
2892
2893 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget *widget)
2894 {
2895 m_createdWidgets.insert(widget);
2896 }
2897
2898 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget *widget)
2899 {
2900 Q_ASSERT(m_createdWidgets.contains(widget));
2901 m_createdWidgets.remove(widget);
2902
2903 if (m_recycleableWidgets.count() < 100) {
2904 m_recycleableWidgets.append(widget);
2905 widget->setVisible(false);
2906 } else {
2907 delete widget;
2908 }
2909 }
2910
2911 QGraphicsWidget *KItemListCreatorBase::popRecycleableWidget()
2912 {
2913 if (m_recycleableWidgets.isEmpty()) {
2914 return nullptr;
2915 }
2916
2917 QGraphicsWidget *widget = m_recycleableWidgets.takeLast();
2918 m_createdWidgets.insert(widget);
2919 return widget;
2920 }
2921
2922 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2923 {
2924 }
2925
2926 void KItemListWidgetCreatorBase::recycle(KItemListWidget *widget)
2927 {
2928 widget->setParentItem(nullptr);
2929 widget->setOpacity(1.0);
2930 pushRecycleableWidget(widget);
2931 }
2932
2933 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2934 {
2935 }
2936
2937 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader *header)
2938 {
2939 header->setOpacity(1.0);
2940 pushRecycleableWidget(header);
2941 }
2942
2943 #include "moc_kitemlistview.cpp"