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