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