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