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