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