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