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