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