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