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