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