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