]> 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 bool animateIconResizing = animate;
1862
1863 if (widget->size() != itemBounds.size()) {
1864 // Resize the widget for the item to the changed size.
1865 if (animate) {
1866 // If a dynamic item size is used then no animation is done in the direction
1867 // of the dynamic size.
1868 if (m_itemSize.width() <= 0) {
1869 // The width is dynamic, apply the new width without animation.
1870 widget->resize(itemBounds.width(), widget->size().height());
1871 } else if (m_itemSize.height() <= 0) {
1872 // The height is dynamic, apply the new height without animation.
1873 widget->resize(widget->size().width(), itemBounds.height());
1874 }
1875 m_animation->start(widget, KItemListViewAnimation::ResizeAnimation, itemBounds.size());
1876 } else {
1877 widget->resize(itemBounds.size());
1878 }
1879 } else {
1880 animateIconResizing = false;
1881 }
1882
1883 const int newIconSize = widget->styleOption().iconSize;
1884 if (widget->iconSize() != newIconSize) {
1885 if (animateIconResizing) {
1886 m_animation->start(widget, KItemListViewAnimation::IconResizeAnimation, newIconSize);
1887 } else {
1888 widget->setIconSize(newIconSize);
1889 }
1890 }
1891
1892 // Updating the cell-information must be done as last step: The decision whether the
1893 // moving-animation should be started at all is based on the previous cell-information.
1894 const Cell cell(m_layouter->itemColumn(i), m_layouter->itemRow(i));
1895 m_visibleCells.insert(i, cell);
1896 }
1897
1898 // Delete invisible KItemListWidget instances that have not been reused
1899 for (int index : qAsConst(reusableItems)) {
1900 recycleWidget(m_visibleItems.value(index));
1901 }
1902
1903 if (supportsExpanding && firstSibblingIndex >= 0) {
1904 Q_ASSERT(lastSibblingIndex >= 0);
1905 updateSiblingsInformation(firstSibblingIndex, lastSibblingIndex);
1906 }
1907
1908 if (m_grouped) {
1909 // Update the layout of all visible group headers
1910 QHashIterator<KItemListWidget*, KItemListGroupHeader*> it(m_visibleGroups);
1911 while (it.hasNext()) {
1912 it.next();
1913 updateGroupHeaderLayout(it.key());
1914 }
1915 }
1916
1917 emitOffsetChanges();
1918 }
1919
1920 QList<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex,
1921 int lastVisibleIndex,
1922 LayoutAnimationHint hint)
1923 {
1924 // Determine all items that are completely invisible and might be
1925 // reused for items that just got (at least partly) visible. If the
1926 // animation hint is set to 'Animation' items that do e.g. an animated
1927 // moving of their position are not marked as invisible: This assures
1928 // that a scrolling inside the view can be done without breaking an animation.
1929
1930 QList<int> items;
1931
1932 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
1933 while (it.hasNext()) {
1934 it.next();
1935
1936 KItemListWidget* widget = it.value();
1937 const int index = widget->index();
1938 const bool invisible = (index < firstVisibleIndex) || (index > lastVisibleIndex);
1939
1940 if (invisible) {
1941 if (m_animation->isStarted(widget)) {
1942 if (hint == NoAnimation) {
1943 // Stopping the animation will call KItemListView::slotAnimationFinished()
1944 // and the widget will be recycled if necessary there.
1945 m_animation->stop(widget);
1946 }
1947 } else {
1948 widget->setVisible(false);
1949 items.append(index);
1950
1951 if (m_grouped) {
1952 recycleGroupHeaderForWidget(widget);
1953 }
1954 }
1955 }
1956 }
1957
1958 return items;
1959 }
1960
1961 bool KItemListView::moveWidget(KItemListWidget* widget,const QPointF& newPos)
1962 {
1963 if (widget->pos() == newPos) {
1964 return false;
1965 }
1966
1967 bool startMovingAnim = false;
1968
1969 if (m_itemSize.isEmpty()) {
1970 // The items are not aligned in a grid but either as columns or rows.
1971 startMovingAnim = true;
1972 } else {
1973 // When having a grid the moving-animation should only be started, if it is done within
1974 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1975 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1976 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1977 const int index = widget->index();
1978 const Cell cell = m_visibleCells.value(index);
1979 if (cell.column >= 0 && cell.row >= 0) {
1980 if (scrollOrientation() == Qt::Vertical) {
1981 startMovingAnim = (cell.row == m_layouter->itemRow(index));
1982 } else {
1983 startMovingAnim = (cell.column == m_layouter->itemColumn(index));
1984 }
1985 }
1986 }
1987
1988 if (startMovingAnim) {
1989 m_animation->start(widget, KItemListViewAnimation::MovingAnimation, newPos);
1990 return true;
1991 }
1992
1993 m_animation->stop(widget);
1994 m_animation->start(widget, KItemListViewAnimation::CreateAnimation);
1995 return false;
1996 }
1997
1998 void KItemListView::emitOffsetChanges()
1999 {
2000 const qreal newScrollOffset = m_layouter->scrollOffset();
2001 if (m_oldScrollOffset != newScrollOffset) {
2002 Q_EMIT scrollOffsetChanged(newScrollOffset, m_oldScrollOffset);
2003 m_oldScrollOffset = newScrollOffset;
2004 }
2005
2006 const qreal newMaximumScrollOffset = m_layouter->maximumScrollOffset();
2007 if (m_oldMaximumScrollOffset != newMaximumScrollOffset) {
2008 Q_EMIT maximumScrollOffsetChanged(newMaximumScrollOffset, m_oldMaximumScrollOffset);
2009 m_oldMaximumScrollOffset = newMaximumScrollOffset;
2010 }
2011
2012 const qreal newItemOffset = m_layouter->itemOffset();
2013 if (m_oldItemOffset != newItemOffset) {
2014 Q_EMIT itemOffsetChanged(newItemOffset, m_oldItemOffset);
2015 m_oldItemOffset = newItemOffset;
2016 }
2017
2018 const qreal newMaximumItemOffset = m_layouter->maximumItemOffset();
2019 if (m_oldMaximumItemOffset != newMaximumItemOffset) {
2020 Q_EMIT maximumItemOffsetChanged(newMaximumItemOffset, m_oldMaximumItemOffset);
2021 m_oldMaximumItemOffset = newMaximumItemOffset;
2022 }
2023 }
2024
2025 KItemListWidget* KItemListView::createWidget(int index)
2026 {
2027 KItemListWidget* widget = widgetCreator()->create(this);
2028 widget->setFlag(QGraphicsItem::ItemStacksBehindParent);
2029
2030 m_visibleItems.insert(index, widget);
2031 m_visibleCells.insert(index, Cell());
2032 updateWidgetProperties(widget, index);
2033 initializeItemListWidget(widget);
2034 return widget;
2035 }
2036
2037 void KItemListView::recycleWidget(KItemListWidget* widget)
2038 {
2039 if (m_grouped) {
2040 recycleGroupHeaderForWidget(widget);
2041 }
2042
2043 const int index = widget->index();
2044 m_visibleItems.remove(index);
2045 m_visibleCells.remove(index);
2046
2047 widgetCreator()->recycle(widget);
2048 }
2049
2050 void KItemListView::setWidgetIndex(KItemListWidget* widget, int index)
2051 {
2052 const int oldIndex = widget->index();
2053 m_visibleItems.remove(oldIndex);
2054 m_visibleCells.remove(oldIndex);
2055
2056 m_visibleItems.insert(index, widget);
2057 m_visibleCells.insert(index, Cell());
2058
2059 widget->setIndex(index);
2060 }
2061
2062 void KItemListView::moveWidgetToIndex(KItemListWidget* widget, int index)
2063 {
2064 const int oldIndex = widget->index();
2065 const Cell oldCell = m_visibleCells.value(oldIndex);
2066
2067 setWidgetIndex(widget, index);
2068
2069 const Cell newCell(m_layouter->itemColumn(index), m_layouter->itemRow(index));
2070 const bool vertical = (scrollOrientation() == Qt::Vertical);
2071 const bool updateCell = (vertical && oldCell.row == newCell.row) ||
2072 (!vertical && oldCell.column == newCell.column);
2073 if (updateCell) {
2074 m_visibleCells.insert(index, newCell);
2075 }
2076 }
2077
2078 void KItemListView::setLayouterSize(const QSizeF& size, SizeType sizeType)
2079 {
2080 switch (sizeType) {
2081 case LayouterSize: m_layouter->setSize(size); break;
2082 case ItemSize: m_layouter->setItemSize(size); break;
2083 default: break;
2084 }
2085 }
2086
2087 void KItemListView::updateWidgetProperties(KItemListWidget* widget, int index)
2088 {
2089 widget->setVisibleRoles(m_visibleRoles);
2090 updateWidgetColumnWidths(widget);
2091 widget->setStyleOption(m_styleOption);
2092
2093 const KItemListSelectionManager* selectionManager = m_controller->selectionManager();
2094
2095 // In SingleSelection mode (e.g., in the Places Panel), the current item is
2096 // always the selected item. It is not necessary to highlight the current item then.
2097 if (m_controller->selectionBehavior() != KItemListController::SingleSelection) {
2098 widget->setCurrent(index == selectionManager->currentItem());
2099 }
2100 widget->setSelected(selectionManager->isSelected(index));
2101 widget->setHovered(false);
2102 widget->setEnabledSelectionToggle(enabledSelectionToggles());
2103 widget->setIndex(index);
2104 widget->setData(m_model->data(index));
2105 widget->setSiblingsInformation(QBitArray());
2106 updateAlternateBackgroundForWidget(widget);
2107
2108 if (m_grouped) {
2109 updateGroupHeaderForWidget(widget);
2110 }
2111 }
2112
2113 void KItemListView::updateGroupHeaderForWidget(KItemListWidget* widget)
2114 {
2115 Q_ASSERT(m_grouped);
2116
2117 const int index = widget->index();
2118 if (!m_layouter->isFirstGroupItem(index)) {
2119 // The widget does not represent the first item of a group
2120 // and hence requires no header
2121 recycleGroupHeaderForWidget(widget);
2122 return;
2123 }
2124
2125 const QList<QPair<int, QVariant> > groups = model()->groups();
2126 if (groups.isEmpty() || !groupHeaderCreator()) {
2127 return;
2128 }
2129
2130 KItemListGroupHeader* groupHeader = m_visibleGroups.value(widget);
2131 if (!groupHeader) {
2132 groupHeader = groupHeaderCreator()->create(this);
2133 groupHeader->setParentItem(widget);
2134 m_visibleGroups.insert(widget, groupHeader);
2135 connect(widget, &KItemListWidget::geometryChanged, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged);
2136 }
2137 Q_ASSERT(groupHeader->parentItem() == widget);
2138
2139 const int groupIndex = groupIndexForItem(index);
2140 Q_ASSERT(groupIndex >= 0);
2141 groupHeader->setData(groups.at(groupIndex).second);
2142 groupHeader->setRole(model()->sortRole());
2143 groupHeader->setStyleOption(m_styleOption);
2144 groupHeader->setScrollOrientation(scrollOrientation());
2145 groupHeader->setItemIndex(index);
2146
2147 groupHeader->show();
2148 }
2149
2150 void KItemListView::updateGroupHeaderLayout(KItemListWidget* widget)
2151 {
2152 KItemListGroupHeader* groupHeader = m_visibleGroups.value(widget);
2153 Q_ASSERT(groupHeader);
2154
2155 const int index = widget->index();
2156 const QRectF groupHeaderRect = m_layouter->groupHeaderRect(index);
2157 const QRectF itemRect = m_layouter->itemRect(index);
2158
2159 // The group-header is a child of the itemlist widget. Translate the
2160 // group header position to the relative position.
2161 if (scrollOrientation() == Qt::Vertical) {
2162 // In the vertical scroll orientation the group header should always span
2163 // the whole width no matter which temporary position the parent widget
2164 // has. In this case the x-position and width will be adjusted manually.
2165 const qreal x = -widget->x() - itemOffset();
2166 const qreal width = maximumItemOffset();
2167 groupHeader->setPos(x, -groupHeaderRect.height());
2168 groupHeader->resize(width, groupHeaderRect.size().height());
2169 } else {
2170 groupHeader->setPos(groupHeaderRect.x() - itemRect.x(), -widget->y());
2171 groupHeader->resize(groupHeaderRect.size());
2172 }
2173 }
2174
2175 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget* widget)
2176 {
2177 KItemListGroupHeader* header = m_visibleGroups.value(widget);
2178 if (header) {
2179 header->setParentItem(nullptr);
2180 groupHeaderCreator()->recycle(header);
2181 m_visibleGroups.remove(widget);
2182 disconnect(widget, &KItemListWidget::geometryChanged, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged);
2183 }
2184 }
2185
2186 void KItemListView::updateVisibleGroupHeaders()
2187 {
2188 Q_ASSERT(m_grouped);
2189 m_layouter->markAsDirty();
2190
2191 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
2192 while (it.hasNext()) {
2193 it.next();
2194 updateGroupHeaderForWidget(it.value());
2195 }
2196 }
2197
2198 int KItemListView::groupIndexForItem(int index) const
2199 {
2200 Q_ASSERT(m_grouped);
2201
2202 const QList<QPair<int, QVariant> > groups = model()->groups();
2203 if (groups.isEmpty()) {
2204 return -1;
2205 }
2206
2207 int min = 0;
2208 int max = groups.count() - 1;
2209 int mid = 0;
2210 do {
2211 mid = (min + max) / 2;
2212 if (index > groups[mid].first) {
2213 min = mid + 1;
2214 } else {
2215 max = mid - 1;
2216 }
2217 } while (groups[mid].first != index && min <= max);
2218
2219 if (min > max) {
2220 while (groups[mid].first > index && mid > 0) {
2221 --mid;
2222 }
2223 }
2224
2225 return mid;
2226 }
2227
2228 void KItemListView::updateAlternateBackgrounds()
2229 {
2230 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
2231 while (it.hasNext()) {
2232 it.next();
2233 updateAlternateBackgroundForWidget(it.value());
2234 }
2235 }
2236
2237 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget* widget)
2238 {
2239 bool enabled = useAlternateBackgrounds();
2240 if (enabled) {
2241 const int index = widget->index();
2242 enabled = (index & 0x1) > 0;
2243 if (m_grouped) {
2244 const int groupIndex = groupIndexForItem(index);
2245 if (groupIndex >= 0) {
2246 const QList<QPair<int, QVariant> > groups = model()->groups();
2247 const int indexOfFirstGroupItem = groups[groupIndex].first;
2248 const int relativeIndex = index - indexOfFirstGroupItem;
2249 enabled = (relativeIndex & 0x1) > 0;
2250 }
2251 }
2252 }
2253 widget->setAlternateBackground(enabled);
2254 }
2255
2256 bool KItemListView::useAlternateBackgrounds() const
2257 {
2258 return m_alternateBackgrounds && m_itemSize.isEmpty();
2259 }
2260
2261 QHash<QByteArray, qreal> KItemListView::preferredColumnWidths(const KItemRangeList& itemRanges) const
2262 {
2263 QElapsedTimer timer;
2264 timer.start();
2265
2266 QHash<QByteArray, qreal> widths;
2267
2268 // Calculate the minimum width for each column that is required
2269 // to show the headline unclipped.
2270 const QFontMetricsF fontMetrics(m_headerWidget->font());
2271 const int gripMargin = m_headerWidget->style()->pixelMetric(QStyle::PM_HeaderGripMargin);
2272 const int headerMargin = m_headerWidget->style()->pixelMetric(QStyle::PM_HeaderMargin);
2273 for (const QByteArray& visibleRole : qAsConst(m_visibleRoles)) {
2274 const QString headerText = m_model->roleDescription(visibleRole);
2275 const qreal headerWidth = fontMetrics.horizontalAdvance(headerText) + gripMargin + headerMargin * 2;
2276 widths.insert(visibleRole, headerWidth);
2277 }
2278
2279 // Calculate the preferred column widths for each item and ignore values
2280 // smaller than the width for showing the headline unclipped.
2281 const KItemListWidgetCreatorBase* creator = widgetCreator();
2282 int calculatedItemCount = 0;
2283 bool maxTimeExceeded = false;
2284 for (const KItemRange& itemRange : itemRanges) {
2285 const int startIndex = itemRange.index;
2286 const int endIndex = startIndex + itemRange.count - 1;
2287
2288 for (int i = startIndex; i <= endIndex; ++i) {
2289 for (const QByteArray& visibleRole : qAsConst(m_visibleRoles)) {
2290 qreal maxWidth = widths.value(visibleRole, 0);
2291 const qreal width = creator->preferredRoleColumnWidth(visibleRole, i, this);
2292 maxWidth = qMax(width, maxWidth);
2293 widths.insert(visibleRole, maxWidth);
2294 }
2295
2296 if (calculatedItemCount > 100 && timer.elapsed() > 200) {
2297 // When having several thousands of items calculating the sizes can get
2298 // very expensive. We accept a possibly too small role-size in favour
2299 // of having no blocking user interface.
2300 maxTimeExceeded = true;
2301 break;
2302 }
2303 ++calculatedItemCount;
2304 }
2305 if (maxTimeExceeded) {
2306 break;
2307 }
2308 }
2309
2310 return widths;
2311 }
2312
2313 void KItemListView::applyColumnWidthsFromHeader()
2314 {
2315 // Apply the new size to the layouter
2316 const qreal requiredWidth = columnWidthsSum() + m_headerWidget->leadingPadding();
2317 const QSizeF dynamicItemSize(qMax(size().width(), requiredWidth),
2318 m_itemSize.height());
2319 m_layouter->setItemSize(dynamicItemSize);
2320
2321 // Update the role sizes for all visible widgets
2322 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
2323 while (it.hasNext()) {
2324 it.next();
2325 updateWidgetColumnWidths(it.value());
2326 }
2327 }
2328
2329 void KItemListView::updateWidgetColumnWidths(KItemListWidget* widget)
2330 {
2331 for (const QByteArray& role : qAsConst(m_visibleRoles)) {
2332 widget->setColumnWidth(role, m_headerWidget->columnWidth(role));
2333 }
2334 widget->setLeadingPadding(m_headerWidget->leadingPadding());
2335 }
2336
2337 void KItemListView::updatePreferredColumnWidths(const KItemRangeList& itemRanges)
2338 {
2339 Q_ASSERT(m_itemSize.isEmpty());
2340 const int itemCount = m_model->count();
2341 int rangesItemCount = 0;
2342 for (const KItemRange& range : itemRanges) {
2343 rangesItemCount += range.count;
2344 }
2345
2346 if (itemCount == rangesItemCount) {
2347 const QHash<QByteArray, qreal> preferredWidths = preferredColumnWidths(itemRanges);
2348 for (const QByteArray& role : qAsConst(m_visibleRoles)) {
2349 m_headerWidget->setPreferredColumnWidth(role, preferredWidths.value(role));
2350 }
2351 } else {
2352 // Only a sub range of the roles need to be determined.
2353 // The chances are good that the widths of the sub ranges
2354 // already fit into the available widths and hence no
2355 // expensive update might be required.
2356 bool changed = false;
2357
2358 const QHash<QByteArray, qreal> updatedWidths = preferredColumnWidths(itemRanges);
2359 QHashIterator<QByteArray, qreal> it(updatedWidths);
2360 while (it.hasNext()) {
2361 it.next();
2362 const QByteArray& role = it.key();
2363 const qreal updatedWidth = it.value();
2364 const qreal currentWidth = m_headerWidget->preferredColumnWidth(role);
2365 if (updatedWidth > currentWidth) {
2366 m_headerWidget->setPreferredColumnWidth(role, updatedWidth);
2367 changed = true;
2368 }
2369 }
2370
2371 if (!changed) {
2372 // All the updated sizes are smaller than the current sizes and no change
2373 // of the stretched roles-widths is required
2374 return;
2375 }
2376 }
2377
2378 if (m_headerWidget->automaticColumnResizing()) {
2379 applyAutomaticColumnWidths();
2380 }
2381 }
2382
2383 void KItemListView::updatePreferredColumnWidths()
2384 {
2385 if (m_model) {
2386 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model->count()));
2387 }
2388 }
2389
2390 void KItemListView::applyAutomaticColumnWidths()
2391 {
2392 Q_ASSERT(m_itemSize.isEmpty());
2393 Q_ASSERT(m_headerWidget->automaticColumnResizing());
2394 if (m_visibleRoles.isEmpty()) {
2395 return;
2396 }
2397
2398 // Calculate the maximum size of an item by considering the
2399 // visible role sizes and apply them to the layouter. If the
2400 // size does not use the available view-size the size of the
2401 // first role will get stretched.
2402
2403 for (const QByteArray& role : qAsConst(m_visibleRoles)) {
2404 const qreal preferredWidth = m_headerWidget->preferredColumnWidth(role);
2405 m_headerWidget->setColumnWidth(role, preferredWidth);
2406 }
2407
2408 const QByteArray firstRole = m_visibleRoles.first();
2409 qreal firstColumnWidth = m_headerWidget->columnWidth(firstRole);
2410 QSizeF dynamicItemSize = m_itemSize;
2411
2412 qreal requiredWidth = columnWidthsSum() + m_headerWidget->leadingPadding()
2413 + m_headerWidget->leadingPadding(); // Adding the padding a second time so we have the same padding symmetrically on both sides of the view.
2414 // This improves UX, looks better and increases the chances of users figuring out that the padding area can be used for deselecting and dropping files.
2415 const qreal availableWidth = size().width();
2416 if (requiredWidth < availableWidth) {
2417 // Stretch the first column to use the whole remaining width
2418 firstColumnWidth += availableWidth - requiredWidth;
2419 m_headerWidget->setColumnWidth(firstRole, firstColumnWidth);
2420 } else if (requiredWidth > availableWidth && m_visibleRoles.count() > 1) {
2421 // Shrink the first column to be able to show as much other
2422 // columns as possible
2423 qreal shrinkedFirstColumnWidth = firstColumnWidth - requiredWidth + availableWidth;
2424
2425 // TODO: A proper calculation of the minimum width depends on the implementation
2426 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2427 // later.
2428 const qreal minWidth = qMin(firstColumnWidth, qreal(m_styleOption.iconSize * 2 + 200));
2429 if (shrinkedFirstColumnWidth < minWidth) {
2430 shrinkedFirstColumnWidth = minWidth;
2431 }
2432
2433 m_headerWidget->setColumnWidth(firstRole, shrinkedFirstColumnWidth);
2434 requiredWidth -= firstColumnWidth - shrinkedFirstColumnWidth;
2435 }
2436
2437 dynamicItemSize.rwidth() = qMax(requiredWidth, availableWidth);
2438
2439 m_layouter->setItemSize(dynamicItemSize);
2440
2441 // Update the role sizes for all visible widgets
2442 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
2443 while (it.hasNext()) {
2444 it.next();
2445 updateWidgetColumnWidths(it.value());
2446 }
2447 }
2448
2449 qreal KItemListView::columnWidthsSum() const
2450 {
2451 qreal widthsSum = 0;
2452 for (const QByteArray& role : qAsConst(m_visibleRoles)) {
2453 widthsSum += m_headerWidget->columnWidth(role);
2454 }
2455 return widthsSum;
2456 }
2457
2458 QRectF KItemListView::headerBoundaries() const
2459 {
2460 return m_headerWidget->isVisible() ? m_headerWidget->geometry() : QRectF();
2461 }
2462
2463 bool KItemListView::changesItemGridLayout(const QSizeF& newGridSize,
2464 const QSizeF& newItemSize,
2465 const QSizeF& newItemMargin) const
2466 {
2467 if (newItemSize.isEmpty() || newGridSize.isEmpty()) {
2468 return false;
2469 }
2470
2471 if (m_layouter->scrollOrientation() == Qt::Vertical) {
2472 const qreal itemWidth = m_layouter->itemSize().width();
2473 if (itemWidth > 0) {
2474 const int newColumnCount = itemsPerSize(newGridSize.width(),
2475 newItemSize.width(),
2476 newItemMargin.width());
2477 if (m_model->count() > newColumnCount) {
2478 const int oldColumnCount = itemsPerSize(m_layouter->size().width(),
2479 itemWidth,
2480 m_layouter->itemMargin().width());
2481 return oldColumnCount != newColumnCount;
2482 }
2483 }
2484 } else {
2485 const qreal itemHeight = m_layouter->itemSize().height();
2486 if (itemHeight > 0) {
2487 const int newRowCount = itemsPerSize(newGridSize.height(),
2488 newItemSize.height(),
2489 newItemMargin.height());
2490 if (m_model->count() > newRowCount) {
2491 const int oldRowCount = itemsPerSize(m_layouter->size().height(),
2492 itemHeight,
2493 m_layouter->itemMargin().height());
2494 return oldRowCount != newRowCount;
2495 }
2496 }
2497 }
2498
2499 return false;
2500 }
2501
2502 bool KItemListView::animateChangedItemCount(int changedItemCount) const
2503 {
2504 if (m_itemSize.isEmpty()) {
2505 // We have only columns or only rows, but no grid: An animation is usually
2506 // welcome when inserting or removing items.
2507 return !supportsItemExpanding();
2508 }
2509
2510 if (m_layouter->size().isEmpty() || m_layouter->itemSize().isEmpty()) {
2511 return false;
2512 }
2513
2514 const int maximum = (scrollOrientation() == Qt::Vertical)
2515 ? m_layouter->size().width() / m_layouter->itemSize().width()
2516 : m_layouter->size().height() / m_layouter->itemSize().height();
2517 // Only animate if up to 2/3 of a row or column are inserted or removed
2518 return changedItemCount <= maximum * 2 / 3;
2519 }
2520
2521
2522 bool KItemListView::scrollBarRequired(const QSizeF& size) const
2523 {
2524 const QSizeF oldSize = m_layouter->size();
2525
2526 m_layouter->setSize(size);
2527 const qreal maxOffset = m_layouter->maximumScrollOffset();
2528 m_layouter->setSize(oldSize);
2529
2530 return m_layouter->scrollOrientation() == Qt::Vertical ? maxOffset > size.height()
2531 : maxOffset > size.width();
2532 }
2533
2534 int KItemListView::showDropIndicator(const QPointF& pos)
2535 {
2536 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
2537 while (it.hasNext()) {
2538 it.next();
2539 const KItemListWidget* widget = it.value();
2540
2541 const QPointF mappedPos = widget->mapFromItem(this, pos);
2542 const QRectF rect = itemRect(widget->index());
2543 if (mappedPos.y() >= 0 && mappedPos.y() <= rect.height()) {
2544 if (m_model->supportsDropping(widget->index())) {
2545 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2546 const int gap = qMax(qreal(4.0), qreal(0.3) * rect.height());
2547 if (mappedPos.y() >= gap && mappedPos.y() <= rect.height() - gap) {
2548 return -1;
2549 }
2550 }
2551
2552 const bool isAboveItem = (mappedPos.y () < rect.height() / 2);
2553 const qreal y = isAboveItem ? rect.top() : rect.bottom();
2554
2555 const QRectF draggingInsertIndicator(rect.left(), y, rect.width(), 1);
2556 if (m_dropIndicator != draggingInsertIndicator) {
2557 m_dropIndicator = draggingInsertIndicator;
2558 update();
2559 }
2560
2561 int index = widget->index();
2562 if (!isAboveItem) {
2563 ++index;
2564 }
2565 return index;
2566 }
2567 }
2568
2569 const QRectF firstItemRect = itemRect(firstVisibleIndex());
2570 return (pos.y() <= firstItemRect.top()) ? 0 : -1;
2571 }
2572
2573 void KItemListView::hideDropIndicator()
2574 {
2575 if (!m_dropIndicator.isNull()) {
2576 m_dropIndicator = QRectF();
2577 update();
2578 }
2579 }
2580
2581 void KItemListView::updateGroupHeaderHeight()
2582 {
2583 qreal groupHeaderHeight = m_styleOption.fontMetrics.height();
2584 qreal groupHeaderMargin = 0;
2585
2586 if (scrollOrientation() == Qt::Horizontal) {
2587 // The vertical margin above and below the header should be
2588 // equal to the horizontal margin, not the vertical margin
2589 // from m_styleOption.
2590 groupHeaderHeight += 2 * m_styleOption.horizontalMargin;
2591 groupHeaderMargin = m_styleOption.horizontalMargin;
2592 } else if (m_itemSize.isEmpty()){
2593 groupHeaderHeight += 4 * m_styleOption.padding;
2594 groupHeaderMargin = m_styleOption.iconSize / 2;
2595 } else {
2596 groupHeaderHeight += 2 * m_styleOption.padding + m_styleOption.verticalMargin;
2597 groupHeaderMargin = m_styleOption.iconSize / 4;
2598 }
2599 m_layouter->setGroupHeaderHeight(groupHeaderHeight);
2600 m_layouter->setGroupHeaderMargin(groupHeaderMargin);
2601
2602 updateVisibleGroupHeaders();
2603 }
2604
2605 void KItemListView::updateSiblingsInformation(int firstIndex, int lastIndex)
2606 {
2607 if (!supportsItemExpanding() || !m_model) {
2608 return;
2609 }
2610
2611 if (firstIndex < 0 || lastIndex < 0) {
2612 firstIndex = m_layouter->firstVisibleIndex();
2613 lastIndex = m_layouter->lastVisibleIndex();
2614 } else {
2615 const bool isRangeVisible = (firstIndex <= m_layouter->lastVisibleIndex() &&
2616 lastIndex >= m_layouter->firstVisibleIndex());
2617 if (!isRangeVisible) {
2618 return;
2619 }
2620 }
2621
2622 int previousParents = 0;
2623 QBitArray previousSiblings;
2624
2625 // The rootIndex describes the first index where the siblings get
2626 // calculated from. For the calculation the upper most parent item
2627 // is required. For performance reasons it is checked first whether
2628 // the visible items before or after the current range already
2629 // contain a siblings information which can be used as base.
2630 int rootIndex = firstIndex;
2631
2632 KItemListWidget* widget = m_visibleItems.value(firstIndex - 1);
2633 if (!widget) {
2634 // There is no visible widget before the range, check whether there
2635 // is one after the range:
2636 widget = m_visibleItems.value(lastIndex + 1);
2637 if (widget) {
2638 // The sibling information of the widget may only be used if
2639 // all items of the range have the same number of parents.
2640 const int parents = m_model->expandedParentsCount(lastIndex + 1);
2641 for (int i = lastIndex; i >= firstIndex; --i) {
2642 if (m_model->expandedParentsCount(i) != parents) {
2643 widget = nullptr;
2644 break;
2645 }
2646 }
2647 }
2648 }
2649
2650 if (widget) {
2651 // Performance optimization: Use the sibling information of the visible
2652 // widget beside the given range.
2653 previousSiblings = widget->siblingsInformation();
2654 if (previousSiblings.isEmpty()) {
2655 return;
2656 }
2657 previousParents = previousSiblings.count() - 1;
2658 previousSiblings.truncate(previousParents);
2659 } else {
2660 // Potentially slow path: Go back to the upper most parent of firstIndex
2661 // to be able to calculate the initial value for the siblings.
2662 while (rootIndex > 0 && m_model->expandedParentsCount(rootIndex) > 0) {
2663 --rootIndex;
2664 }
2665 }
2666
2667 Q_ASSERT(previousParents >= 0);
2668 for (int i = rootIndex; i <= lastIndex; ++i) {
2669 // Update the parent-siblings in case if the current item represents
2670 // a child or an upper parent.
2671 const int currentParents = m_model->expandedParentsCount(i);
2672 Q_ASSERT(currentParents >= 0);
2673 if (previousParents < currentParents) {
2674 previousParents = currentParents;
2675 previousSiblings.resize(currentParents);
2676 previousSiblings.setBit(currentParents - 1, hasSiblingSuccessor(i - 1));
2677 } else if (previousParents > currentParents) {
2678 previousParents = currentParents;
2679 previousSiblings.truncate(currentParents);
2680 }
2681
2682 if (i >= firstIndex) {
2683 // The index represents a visible item. Apply the parent-siblings
2684 // and update the sibling of the current item.
2685 KItemListWidget* widget = m_visibleItems.value(i);
2686 if (!widget) {
2687 continue;
2688 }
2689
2690 QBitArray siblings = previousSiblings;
2691 siblings.resize(siblings.count() + 1);
2692 siblings.setBit(siblings.count() - 1, hasSiblingSuccessor(i));
2693
2694 widget->setSiblingsInformation(siblings);
2695 }
2696 }
2697 }
2698
2699 bool KItemListView::hasSiblingSuccessor(int index) const
2700 {
2701 bool hasSuccessor = false;
2702 const int parentsCount = m_model->expandedParentsCount(index);
2703 int successorIndex = index + 1;
2704
2705 // Search the next sibling
2706 const int itemCount = m_model->count();
2707 while (successorIndex < itemCount) {
2708 const int currentParentsCount = m_model->expandedParentsCount(successorIndex);
2709 if (currentParentsCount == parentsCount) {
2710 hasSuccessor = true;
2711 break;
2712 } else if (currentParentsCount < parentsCount) {
2713 break;
2714 }
2715 ++successorIndex;
2716 }
2717
2718 if (m_grouped && hasSuccessor) {
2719 // If the sibling is part of another group, don't mark it as
2720 // successor as the group header is between the sibling connections.
2721 for (int i = index + 1; i <= successorIndex; ++i) {
2722 if (m_layouter->isFirstGroupItem(i)) {
2723 hasSuccessor = false;
2724 break;
2725 }
2726 }
2727 }
2728
2729 return hasSuccessor;
2730 }
2731
2732 void KItemListView::disconnectRoleEditingSignals(int index)
2733 {
2734 KStandardItemListWidget* widget = qobject_cast<KStandardItemListWidget *>(m_visibleItems.value(index));
2735 if (!widget) {
2736 return;
2737 }
2738
2739 disconnect(widget, &KItemListWidget::roleEditingCanceled, this, nullptr);
2740 disconnect(widget, &KItemListWidget::roleEditingFinished, this, nullptr);
2741 disconnect(this, &KItemListView::scrollOffsetChanged, widget, nullptr);
2742 }
2743
2744 int KItemListView::calculateAutoScrollingIncrement(int pos, int range, int oldInc)
2745 {
2746 int inc = 0;
2747
2748 const int minSpeed = 4;
2749 const int maxSpeed = 128;
2750 const int speedLimiter = 96;
2751 const int autoScrollBorder = 64;
2752
2753 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2754 // This assures that the autoscrolling speed grows gradually.
2755 const int incLimiter = 1;
2756
2757 if (pos < autoScrollBorder) {
2758 inc = -minSpeed + qAbs(pos - autoScrollBorder) * (pos - autoScrollBorder) / speedLimiter;
2759 inc = qMax(inc, -maxSpeed);
2760 inc = qMax(inc, oldInc - incLimiter);
2761 } else if (pos > range - autoScrollBorder) {
2762 inc = minSpeed + qAbs(pos - range + autoScrollBorder) * (pos - range + autoScrollBorder) / speedLimiter;
2763 inc = qMin(inc, maxSpeed);
2764 inc = qMin(inc, oldInc + incLimiter);
2765 }
2766
2767 return inc;
2768 }
2769
2770 int KItemListView::itemsPerSize(qreal size, qreal itemSize, qreal itemMargin)
2771 {
2772 const qreal availableSize = size - itemMargin;
2773 const int count = availableSize / (itemSize + itemMargin);
2774 return count;
2775 }
2776
2777
2778
2779 KItemListCreatorBase::~KItemListCreatorBase()
2780 {
2781 qDeleteAll(m_recycleableWidgets);
2782 qDeleteAll(m_createdWidgets);
2783 }
2784
2785 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget* widget)
2786 {
2787 m_createdWidgets.insert(widget);
2788 }
2789
2790 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget* widget)
2791 {
2792 Q_ASSERT(m_createdWidgets.contains(widget));
2793 m_createdWidgets.remove(widget);
2794
2795 if (m_recycleableWidgets.count() < 100) {
2796 m_recycleableWidgets.append(widget);
2797 widget->setVisible(false);
2798 } else {
2799 delete widget;
2800 }
2801 }
2802
2803 QGraphicsWidget* KItemListCreatorBase::popRecycleableWidget()
2804 {
2805 if (m_recycleableWidgets.isEmpty()) {
2806 return nullptr;
2807 }
2808
2809 QGraphicsWidget* widget = m_recycleableWidgets.takeLast();
2810 m_createdWidgets.insert(widget);
2811 return widget;
2812 }
2813
2814 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2815 {
2816 }
2817
2818 void KItemListWidgetCreatorBase::recycle(KItemListWidget* widget)
2819 {
2820 widget->setParentItem(nullptr);
2821 widget->setOpacity(1.0);
2822 pushRecycleableWidget(widget);
2823 }
2824
2825 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2826 {
2827 }
2828
2829 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader* header)
2830 {
2831 header->setOpacity(1.0);
2832 pushRecycleableWidget(header);
2833 }
2834