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