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