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