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