]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kitemlistview.cpp
Allow interaction with folder/files with the stylus again
[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 foreach (const QByteArray& role, 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 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 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 foreach (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 foreach (KItemListWidget* widget, m_visibleItems) {
1159 const int i = widget->index();
1160 if (i < firstRemovedIndex) {
1161 continue;
1162 } else if (i > lastRemovedIndex) {
1163 itemsToMove.append(i);
1164 continue;
1165 }
1166
1167 m_animation->stop(widget);
1168 // Stopping the animation might lead to recycling the widget if
1169 // it is invisible (see slotAnimationFinished()).
1170 // Check again whether it is still visible:
1171 if (!m_visibleItems.contains(i)) {
1172 continue;
1173 }
1174
1175 if (m_model->count() == 0 || hasMultipleRanges || !animateChangedItemCount(count)) {
1176 // Remove the widget without animation
1177 recycleWidget(widget);
1178 } else {
1179 // Animate the removing of the items. Special case: When removing an item there
1180 // is no valid model index available anymore. For the
1181 // remove-animation the item gets removed from m_visibleItems but the widget
1182 // will stay alive until the animation has been finished and will
1183 // be recycled (deleted) in KItemListView::slotAnimationFinished().
1184 m_visibleItems.remove(i);
1185 widget->setIndex(-1);
1186 m_animation->start(widget, KItemListViewAnimation::DeleteAnimation);
1187 }
1188 }
1189
1190 // Update the indexes of all KItemListWidget instances that are located
1191 // after the deleted items. It is important to update them in ascending
1192 // order to prevent overlaps when setting the new index.
1193 std::sort(itemsToMove.begin(), itemsToMove.end());
1194 foreach (int i, itemsToMove) {
1195 KItemListWidget* widget = m_visibleItems.value(i);
1196 Q_ASSERT(widget);
1197 const int newIndex = i - count;
1198 if (hasMultipleRanges) {
1199 setWidgetIndex(widget, newIndex);
1200 } else {
1201 // Try to animate the moving of the item
1202 moveWidgetToIndex(widget, newIndex);
1203 }
1204 }
1205
1206 if (!hasMultipleRanges) {
1207 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
1208 // assumes an updated geometry. If items are removed during an active transaction,
1209 // the transaction will be temporary deactivated so that doLayout() triggers a
1210 // geometry update if necessary.
1211 const int activeTransactions = m_activeTransactions;
1212 m_activeTransactions = 0;
1213 doLayout(animateChangedItemCount(count) ? Animation : NoAnimation, index, -count);
1214 m_activeTransactions = activeTransactions;
1215 updateSiblingsInformation();
1216 }
1217 }
1218
1219 if (m_controller) {
1220 m_controller->selectionManager()->itemsRemoved(itemRanges);
1221 }
1222
1223 if (hasMultipleRanges) {
1224 m_endTransactionAnimationHint = NoAnimation;
1225 endTransaction();
1226 updateSiblingsInformation();
1227 }
1228
1229 if (m_grouped && (hasMultipleRanges || m_model->count() > 0)) {
1230 // In case if the first item of a group has been removed, the group header
1231 // must be applied to the next visible item.
1232 updateVisibleGroupHeaders();
1233 }
1234
1235 if (useAlternateBackgrounds()) {
1236 updateAlternateBackgrounds();
1237 }
1238 }
1239
1240 void KItemListView::slotItemsMoved(const KItemRange& itemRange, const QList<int>& movedToIndexes)
1241 {
1242 m_sizeHintResolver->itemsMoved(itemRange, movedToIndexes);
1243 m_layouter->markAsDirty();
1244
1245 if (m_controller) {
1246 m_controller->selectionManager()->itemsMoved(itemRange, movedToIndexes);
1247 }
1248
1249 const int firstVisibleMovedIndex = qMax(firstVisibleIndex(), itemRange.index);
1250 const int lastVisibleMovedIndex = qMin(lastVisibleIndex(), itemRange.index + itemRange.count - 1);
1251
1252 for (int index = firstVisibleMovedIndex; index <= lastVisibleMovedIndex; ++index) {
1253 KItemListWidget* widget = m_visibleItems.value(index);
1254 if (widget) {
1255 updateWidgetProperties(widget, index);
1256 initializeItemListWidget(widget);
1257 }
1258 }
1259
1260 doLayout(NoAnimation);
1261 updateSiblingsInformation();
1262 }
1263
1264 void KItemListView::slotItemsChanged(const KItemRangeList& itemRanges,
1265 const QSet<QByteArray>& roles)
1266 {
1267 const bool updateSizeHints = itemSizeHintUpdateRequired(roles);
1268 if (updateSizeHints && m_itemSize.isEmpty()) {
1269 updatePreferredColumnWidths(itemRanges);
1270 }
1271
1272 foreach (const KItemRange& itemRange, itemRanges) {
1273 const int index = itemRange.index;
1274 const int count = itemRange.count;
1275
1276 if (updateSizeHints) {
1277 m_sizeHintResolver->itemsChanged(index, count, roles);
1278 m_layouter->markAsDirty();
1279
1280 if (!m_layoutTimer->isActive()) {
1281 m_layoutTimer->start();
1282 }
1283 }
1284
1285 // Apply the changed roles to the visible item-widgets
1286 const int lastIndex = index + count - 1;
1287 for (int i = index; i <= lastIndex; ++i) {
1288 KItemListWidget* widget = m_visibleItems.value(i);
1289 if (widget) {
1290 widget->setData(m_model->data(i), roles);
1291 }
1292 }
1293
1294 if (m_grouped && roles.contains(m_model->sortRole())) {
1295 // The sort-role has been changed which might result
1296 // in modified group headers
1297 updateVisibleGroupHeaders();
1298 doLayout(NoAnimation);
1299 }
1300
1301 QAccessibleTableModelChangeEvent ev(this, QAccessibleTableModelChangeEvent::DataChanged);
1302 ev.setFirstRow(itemRange.index);
1303 ev.setLastRow(itemRange.index + itemRange.count);
1304 QAccessible::updateAccessibility(&ev);
1305 }
1306 }
1307
1308 void KItemListView::slotGroupsChanged()
1309 {
1310 updateVisibleGroupHeaders();
1311 doLayout(NoAnimation);
1312 updateSiblingsInformation();
1313 }
1314
1315 void KItemListView::slotGroupedSortingChanged(bool current)
1316 {
1317 m_grouped = current;
1318 m_layouter->markAsDirty();
1319
1320 if (m_grouped) {
1321 updateGroupHeaderHeight();
1322 } else {
1323 // Clear all visible headers. Note that the QHashIterator takes a copy of
1324 // m_visibleGroups. Therefore, it remains valid even if items are removed
1325 // from m_visibleGroups in recycleGroupHeaderForWidget().
1326 QHashIterator<KItemListWidget*, KItemListGroupHeader*> it(m_visibleGroups);
1327 while (it.hasNext()) {
1328 it.next();
1329 recycleGroupHeaderForWidget(it.key());
1330 }
1331 Q_ASSERT(m_visibleGroups.isEmpty());
1332 }
1333
1334 if (useAlternateBackgrounds()) {
1335 // Changing the group mode requires to update the alternate backgrounds
1336 // as with the enabled group mode the altering is done on base of the first
1337 // group item.
1338 updateAlternateBackgrounds();
1339 }
1340 updateSiblingsInformation();
1341 doLayout(NoAnimation);
1342 }
1343
1344 void KItemListView::slotSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous)
1345 {
1346 Q_UNUSED(current)
1347 Q_UNUSED(previous)
1348 if (m_grouped) {
1349 updateVisibleGroupHeaders();
1350 doLayout(NoAnimation);
1351 }
1352 }
1353
1354 void KItemListView::slotSortRoleChanged(const QByteArray& current, const QByteArray& previous)
1355 {
1356 Q_UNUSED(current)
1357 Q_UNUSED(previous)
1358 if (m_grouped) {
1359 updateVisibleGroupHeaders();
1360 doLayout(NoAnimation);
1361 }
1362 }
1363
1364 void KItemListView::slotCurrentChanged(int current, int previous)
1365 {
1366 Q_UNUSED(previous)
1367
1368 // In SingleSelection mode (e.g., in the Places Panel), the current item is
1369 // always the selected item. It is not necessary to highlight the current item then.
1370 if (m_controller->selectionBehavior() != KItemListController::SingleSelection) {
1371 KItemListWidget* previousWidget = m_visibleItems.value(previous, nullptr);
1372 if (previousWidget) {
1373 previousWidget->setCurrent(false);
1374 }
1375
1376 KItemListWidget* currentWidget = m_visibleItems.value(current, nullptr);
1377 if (currentWidget) {
1378 currentWidget->setCurrent(true);
1379 }
1380 }
1381
1382 QAccessibleEvent ev(this, QAccessible::Focus);
1383 ev.setChild(current);
1384 QAccessible::updateAccessibility(&ev);
1385 }
1386
1387 void KItemListView::slotSelectionChanged(const KItemSet& current, const KItemSet& previous)
1388 {
1389 Q_UNUSED(previous)
1390
1391 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
1392 while (it.hasNext()) {
1393 it.next();
1394 const int index = it.key();
1395 KItemListWidget* widget = it.value();
1396 widget->setSelected(current.contains(index));
1397 }
1398 }
1399
1400 void KItemListView::slotAnimationFinished(QGraphicsWidget* widget,
1401 KItemListViewAnimation::AnimationType type)
1402 {
1403 KItemListWidget* itemListWidget = qobject_cast<KItemListWidget*>(widget);
1404 Q_ASSERT(itemListWidget);
1405
1406 switch (type) {
1407 case KItemListViewAnimation::DeleteAnimation: {
1408 // As we recycle the widget in this case it is important to assure that no
1409 // other animation has been started. This is a convention in KItemListView and
1410 // not a requirement defined by KItemListViewAnimation.
1411 Q_ASSERT(!m_animation->isStarted(itemListWidget));
1412
1413 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1414 // by m_visibleWidgets and must be deleted manually after the animation has
1415 // been finished.
1416 recycleGroupHeaderForWidget(itemListWidget);
1417 widgetCreator()->recycle(itemListWidget);
1418 break;
1419 }
1420
1421 case KItemListViewAnimation::CreateAnimation:
1422 case KItemListViewAnimation::MovingAnimation:
1423 case KItemListViewAnimation::ResizeAnimation: {
1424 const int index = itemListWidget->index();
1425 const bool invisible = (index < m_layouter->firstVisibleIndex()) ||
1426 (index > m_layouter->lastVisibleIndex());
1427 if (invisible && !m_animation->isStarted(itemListWidget)) {
1428 recycleWidget(itemListWidget);
1429 }
1430 break;
1431 }
1432
1433 default: break;
1434 }
1435 }
1436
1437 void KItemListView::slotLayoutTimerFinished()
1438 {
1439 m_layouter->setSize(geometry().size());
1440 doLayout(Animation);
1441 }
1442
1443 void KItemListView::slotRubberBandPosChanged()
1444 {
1445 update();
1446 }
1447
1448 void KItemListView::slotRubberBandActivationChanged(bool active)
1449 {
1450 if (active) {
1451 connect(m_rubberBand, &KItemListRubberBand::startPositionChanged, this, &KItemListView::slotRubberBandPosChanged);
1452 connect(m_rubberBand, &KItemListRubberBand::endPositionChanged, this, &KItemListView::slotRubberBandPosChanged);
1453 m_skipAutoScrollForRubberBand = true;
1454 } else {
1455 disconnect(m_rubberBand, &KItemListRubberBand::startPositionChanged, this, &KItemListView::slotRubberBandPosChanged);
1456 disconnect(m_rubberBand, &KItemListRubberBand::endPositionChanged, this, &KItemListView::slotRubberBandPosChanged);
1457 m_skipAutoScrollForRubberBand = false;
1458 }
1459
1460 update();
1461 }
1462
1463 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray& role,
1464 qreal currentWidth,
1465 qreal previousWidth)
1466 {
1467 Q_UNUSED(role)
1468 Q_UNUSED(currentWidth)
1469 Q_UNUSED(previousWidth)
1470
1471 m_headerWidget->setAutomaticColumnResizing(false);
1472 applyColumnWidthsFromHeader();
1473 doLayout(NoAnimation);
1474 }
1475
1476 void KItemListView::slotHeaderColumnMoved(const QByteArray& role,
1477 int currentIndex,
1478 int previousIndex)
1479 {
1480 Q_ASSERT(m_visibleRoles[previousIndex] == role);
1481
1482 const QList<QByteArray> previous = m_visibleRoles;
1483
1484 QList<QByteArray> current = m_visibleRoles;
1485 current.removeAt(previousIndex);
1486 current.insert(currentIndex, role);
1487
1488 setVisibleRoles(current);
1489
1490 emit visibleRolesChanged(current, previous);
1491 }
1492
1493 void KItemListView::triggerAutoScrolling()
1494 {
1495 if (!m_autoScrollTimer) {
1496 return;
1497 }
1498
1499 int pos = 0;
1500 int visibleSize = 0;
1501 if (scrollOrientation() == Qt::Vertical) {
1502 pos = m_mousePos.y();
1503 visibleSize = size().height();
1504 } else {
1505 pos = m_mousePos.x();
1506 visibleSize = size().width();
1507 }
1508
1509 if (m_autoScrollTimer->interval() == InitialAutoScrollDelay) {
1510 m_autoScrollIncrement = 0;
1511 }
1512
1513 m_autoScrollIncrement = calculateAutoScrollingIncrement(pos, visibleSize, m_autoScrollIncrement);
1514 if (m_autoScrollIncrement == 0) {
1515 // The mouse position is not above an autoscroll margin (the autoscroll timer
1516 // will be restarted in mouseMoveEvent())
1517 m_autoScrollTimer->stop();
1518 return;
1519 }
1520
1521 if (m_rubberBand->isActive() && m_skipAutoScrollForRubberBand) {
1522 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1523 // if the direction of the rubberband is similar to the autoscroll direction. This
1524 // prevents that starting to create a rubberband within the autoscroll margins starts
1525 // an autoscrolling.
1526
1527 const qreal minDiff = 4; // Ignore any autoscrolling if the rubberband is very small
1528 const qreal diff = (scrollOrientation() == Qt::Vertical)
1529 ? m_rubberBand->endPosition().y() - m_rubberBand->startPosition().y()
1530 : m_rubberBand->endPosition().x() - m_rubberBand->startPosition().x();
1531 if (qAbs(diff) < minDiff || (m_autoScrollIncrement < 0 && diff > 0) || (m_autoScrollIncrement > 0 && diff < 0)) {
1532 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1533 // been moved up although the autoscroll direction might be down)
1534 m_autoScrollTimer->stop();
1535 return;
1536 }
1537 }
1538
1539 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1540 // the autoscrolling may not get skipped anymore until a new rubberband is created
1541 m_skipAutoScrollForRubberBand = false;
1542
1543 const qreal maxVisibleOffset = qMax(qreal(0), maximumScrollOffset() - visibleSize);
1544 const qreal newScrollOffset = qMin(scrollOffset() + m_autoScrollIncrement, maxVisibleOffset);
1545 setScrollOffset(newScrollOffset);
1546
1547 // Trigger the autoscroll timer which will periodically call
1548 // triggerAutoScrolling()
1549 m_autoScrollTimer->start(RepeatingAutoScrollDelay);
1550 }
1551
1552 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1553 {
1554 KItemListWidget* widget = qobject_cast<KItemListWidget*>(sender());
1555 Q_ASSERT(widget);
1556 KItemListGroupHeader* groupHeader = m_visibleGroups.value(widget);
1557 Q_ASSERT(groupHeader);
1558 updateGroupHeaderLayout(widget);
1559 }
1560
1561 void KItemListView::slotRoleEditingCanceled(int index, const QByteArray& role, const QVariant& value)
1562 {
1563 disconnectRoleEditingSignals(index);
1564
1565 emit roleEditingCanceled(index, role, value);
1566 m_editingRole = false;
1567 }
1568
1569 void KItemListView::slotRoleEditingFinished(int index, const QByteArray& role, const QVariant& value)
1570 {
1571 disconnectRoleEditingSignals(index);
1572
1573 emit roleEditingFinished(index, role, value);
1574 m_editingRole = false;
1575 }
1576
1577 void KItemListView::setController(KItemListController* controller)
1578 {
1579 if (m_controller != controller) {
1580 KItemListController* previous = m_controller;
1581 if (previous) {
1582 KItemListSelectionManager* selectionManager = previous->selectionManager();
1583 disconnect(selectionManager, &KItemListSelectionManager::currentChanged, this, &KItemListView::slotCurrentChanged);
1584 disconnect(selectionManager, &KItemListSelectionManager::selectionChanged, this, &KItemListView::slotSelectionChanged);
1585 }
1586
1587 m_controller = controller;
1588
1589 if (controller) {
1590 KItemListSelectionManager* selectionManager = controller->selectionManager();
1591 connect(selectionManager, &KItemListSelectionManager::currentChanged, this, &KItemListView::slotCurrentChanged);
1592 connect(selectionManager, &KItemListSelectionManager::selectionChanged, this, &KItemListView::slotSelectionChanged);
1593 }
1594
1595 onControllerChanged(controller, previous);
1596 }
1597 }
1598
1599 void KItemListView::setModel(KItemModelBase* model)
1600 {
1601 if (m_model == model) {
1602 return;
1603 }
1604
1605 KItemModelBase* previous = m_model;
1606
1607 if (m_model) {
1608 disconnect(m_model, &KItemModelBase::itemsChanged,
1609 this, &KItemListView::slotItemsChanged);
1610 disconnect(m_model, &KItemModelBase::itemsInserted,
1611 this, &KItemListView::slotItemsInserted);
1612 disconnect(m_model, &KItemModelBase::itemsRemoved,
1613 this, &KItemListView::slotItemsRemoved);
1614 disconnect(m_model, &KItemModelBase::itemsMoved,
1615 this, &KItemListView::slotItemsMoved);
1616 disconnect(m_model, &KItemModelBase::groupsChanged,
1617 this, &KItemListView::slotGroupsChanged);
1618 disconnect(m_model, &KItemModelBase::groupedSortingChanged,
1619 this, &KItemListView::slotGroupedSortingChanged);
1620 disconnect(m_model, &KItemModelBase::sortOrderChanged,
1621 this, &KItemListView::slotSortOrderChanged);
1622 disconnect(m_model, &KItemModelBase::sortRoleChanged,
1623 this, &KItemListView::slotSortRoleChanged);
1624
1625 m_sizeHintResolver->itemsRemoved(KItemRangeList() << KItemRange(0, m_model->count()));
1626 }
1627
1628 m_model = model;
1629 m_layouter->setModel(model);
1630 m_grouped = model->groupedSorting();
1631
1632 if (m_model) {
1633 connect(m_model, &KItemModelBase::itemsChanged,
1634 this, &KItemListView::slotItemsChanged);
1635 connect(m_model, &KItemModelBase::itemsInserted,
1636 this, &KItemListView::slotItemsInserted);
1637 connect(m_model, &KItemModelBase::itemsRemoved,
1638 this, &KItemListView::slotItemsRemoved);
1639 connect(m_model, &KItemModelBase::itemsMoved,
1640 this, &KItemListView::slotItemsMoved);
1641 connect(m_model, &KItemModelBase::groupsChanged,
1642 this, &KItemListView::slotGroupsChanged);
1643 connect(m_model, &KItemModelBase::groupedSortingChanged,
1644 this, &KItemListView::slotGroupedSortingChanged);
1645 connect(m_model, &KItemModelBase::sortOrderChanged,
1646 this, &KItemListView::slotSortOrderChanged);
1647 connect(m_model, &KItemModelBase::sortRoleChanged,
1648 this, &KItemListView::slotSortRoleChanged);
1649
1650 const int itemCount = m_model->count();
1651 if (itemCount > 0) {
1652 slotItemsInserted(KItemRangeList() << KItemRange(0, itemCount));
1653 }
1654 }
1655
1656 onModelChanged(model, previous);
1657 }
1658
1659 KItemListRubberBand* KItemListView::rubberBand() const
1660 {
1661 return m_rubberBand;
1662 }
1663
1664 void KItemListView::doLayout(LayoutAnimationHint hint, int changedIndex, int changedCount)
1665 {
1666 if (m_layoutTimer->isActive()) {
1667 m_layoutTimer->stop();
1668 }
1669
1670 if (m_activeTransactions > 0) {
1671 if (hint == NoAnimation) {
1672 // As soon as at least one property change should be done without animation,
1673 // the whole transaction will be marked as not animated.
1674 m_endTransactionAnimationHint = NoAnimation;
1675 }
1676 return;
1677 }
1678
1679 if (!m_model || m_model->count() < 0) {
1680 return;
1681 }
1682
1683 int firstVisibleIndex = m_layouter->firstVisibleIndex();
1684 if (firstVisibleIndex < 0) {
1685 emitOffsetChanges();
1686 return;
1687 }
1688
1689 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1690 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1691 // is still shown if the maximum offset got decreased.
1692 const qreal visibleOffsetRange = (scrollOrientation() == Qt::Horizontal) ? size().width() : size().height();
1693 const qreal maxOffsetToShowFullRange = maximumScrollOffset() - visibleOffsetRange;
1694 if (scrollOffset() > maxOffsetToShowFullRange) {
1695 m_layouter->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange));
1696 firstVisibleIndex = m_layouter->firstVisibleIndex();
1697 }
1698
1699 const int lastVisibleIndex = m_layouter->lastVisibleIndex();
1700
1701 int firstSibblingIndex = -1;
1702 int lastSibblingIndex = -1;
1703 const bool supportsExpanding = supportsItemExpanding();
1704
1705 QList<int> reusableItems = recycleInvisibleItems(firstVisibleIndex, lastVisibleIndex, hint);
1706
1707 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1708 // instances from invisible items are reused. If no reusable items are
1709 // found then new KItemListWidget instances get created.
1710 const bool animate = (hint == Animation);
1711 for (int i = firstVisibleIndex; i <= lastVisibleIndex; ++i) {
1712 bool applyNewPos = true;
1713 bool wasHidden = false;
1714
1715 const QRectF itemBounds = m_layouter->itemRect(i);
1716 const QPointF newPos = itemBounds.topLeft();
1717 KItemListWidget* widget = m_visibleItems.value(i);
1718 if (!widget) {
1719 wasHidden = true;
1720 if (!reusableItems.isEmpty()) {
1721 // Reuse a KItemListWidget instance from an invisible item
1722 const int oldIndex = reusableItems.takeLast();
1723 widget = m_visibleItems.value(oldIndex);
1724 setWidgetIndex(widget, i);
1725 updateWidgetProperties(widget, i);
1726 initializeItemListWidget(widget);
1727 } else {
1728 // No reusable KItemListWidget instance is available, create a new one
1729 widget = createWidget(i);
1730 }
1731 widget->resize(itemBounds.size());
1732
1733 if (animate && changedCount < 0) {
1734 // Items have been deleted.
1735 if (i >= changedIndex) {
1736 // The item is located behind the removed range. Move the
1737 // created item to the imaginary old position outside the
1738 // view. It will get animated to the new position later.
1739 const int previousIndex = i - changedCount;
1740 const QRectF itemRect = m_layouter->itemRect(previousIndex);
1741 if (itemRect.isEmpty()) {
1742 const QPointF invisibleOldPos = (scrollOrientation() == Qt::Vertical)
1743 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1744 widget->setPos(invisibleOldPos);
1745 } else {
1746 widget->setPos(itemRect.topLeft());
1747 }
1748 applyNewPos = false;
1749 }
1750 }
1751
1752 if (supportsExpanding && changedCount == 0) {
1753 if (firstSibblingIndex < 0) {
1754 firstSibblingIndex = i;
1755 }
1756 lastSibblingIndex = i;
1757 }
1758 }
1759
1760 if (animate) {
1761 if (m_animation->isStarted(widget, KItemListViewAnimation::MovingAnimation)) {
1762 m_animation->start(widget, KItemListViewAnimation::MovingAnimation, newPos);
1763 applyNewPos = false;
1764 }
1765
1766 const bool itemsRemoved = (changedCount < 0);
1767 const bool itemsInserted = (changedCount > 0);
1768 if (itemsRemoved && (i >= changedIndex)) {
1769 // The item is located after the removed items. Animate the moving of the position.
1770 applyNewPos = !moveWidget(widget, newPos);
1771 } else if (itemsInserted && i >= changedIndex) {
1772 // The item is located after the first inserted item
1773 if (i <= changedIndex + changedCount - 1) {
1774 // The item is an inserted item. Animate the appearing of the item.
1775 // For performance reasons no animation is done when changedCount is equal
1776 // to all available items.
1777 if (changedCount < m_model->count()) {
1778 m_animation->start(widget, KItemListViewAnimation::CreateAnimation);
1779 }
1780 } else if (!m_animation->isStarted(widget, KItemListViewAnimation::CreateAnimation)) {
1781 // The item was already there before, so animate the moving of the position.
1782 // No moving animation is done if the item is animated by a create animation: This
1783 // prevents a "move animation mess" when inserting several ranges in parallel.
1784 applyNewPos = !moveWidget(widget, newPos);
1785 }
1786 } else if (!itemsRemoved && !itemsInserted && !wasHidden) {
1787 // The size of the view might have been changed. Animate the moving of the position.
1788 applyNewPos = !moveWidget(widget, newPos);
1789 }
1790 } else {
1791 m_animation->stop(widget);
1792 }
1793
1794 if (applyNewPos) {
1795 widget->setPos(newPos);
1796 }
1797
1798 Q_ASSERT(widget->index() == i);
1799 widget->setVisible(true);
1800
1801 if (widget->size() != itemBounds.size()) {
1802 // Resize the widget for the item to the changed size.
1803 if (animate) {
1804 // If a dynamic item size is used then no animation is done in the direction
1805 // of the dynamic size.
1806 if (m_itemSize.width() <= 0) {
1807 // The width is dynamic, apply the new width without animation.
1808 widget->resize(itemBounds.width(), widget->size().height());
1809 } else if (m_itemSize.height() <= 0) {
1810 // The height is dynamic, apply the new height without animation.
1811 widget->resize(widget->size().width(), itemBounds.height());
1812 }
1813 m_animation->start(widget, KItemListViewAnimation::ResizeAnimation, itemBounds.size());
1814 } else {
1815 widget->resize(itemBounds.size());
1816 }
1817 }
1818
1819 // Updating the cell-information must be done as last step: The decision whether the
1820 // moving-animation should be started at all is based on the previous cell-information.
1821 const Cell cell(m_layouter->itemColumn(i), m_layouter->itemRow(i));
1822 m_visibleCells.insert(i, cell);
1823 }
1824
1825 // Delete invisible KItemListWidget instances that have not been reused
1826 foreach (int index, reusableItems) {
1827 recycleWidget(m_visibleItems.value(index));
1828 }
1829
1830 if (supportsExpanding && firstSibblingIndex >= 0) {
1831 Q_ASSERT(lastSibblingIndex >= 0);
1832 updateSiblingsInformation(firstSibblingIndex, lastSibblingIndex);
1833 }
1834
1835 if (m_grouped) {
1836 // Update the layout of all visible group headers
1837 QHashIterator<KItemListWidget*, KItemListGroupHeader*> it(m_visibleGroups);
1838 while (it.hasNext()) {
1839 it.next();
1840 updateGroupHeaderLayout(it.key());
1841 }
1842 }
1843
1844 emitOffsetChanges();
1845 }
1846
1847 QList<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex,
1848 int lastVisibleIndex,
1849 LayoutAnimationHint hint)
1850 {
1851 // Determine all items that are completely invisible and might be
1852 // reused for items that just got (at least partly) visible. If the
1853 // animation hint is set to 'Animation' items that do e.g. an animated
1854 // moving of their position are not marked as invisible: This assures
1855 // that a scrolling inside the view can be done without breaking an animation.
1856
1857 QList<int> items;
1858
1859 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
1860 while (it.hasNext()) {
1861 it.next();
1862
1863 KItemListWidget* widget = it.value();
1864 const int index = widget->index();
1865 const bool invisible = (index < firstVisibleIndex) || (index > lastVisibleIndex);
1866
1867 if (invisible) {
1868 if (m_animation->isStarted(widget)) {
1869 if (hint == NoAnimation) {
1870 // Stopping the animation will call KItemListView::slotAnimationFinished()
1871 // and the widget will be recycled if necessary there.
1872 m_animation->stop(widget);
1873 }
1874 } else {
1875 widget->setVisible(false);
1876 items.append(index);
1877
1878 if (m_grouped) {
1879 recycleGroupHeaderForWidget(widget);
1880 }
1881 }
1882 }
1883 }
1884
1885 return items;
1886 }
1887
1888 bool KItemListView::moveWidget(KItemListWidget* widget,const QPointF& newPos)
1889 {
1890 if (widget->pos() == newPos) {
1891 return false;
1892 }
1893
1894 bool startMovingAnim = false;
1895
1896 if (m_itemSize.isEmpty()) {
1897 // The items are not aligned in a grid but either as columns or rows.
1898 startMovingAnim = true;
1899 } else {
1900 // When having a grid the moving-animation should only be started, if it is done within
1901 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1902 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1903 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1904 const int index = widget->index();
1905 const Cell cell = m_visibleCells.value(index);
1906 if (cell.column >= 0 && cell.row >= 0) {
1907 if (scrollOrientation() == Qt::Vertical) {
1908 startMovingAnim = (cell.row == m_layouter->itemRow(index));
1909 } else {
1910 startMovingAnim = (cell.column == m_layouter->itemColumn(index));
1911 }
1912 }
1913 }
1914
1915 if (startMovingAnim) {
1916 m_animation->start(widget, KItemListViewAnimation::MovingAnimation, newPos);
1917 return true;
1918 }
1919
1920 m_animation->stop(widget);
1921 m_animation->start(widget, KItemListViewAnimation::CreateAnimation);
1922 return false;
1923 }
1924
1925 void KItemListView::emitOffsetChanges()
1926 {
1927 const qreal newScrollOffset = m_layouter->scrollOffset();
1928 if (m_oldScrollOffset != newScrollOffset) {
1929 emit scrollOffsetChanged(newScrollOffset, m_oldScrollOffset);
1930 m_oldScrollOffset = newScrollOffset;
1931 }
1932
1933 const qreal newMaximumScrollOffset = m_layouter->maximumScrollOffset();
1934 if (m_oldMaximumScrollOffset != newMaximumScrollOffset) {
1935 emit maximumScrollOffsetChanged(newMaximumScrollOffset, m_oldMaximumScrollOffset);
1936 m_oldMaximumScrollOffset = newMaximumScrollOffset;
1937 }
1938
1939 const qreal newItemOffset = m_layouter->itemOffset();
1940 if (m_oldItemOffset != newItemOffset) {
1941 emit itemOffsetChanged(newItemOffset, m_oldItemOffset);
1942 m_oldItemOffset = newItemOffset;
1943 }
1944
1945 const qreal newMaximumItemOffset = m_layouter->maximumItemOffset();
1946 if (m_oldMaximumItemOffset != newMaximumItemOffset) {
1947 emit maximumItemOffsetChanged(newMaximumItemOffset, m_oldMaximumItemOffset);
1948 m_oldMaximumItemOffset = newMaximumItemOffset;
1949 }
1950 }
1951
1952 KItemListWidget* KItemListView::createWidget(int index)
1953 {
1954 KItemListWidget* widget = widgetCreator()->create(this);
1955 widget->setFlag(QGraphicsItem::ItemStacksBehindParent);
1956
1957 m_visibleItems.insert(index, widget);
1958 m_visibleCells.insert(index, Cell());
1959 updateWidgetProperties(widget, index);
1960 initializeItemListWidget(widget);
1961 return widget;
1962 }
1963
1964 void KItemListView::recycleWidget(KItemListWidget* widget)
1965 {
1966 if (m_grouped) {
1967 recycleGroupHeaderForWidget(widget);
1968 }
1969
1970 const int index = widget->index();
1971 m_visibleItems.remove(index);
1972 m_visibleCells.remove(index);
1973
1974 widgetCreator()->recycle(widget);
1975 }
1976
1977 void KItemListView::setWidgetIndex(KItemListWidget* widget, int index)
1978 {
1979 const int oldIndex = widget->index();
1980 m_visibleItems.remove(oldIndex);
1981 m_visibleCells.remove(oldIndex);
1982
1983 m_visibleItems.insert(index, widget);
1984 m_visibleCells.insert(index, Cell());
1985
1986 widget->setIndex(index);
1987 }
1988
1989 void KItemListView::moveWidgetToIndex(KItemListWidget* widget, int index)
1990 {
1991 const int oldIndex = widget->index();
1992 const Cell oldCell = m_visibleCells.value(oldIndex);
1993
1994 setWidgetIndex(widget, index);
1995
1996 const Cell newCell(m_layouter->itemColumn(index), m_layouter->itemRow(index));
1997 const bool vertical = (scrollOrientation() == Qt::Vertical);
1998 const bool updateCell = (vertical && oldCell.row == newCell.row) ||
1999 (!vertical && oldCell.column == newCell.column);
2000 if (updateCell) {
2001 m_visibleCells.insert(index, newCell);
2002 }
2003 }
2004
2005 void KItemListView::setLayouterSize(const QSizeF& size, SizeType sizeType)
2006 {
2007 switch (sizeType) {
2008 case LayouterSize: m_layouter->setSize(size); break;
2009 case ItemSize: m_layouter->setItemSize(size); break;
2010 default: break;
2011 }
2012 }
2013
2014 void KItemListView::updateWidgetProperties(KItemListWidget* widget, int index)
2015 {
2016 widget->setVisibleRoles(m_visibleRoles);
2017 updateWidgetColumnWidths(widget);
2018 widget->setStyleOption(m_styleOption);
2019
2020 const KItemListSelectionManager* selectionManager = m_controller->selectionManager();
2021
2022 // In SingleSelection mode (e.g., in the Places Panel), the current item is
2023 // always the selected item. It is not necessary to highlight the current item then.
2024 if (m_controller->selectionBehavior() != KItemListController::SingleSelection) {
2025 widget->setCurrent(index == selectionManager->currentItem());
2026 }
2027 widget->setSelected(selectionManager->isSelected(index));
2028 widget->setHovered(false);
2029 widget->setEnabledSelectionToggle(enabledSelectionToggles());
2030 widget->setIndex(index);
2031 widget->setData(m_model->data(index));
2032 widget->setSiblingsInformation(QBitArray());
2033 updateAlternateBackgroundForWidget(widget);
2034
2035 if (m_grouped) {
2036 updateGroupHeaderForWidget(widget);
2037 }
2038 }
2039
2040 void KItemListView::updateGroupHeaderForWidget(KItemListWidget* widget)
2041 {
2042 Q_ASSERT(m_grouped);
2043
2044 const int index = widget->index();
2045 if (!m_layouter->isFirstGroupItem(index)) {
2046 // The widget does not represent the first item of a group
2047 // and hence requires no header
2048 recycleGroupHeaderForWidget(widget);
2049 return;
2050 }
2051
2052 const QList<QPair<int, QVariant> > groups = model()->groups();
2053 if (groups.isEmpty() || !groupHeaderCreator()) {
2054 return;
2055 }
2056
2057 KItemListGroupHeader* groupHeader = m_visibleGroups.value(widget);
2058 if (!groupHeader) {
2059 groupHeader = groupHeaderCreator()->create(this);
2060 groupHeader->setParentItem(widget);
2061 m_visibleGroups.insert(widget, groupHeader);
2062 connect(widget, &KItemListWidget::geometryChanged, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged);
2063 }
2064 Q_ASSERT(groupHeader->parentItem() == widget);
2065
2066 const int groupIndex = groupIndexForItem(index);
2067 Q_ASSERT(groupIndex >= 0);
2068 groupHeader->setData(groups.at(groupIndex).second);
2069 groupHeader->setRole(model()->sortRole());
2070 groupHeader->setStyleOption(m_styleOption);
2071 groupHeader->setScrollOrientation(scrollOrientation());
2072 groupHeader->setItemIndex(index);
2073
2074 groupHeader->show();
2075 }
2076
2077 void KItemListView::updateGroupHeaderLayout(KItemListWidget* widget)
2078 {
2079 KItemListGroupHeader* groupHeader = m_visibleGroups.value(widget);
2080 Q_ASSERT(groupHeader);
2081
2082 const int index = widget->index();
2083 const QRectF groupHeaderRect = m_layouter->groupHeaderRect(index);
2084 const QRectF itemRect = m_layouter->itemRect(index);
2085
2086 // The group-header is a child of the itemlist widget. Translate the
2087 // group header position to the relative position.
2088 if (scrollOrientation() == Qt::Vertical) {
2089 // In the vertical scroll orientation the group header should always span
2090 // the whole width no matter which temporary position the parent widget
2091 // has. In this case the x-position and width will be adjusted manually.
2092 const qreal x = -widget->x() - itemOffset();
2093 const qreal width = maximumItemOffset();
2094 groupHeader->setPos(x, -groupHeaderRect.height());
2095 groupHeader->resize(width, groupHeaderRect.size().height());
2096 } else {
2097 groupHeader->setPos(groupHeaderRect.x() - itemRect.x(), -widget->y());
2098 groupHeader->resize(groupHeaderRect.size());
2099 }
2100 }
2101
2102 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget* widget)
2103 {
2104 KItemListGroupHeader* header = m_visibleGroups.value(widget);
2105 if (header) {
2106 header->setParentItem(nullptr);
2107 groupHeaderCreator()->recycle(header);
2108 m_visibleGroups.remove(widget);
2109 disconnect(widget, &KItemListWidget::geometryChanged, this, &KItemListView::slotGeometryOfGroupHeaderParentChanged);
2110 }
2111 }
2112
2113 void KItemListView::updateVisibleGroupHeaders()
2114 {
2115 Q_ASSERT(m_grouped);
2116 m_layouter->markAsDirty();
2117
2118 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
2119 while (it.hasNext()) {
2120 it.next();
2121 updateGroupHeaderForWidget(it.value());
2122 }
2123 }
2124
2125 int KItemListView::groupIndexForItem(int index) const
2126 {
2127 Q_ASSERT(m_grouped);
2128
2129 const QList<QPair<int, QVariant> > groups = model()->groups();
2130 if (groups.isEmpty()) {
2131 return -1;
2132 }
2133
2134 int min = 0;
2135 int max = groups.count() - 1;
2136 int mid = 0;
2137 do {
2138 mid = (min + max) / 2;
2139 if (index > groups[mid].first) {
2140 min = mid + 1;
2141 } else {
2142 max = mid - 1;
2143 }
2144 } while (groups[mid].first != index && min <= max);
2145
2146 if (min > max) {
2147 while (groups[mid].first > index && mid > 0) {
2148 --mid;
2149 }
2150 }
2151
2152 return mid;
2153 }
2154
2155 void KItemListView::updateAlternateBackgrounds()
2156 {
2157 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
2158 while (it.hasNext()) {
2159 it.next();
2160 updateAlternateBackgroundForWidget(it.value());
2161 }
2162 }
2163
2164 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget* widget)
2165 {
2166 bool enabled = useAlternateBackgrounds();
2167 if (enabled) {
2168 const int index = widget->index();
2169 enabled = (index & 0x1) > 0;
2170 if (m_grouped) {
2171 const int groupIndex = groupIndexForItem(index);
2172 if (groupIndex >= 0) {
2173 const QList<QPair<int, QVariant> > groups = model()->groups();
2174 const int indexOfFirstGroupItem = groups[groupIndex].first;
2175 const int relativeIndex = index - indexOfFirstGroupItem;
2176 enabled = (relativeIndex & 0x1) > 0;
2177 }
2178 }
2179 }
2180 widget->setAlternateBackground(enabled);
2181 }
2182
2183 bool KItemListView::useAlternateBackgrounds() const
2184 {
2185 return m_itemSize.isEmpty() && m_visibleRoles.count() > 1;
2186 }
2187
2188 QHash<QByteArray, qreal> KItemListView::preferredColumnWidths(const KItemRangeList& itemRanges) const
2189 {
2190 QElapsedTimer timer;
2191 timer.start();
2192
2193 QHash<QByteArray, qreal> widths;
2194
2195 // Calculate the minimum width for each column that is required
2196 // to show the headline unclipped.
2197 const QFontMetricsF fontMetrics(m_headerWidget->font());
2198 const int gripMargin = m_headerWidget->style()->pixelMetric(QStyle::PM_HeaderGripMargin);
2199 const int headerMargin = m_headerWidget->style()->pixelMetric(QStyle::PM_HeaderMargin);
2200 foreach (const QByteArray& visibleRole, visibleRoles()) {
2201 const QString headerText = m_model->roleDescription(visibleRole);
2202 const qreal headerWidth = fontMetrics.width(headerText) + gripMargin + headerMargin * 2;
2203 widths.insert(visibleRole, headerWidth);
2204 }
2205
2206 // Calculate the preferred column withs for each item and ignore values
2207 // smaller than the width for showing the headline unclipped.
2208 const KItemListWidgetCreatorBase* creator = widgetCreator();
2209 int calculatedItemCount = 0;
2210 bool maxTimeExceeded = false;
2211 foreach (const KItemRange& itemRange, itemRanges) {
2212 const int startIndex = itemRange.index;
2213 const int endIndex = startIndex + itemRange.count - 1;
2214
2215 for (int i = startIndex; i <= endIndex; ++i) {
2216 foreach (const QByteArray& visibleRole, visibleRoles()) {
2217 qreal maxWidth = widths.value(visibleRole, 0);
2218 const qreal width = creator->preferredRoleColumnWidth(visibleRole, i, this);
2219 maxWidth = qMax(width, maxWidth);
2220 widths.insert(visibleRole, maxWidth);
2221 }
2222
2223 if (calculatedItemCount > 100 && timer.elapsed() > 200) {
2224 // When having several thousands of items calculating the sizes can get
2225 // very expensive. We accept a possibly too small role-size in favour
2226 // of having no blocking user interface.
2227 maxTimeExceeded = true;
2228 break;
2229 }
2230 ++calculatedItemCount;
2231 }
2232 if (maxTimeExceeded) {
2233 break;
2234 }
2235 }
2236
2237 return widths;
2238 }
2239
2240 void KItemListView::applyColumnWidthsFromHeader()
2241 {
2242 // Apply the new size to the layouter
2243 const qreal requiredWidth = columnWidthsSum();
2244 const QSizeF dynamicItemSize(qMax(size().width(), requiredWidth),
2245 m_itemSize.height());
2246 m_layouter->setItemSize(dynamicItemSize);
2247
2248 // Update the role sizes for all visible widgets
2249 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
2250 while (it.hasNext()) {
2251 it.next();
2252 updateWidgetColumnWidths(it.value());
2253 }
2254 }
2255
2256 void KItemListView::updateWidgetColumnWidths(KItemListWidget* widget)
2257 {
2258 foreach (const QByteArray& role, m_visibleRoles) {
2259 widget->setColumnWidth(role, m_headerWidget->columnWidth(role));
2260 }
2261 }
2262
2263 void KItemListView::updatePreferredColumnWidths(const KItemRangeList& itemRanges)
2264 {
2265 Q_ASSERT(m_itemSize.isEmpty());
2266 const int itemCount = m_model->count();
2267 int rangesItemCount = 0;
2268 foreach (const KItemRange& range, itemRanges) {
2269 rangesItemCount += range.count;
2270 }
2271
2272 if (itemCount == rangesItemCount) {
2273 const QHash<QByteArray, qreal> preferredWidths = preferredColumnWidths(itemRanges);
2274 foreach (const QByteArray& role, m_visibleRoles) {
2275 m_headerWidget->setPreferredColumnWidth(role, preferredWidths.value(role));
2276 }
2277 } else {
2278 // Only a sub range of the roles need to be determined.
2279 // The chances are good that the widths of the sub ranges
2280 // already fit into the available widths and hence no
2281 // expensive update might be required.
2282 bool changed = false;
2283
2284 const QHash<QByteArray, qreal> updatedWidths = preferredColumnWidths(itemRanges);
2285 QHashIterator<QByteArray, qreal> it(updatedWidths);
2286 while (it.hasNext()) {
2287 it.next();
2288 const QByteArray& role = it.key();
2289 const qreal updatedWidth = it.value();
2290 const qreal currentWidth = m_headerWidget->preferredColumnWidth(role);
2291 if (updatedWidth > currentWidth) {
2292 m_headerWidget->setPreferredColumnWidth(role, updatedWidth);
2293 changed = true;
2294 }
2295 }
2296
2297 if (!changed) {
2298 // All the updated sizes are smaller than the current sizes and no change
2299 // of the stretched roles-widths is required
2300 return;
2301 }
2302 }
2303
2304 if (m_headerWidget->automaticColumnResizing()) {
2305 applyAutomaticColumnWidths();
2306 }
2307 }
2308
2309 void KItemListView::updatePreferredColumnWidths()
2310 {
2311 if (m_model) {
2312 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, m_model->count()));
2313 }
2314 }
2315
2316 void KItemListView::applyAutomaticColumnWidths()
2317 {
2318 Q_ASSERT(m_itemSize.isEmpty());
2319 Q_ASSERT(m_headerWidget->automaticColumnResizing());
2320 if (m_visibleRoles.isEmpty()) {
2321 return;
2322 }
2323
2324 // Calculate the maximum size of an item by considering the
2325 // visible role sizes and apply them to the layouter. If the
2326 // size does not use the available view-size the size of the
2327 // first role will get stretched.
2328
2329 foreach (const QByteArray& role, m_visibleRoles) {
2330 const qreal preferredWidth = m_headerWidget->preferredColumnWidth(role);
2331 m_headerWidget->setColumnWidth(role, preferredWidth);
2332 }
2333
2334 const QByteArray firstRole = m_visibleRoles.first();
2335 qreal firstColumnWidth = m_headerWidget->columnWidth(firstRole);
2336 QSizeF dynamicItemSize = m_itemSize;
2337
2338 qreal requiredWidth = columnWidthsSum();
2339 const qreal availableWidth = size().width();
2340 if (requiredWidth < availableWidth) {
2341 // Stretch the first column to use the whole remaining width
2342 firstColumnWidth += availableWidth - requiredWidth;
2343 m_headerWidget->setColumnWidth(firstRole, firstColumnWidth);
2344 } else if (requiredWidth > availableWidth && m_visibleRoles.count() > 1) {
2345 // Shrink the first column to be able to show as much other
2346 // columns as possible
2347 qreal shrinkedFirstColumnWidth = firstColumnWidth - requiredWidth + availableWidth;
2348
2349 // TODO: A proper calculation of the minimum width depends on the implementation
2350 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2351 // later.
2352 const qreal minWidth = qMin(firstColumnWidth, qreal(m_styleOption.iconSize * 2 + 200));
2353 if (shrinkedFirstColumnWidth < minWidth) {
2354 shrinkedFirstColumnWidth = minWidth;
2355 }
2356
2357 m_headerWidget->setColumnWidth(firstRole, shrinkedFirstColumnWidth);
2358 requiredWidth -= firstColumnWidth - shrinkedFirstColumnWidth;
2359 }
2360
2361 dynamicItemSize.rwidth() = qMax(requiredWidth, availableWidth);
2362
2363 m_layouter->setItemSize(dynamicItemSize);
2364
2365 // Update the role sizes for all visible widgets
2366 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
2367 while (it.hasNext()) {
2368 it.next();
2369 updateWidgetColumnWidths(it.value());
2370 }
2371 }
2372
2373 qreal KItemListView::columnWidthsSum() const
2374 {
2375 qreal widthsSum = 0;
2376 foreach (const QByteArray& role, m_visibleRoles) {
2377 widthsSum += m_headerWidget->columnWidth(role);
2378 }
2379 return widthsSum;
2380 }
2381
2382 QRectF KItemListView::headerBoundaries() const
2383 {
2384 return m_headerWidget->isVisible() ? m_headerWidget->geometry() : QRectF();
2385 }
2386
2387 bool KItemListView::changesItemGridLayout(const QSizeF& newGridSize,
2388 const QSizeF& newItemSize,
2389 const QSizeF& newItemMargin) const
2390 {
2391 if (newItemSize.isEmpty() || newGridSize.isEmpty()) {
2392 return false;
2393 }
2394
2395 if (m_layouter->scrollOrientation() == Qt::Vertical) {
2396 const qreal itemWidth = m_layouter->itemSize().width();
2397 if (itemWidth > 0) {
2398 const int newColumnCount = itemsPerSize(newGridSize.width(),
2399 newItemSize.width(),
2400 newItemMargin.width());
2401 if (m_model->count() > newColumnCount) {
2402 const int oldColumnCount = itemsPerSize(m_layouter->size().width(),
2403 itemWidth,
2404 m_layouter->itemMargin().width());
2405 return oldColumnCount != newColumnCount;
2406 }
2407 }
2408 } else {
2409 const qreal itemHeight = m_layouter->itemSize().height();
2410 if (itemHeight > 0) {
2411 const int newRowCount = itemsPerSize(newGridSize.height(),
2412 newItemSize.height(),
2413 newItemMargin.height());
2414 if (m_model->count() > newRowCount) {
2415 const int oldRowCount = itemsPerSize(m_layouter->size().height(),
2416 itemHeight,
2417 m_layouter->itemMargin().height());
2418 return oldRowCount != newRowCount;
2419 }
2420 }
2421 }
2422
2423 return false;
2424 }
2425
2426 bool KItemListView::animateChangedItemCount(int changedItemCount) const
2427 {
2428 if (m_itemSize.isEmpty()) {
2429 // We have only columns or only rows, but no grid: An animation is usually
2430 // welcome when inserting or removing items.
2431 return !supportsItemExpanding();
2432 }
2433
2434 if (m_layouter->size().isEmpty() || m_layouter->itemSize().isEmpty()) {
2435 return false;
2436 }
2437
2438 const int maximum = (scrollOrientation() == Qt::Vertical)
2439 ? m_layouter->size().width() / m_layouter->itemSize().width()
2440 : m_layouter->size().height() / m_layouter->itemSize().height();
2441 // Only animate if up to 2/3 of a row or column are inserted or removed
2442 return changedItemCount <= maximum * 2 / 3;
2443 }
2444
2445
2446 bool KItemListView::scrollBarRequired(const QSizeF& size) const
2447 {
2448 const QSizeF oldSize = m_layouter->size();
2449
2450 m_layouter->setSize(size);
2451 const qreal maxOffset = m_layouter->maximumScrollOffset();
2452 m_layouter->setSize(oldSize);
2453
2454 return m_layouter->scrollOrientation() == Qt::Vertical ? maxOffset > size.height()
2455 : maxOffset > size.width();
2456 }
2457
2458 int KItemListView::showDropIndicator(const QPointF& pos)
2459 {
2460 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
2461 while (it.hasNext()) {
2462 it.next();
2463 const KItemListWidget* widget = it.value();
2464
2465 const QPointF mappedPos = widget->mapFromItem(this, pos);
2466 const QRectF rect = itemRect(widget->index());
2467 if (mappedPos.y() >= 0 && mappedPos.y() <= rect.height()) {
2468 if (m_model->supportsDropping(widget->index())) {
2469 // Keep 30% of the rectangle as the gap instead of always having a fixed gap
2470 const int gap = qMax(qreal(4.0), qreal(0.3) * rect.height());
2471 if (mappedPos.y() >= gap && mappedPos.y() <= rect.height() - gap) {
2472 return -1;
2473 }
2474 }
2475
2476 const bool isAboveItem = (mappedPos.y () < rect.height() / 2);
2477 const qreal y = isAboveItem ? rect.top() : rect.bottom();
2478
2479 const QRectF draggingInsertIndicator(rect.left(), y, rect.width(), 1);
2480 if (m_dropIndicator != draggingInsertIndicator) {
2481 m_dropIndicator = draggingInsertIndicator;
2482 update();
2483 }
2484
2485 int index = widget->index();
2486 if (!isAboveItem) {
2487 ++index;
2488 }
2489 return index;
2490 }
2491 }
2492
2493 const QRectF firstItemRect = itemRect(firstVisibleIndex());
2494 return (pos.y() <= firstItemRect.top()) ? 0 : -1;
2495 }
2496
2497 void KItemListView::hideDropIndicator()
2498 {
2499 if (!m_dropIndicator.isNull()) {
2500 m_dropIndicator = QRectF();
2501 update();
2502 }
2503 }
2504
2505 void KItemListView::updateGroupHeaderHeight()
2506 {
2507 qreal groupHeaderHeight = m_styleOption.fontMetrics.height();
2508 qreal groupHeaderMargin = 0;
2509
2510 if (scrollOrientation() == Qt::Horizontal) {
2511 // The vertical margin above and below the header should be
2512 // equal to the horizontal margin, not the vertical margin
2513 // from m_styleOption.
2514 groupHeaderHeight += 2 * m_styleOption.horizontalMargin;
2515 groupHeaderMargin = m_styleOption.horizontalMargin;
2516 } else if (m_itemSize.isEmpty()){
2517 groupHeaderHeight += 4 * m_styleOption.padding;
2518 groupHeaderMargin = m_styleOption.iconSize / 2;
2519 } else {
2520 groupHeaderHeight += 2 * m_styleOption.padding + m_styleOption.verticalMargin;
2521 groupHeaderMargin = m_styleOption.iconSize / 4;
2522 }
2523 m_layouter->setGroupHeaderHeight(groupHeaderHeight);
2524 m_layouter->setGroupHeaderMargin(groupHeaderMargin);
2525
2526 updateVisibleGroupHeaders();
2527 }
2528
2529 void KItemListView::updateSiblingsInformation(int firstIndex, int lastIndex)
2530 {
2531 if (!supportsItemExpanding() || !m_model) {
2532 return;
2533 }
2534
2535 if (firstIndex < 0 || lastIndex < 0) {
2536 firstIndex = m_layouter->firstVisibleIndex();
2537 lastIndex = m_layouter->lastVisibleIndex();
2538 } else {
2539 const bool isRangeVisible = (firstIndex <= m_layouter->lastVisibleIndex() &&
2540 lastIndex >= m_layouter->firstVisibleIndex());
2541 if (!isRangeVisible) {
2542 return;
2543 }
2544 }
2545
2546 int previousParents = 0;
2547 QBitArray previousSiblings;
2548
2549 // The rootIndex describes the first index where the siblings get
2550 // calculated from. For the calculation the upper most parent item
2551 // is required. For performance reasons it is checked first whether
2552 // the visible items before or after the current range already
2553 // contain a siblings information which can be used as base.
2554 int rootIndex = firstIndex;
2555
2556 KItemListWidget* widget = m_visibleItems.value(firstIndex - 1);
2557 if (!widget) {
2558 // There is no visible widget before the range, check whether there
2559 // is one after the range:
2560 widget = m_visibleItems.value(lastIndex + 1);
2561 if (widget) {
2562 // The sibling information of the widget may only be used if
2563 // all items of the range have the same number of parents.
2564 const int parents = m_model->expandedParentsCount(lastIndex + 1);
2565 for (int i = lastIndex; i >= firstIndex; --i) {
2566 if (m_model->expandedParentsCount(i) != parents) {
2567 widget = nullptr;
2568 break;
2569 }
2570 }
2571 }
2572 }
2573
2574 if (widget) {
2575 // Performance optimization: Use the sibling information of the visible
2576 // widget beside the given range.
2577 previousSiblings = widget->siblingsInformation();
2578 if (previousSiblings.isEmpty()) {
2579 return;
2580 }
2581 previousParents = previousSiblings.count() - 1;
2582 previousSiblings.truncate(previousParents);
2583 } else {
2584 // Potentially slow path: Go back to the upper most parent of firstIndex
2585 // to be able to calculate the initial value for the siblings.
2586 while (rootIndex > 0 && m_model->expandedParentsCount(rootIndex) > 0) {
2587 --rootIndex;
2588 }
2589 }
2590
2591 Q_ASSERT(previousParents >= 0);
2592 for (int i = rootIndex; i <= lastIndex; ++i) {
2593 // Update the parent-siblings in case if the current item represents
2594 // a child or an upper parent.
2595 const int currentParents = m_model->expandedParentsCount(i);
2596 Q_ASSERT(currentParents >= 0);
2597 if (previousParents < currentParents) {
2598 previousParents = currentParents;
2599 previousSiblings.resize(currentParents);
2600 previousSiblings.setBit(currentParents - 1, hasSiblingSuccessor(i - 1));
2601 } else if (previousParents > currentParents) {
2602 previousParents = currentParents;
2603 previousSiblings.truncate(currentParents);
2604 }
2605
2606 if (i >= firstIndex) {
2607 // The index represents a visible item. Apply the parent-siblings
2608 // and update the sibling of the current item.
2609 KItemListWidget* widget = m_visibleItems.value(i);
2610 if (!widget) {
2611 continue;
2612 }
2613
2614 QBitArray siblings = previousSiblings;
2615 siblings.resize(siblings.count() + 1);
2616 siblings.setBit(siblings.count() - 1, hasSiblingSuccessor(i));
2617
2618 widget->setSiblingsInformation(siblings);
2619 }
2620 }
2621 }
2622
2623 bool KItemListView::hasSiblingSuccessor(int index) const
2624 {
2625 bool hasSuccessor = false;
2626 const int parentsCount = m_model->expandedParentsCount(index);
2627 int successorIndex = index + 1;
2628
2629 // Search the next sibling
2630 const int itemCount = m_model->count();
2631 while (successorIndex < itemCount) {
2632 const int currentParentsCount = m_model->expandedParentsCount(successorIndex);
2633 if (currentParentsCount == parentsCount) {
2634 hasSuccessor = true;
2635 break;
2636 } else if (currentParentsCount < parentsCount) {
2637 break;
2638 }
2639 ++successorIndex;
2640 }
2641
2642 if (m_grouped && hasSuccessor) {
2643 // If the sibling is part of another group, don't mark it as
2644 // successor as the group header is between the sibling connections.
2645 for (int i = index + 1; i <= successorIndex; ++i) {
2646 if (m_layouter->isFirstGroupItem(i)) {
2647 hasSuccessor = false;
2648 break;
2649 }
2650 }
2651 }
2652
2653 return hasSuccessor;
2654 }
2655
2656 void KItemListView::disconnectRoleEditingSignals(int index)
2657 {
2658 KStandardItemListWidget* widget = qobject_cast<KStandardItemListWidget *>(m_visibleItems.value(index));
2659 if (!widget) {
2660 return;
2661 }
2662
2663 disconnect(widget, &KItemListWidget::roleEditingCanceled, this, nullptr);
2664 disconnect(widget, &KItemListWidget::roleEditingFinished, this, nullptr);
2665 disconnect(this, &KItemListView::scrollOffsetChanged, widget, nullptr);
2666 }
2667
2668 int KItemListView::calculateAutoScrollingIncrement(int pos, int range, int oldInc)
2669 {
2670 int inc = 0;
2671
2672 const int minSpeed = 4;
2673 const int maxSpeed = 128;
2674 const int speedLimiter = 96;
2675 const int autoScrollBorder = 64;
2676
2677 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2678 // This assures that the autoscrolling speed grows gradually.
2679 const int incLimiter = 1;
2680
2681 if (pos < autoScrollBorder) {
2682 inc = -minSpeed + qAbs(pos - autoScrollBorder) * (pos - autoScrollBorder) / speedLimiter;
2683 inc = qMax(inc, -maxSpeed);
2684 inc = qMax(inc, oldInc - incLimiter);
2685 } else if (pos > range - autoScrollBorder) {
2686 inc = minSpeed + qAbs(pos - range + autoScrollBorder) * (pos - range + autoScrollBorder) / speedLimiter;
2687 inc = qMin(inc, maxSpeed);
2688 inc = qMin(inc, oldInc + incLimiter);
2689 }
2690
2691 return inc;
2692 }
2693
2694 int KItemListView::itemsPerSize(qreal size, qreal itemSize, qreal itemMargin)
2695 {
2696 const qreal availableSize = size - itemMargin;
2697 const int count = availableSize / (itemSize + itemMargin);
2698 return count;
2699 }
2700
2701
2702
2703 KItemListCreatorBase::~KItemListCreatorBase()
2704 {
2705 qDeleteAll(m_recycleableWidgets);
2706 qDeleteAll(m_createdWidgets);
2707 }
2708
2709 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget* widget)
2710 {
2711 m_createdWidgets.insert(widget);
2712 }
2713
2714 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget* widget)
2715 {
2716 Q_ASSERT(m_createdWidgets.contains(widget));
2717 m_createdWidgets.remove(widget);
2718
2719 if (m_recycleableWidgets.count() < 100) {
2720 m_recycleableWidgets.append(widget);
2721 widget->setVisible(false);
2722 } else {
2723 delete widget;
2724 }
2725 }
2726
2727 QGraphicsWidget* KItemListCreatorBase::popRecycleableWidget()
2728 {
2729 if (m_recycleableWidgets.isEmpty()) {
2730 return nullptr;
2731 }
2732
2733 QGraphicsWidget* widget = m_recycleableWidgets.takeLast();
2734 m_createdWidgets.insert(widget);
2735 return widget;
2736 }
2737
2738 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2739 {
2740 }
2741
2742 void KItemListWidgetCreatorBase::recycle(KItemListWidget* widget)
2743 {
2744 widget->setParentItem(nullptr);
2745 widget->setOpacity(1.0);
2746 pushRecycleableWidget(widget);
2747 }
2748
2749 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2750 {
2751 }
2752
2753 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader* header)
2754 {
2755 header->setOpacity(1.0);
2756 pushRecycleableWidget(header);
2757 }
2758