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