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