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