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