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