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