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