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