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