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