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