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