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