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