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