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