]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kitemlistview.cpp
Internal interface cleanup
[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->setPos(-offset, 0);
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 if (m_headerWidget->automaticColumnResizing()) {
422 applyAutomaticColumnWidths();
423 } else {
424 const qreal requiredWidth = columnWidthsSum();
425 const QSizeF dynamicItemSize(qMax(newSize.width(), requiredWidth),
426 m_itemSize.height());
427 m_layouter->setItemSize(dynamicItemSize);
428 m_headerWidget->resize(dynamicItemSize.width(), m_headerWidget->size().height());
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 Q_UNUSED(index);
514 return itemSize();
515 }
516
517 qreal KItemListView::preferredColumnWidth(int index, const QByteArray& role) const
518 {
519 Q_UNUSED(index);
520 Q_UNUSED(role);
521 return 100;
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 m_headerWidget->setPos(0, 0);
619 m_headerWidget->setModel(m_model);
620 m_headerWidget->setColumns(m_visibleRoles);
621 m_headerWidget->setZValue(1);
622
623 connect(m_headerWidget, SIGNAL(columnWidthChanged(QByteArray,qreal,qreal)),
624 this, SLOT(slotHeaderColumnWidthChanged(QByteArray,qreal,qreal)));
625 connect(m_headerWidget, SIGNAL(columnMoved(QByteArray,int,int)),
626 this, SLOT(slotHeaderColumnMoved(QByteArray,int,int)));
627 connect(m_headerWidget, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)),
628 this, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)));
629 connect(m_headerWidget, SIGNAL(sortRoleChanged(QByteArray,QByteArray)),
630 this, SIGNAL(sortRoleChanged(QByteArray,QByteArray)));
631
632 m_layouter->setHeaderHeight(m_headerWidget->size().height());
633 m_headerWidget->setVisible(true);
634 } else if (!visible && m_headerWidget->isVisible()) {
635 disconnect(m_headerWidget, SIGNAL(columnWidthChanged(QByteArray,qreal,qreal)),
636 this, SLOT(slotHeaderColumnWidthChanged(QByteArray,qreal,qreal)));
637 disconnect(m_headerWidget, SIGNAL(columnMoved(QByteArray,int,int)),
638 this, SLOT(slotHeaderColumnMoved(QByteArray,int,int)));
639 disconnect(m_headerWidget, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)),
640 this, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)));
641 disconnect(m_headerWidget, SIGNAL(sortRoleChanged(QByteArray,QByteArray)),
642 this, SIGNAL(sortRoleChanged(QByteArray,QByteArray)));
643
644 m_layouter->setHeaderHeight(0);
645 m_headerWidget->setVisible(false);
646 }
647 }
648
649 bool KItemListView::isHeaderVisible() const
650 {
651 return m_headerWidget->isVisible();
652 }
653
654 KItemListHeader* KItemListView::header() const
655 {
656 return m_header;
657 }
658
659 QPixmap KItemListView::createDragPixmap(const QSet<int>& indexes) const
660 {
661 Q_UNUSED(indexes);
662 return QPixmap();
663 }
664
665 void KItemListView::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
666 {
667 QGraphicsWidget::paint(painter, option, widget);
668
669 if (m_rubberBand->isActive()) {
670 QRectF rubberBandRect = QRectF(m_rubberBand->startPosition(),
671 m_rubberBand->endPosition()).normalized();
672
673 const QPointF topLeft = rubberBandRect.topLeft();
674 if (scrollOrientation() == Qt::Vertical) {
675 rubberBandRect.moveTo(topLeft.x(), topLeft.y() - scrollOffset());
676 } else {
677 rubberBandRect.moveTo(topLeft.x() - scrollOffset(), topLeft.y());
678 }
679
680 QStyleOptionRubberBand opt;
681 opt.initFrom(widget);
682 opt.shape = QRubberBand::Rectangle;
683 opt.opaque = false;
684 opt.rect = rubberBandRect.toRect();
685 style()->drawControl(QStyle::CE_RubberBand, &opt, painter);
686 }
687 }
688
689 void KItemListView::initializeItemListWidget(KItemListWidget* item)
690 {
691 Q_UNUSED(item);
692 }
693
694 bool KItemListView::itemSizeHintUpdateRequired(const QSet<QByteArray>& changedRoles) const
695 {
696 Q_UNUSED(changedRoles);
697 return true;
698 }
699
700 void KItemListView::onControllerChanged(KItemListController* current, KItemListController* previous)
701 {
702 Q_UNUSED(current);
703 Q_UNUSED(previous);
704 }
705
706 void KItemListView::onModelChanged(KItemModelBase* current, KItemModelBase* previous)
707 {
708 Q_UNUSED(current);
709 Q_UNUSED(previous);
710 }
711
712 void KItemListView::onScrollOrientationChanged(Qt::Orientation current, Qt::Orientation previous)
713 {
714 Q_UNUSED(current);
715 Q_UNUSED(previous);
716 }
717
718 void KItemListView::onItemSizeChanged(const QSizeF& current, const QSizeF& previous)
719 {
720 Q_UNUSED(current);
721 Q_UNUSED(previous);
722 }
723
724 void KItemListView::onScrollOffsetChanged(qreal current, qreal previous)
725 {
726 Q_UNUSED(current);
727 Q_UNUSED(previous);
728 }
729
730 void KItemListView::onVisibleRolesChanged(const QList<QByteArray>& current, const QList<QByteArray>& previous)
731 {
732 Q_UNUSED(current);
733 Q_UNUSED(previous);
734 }
735
736 void KItemListView::onStyleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous)
737 {
738 Q_UNUSED(current);
739 Q_UNUSED(previous);
740 }
741
742 void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding)
743 {
744 Q_UNUSED(supportsExpanding);
745 }
746
747 void KItemListView::onTransactionBegin()
748 {
749 }
750
751 void KItemListView::onTransactionEnd()
752 {
753 }
754
755 bool KItemListView::event(QEvent* event)
756 {
757 // Forward all events to the controller and handle them there
758 if (m_controller && m_controller->processEvent(event, transform())) {
759 event->accept();
760 return true;
761 }
762 return QGraphicsWidget::event(event);
763 }
764
765 void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent* event)
766 {
767 m_mousePos = transform().map(event->pos());
768 event->accept();
769 }
770
771 void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
772 {
773 QGraphicsWidget::mouseMoveEvent(event);
774
775 m_mousePos = transform().map(event->pos());
776 if (m_autoScrollTimer && !m_autoScrollTimer->isActive()) {
777 m_autoScrollTimer->start(InitialAutoScrollDelay);
778 }
779 }
780
781 void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent* event)
782 {
783 event->setAccepted(true);
784 setAutoScroll(true);
785 }
786
787 void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent *event)
788 {
789 QGraphicsWidget::dragMoveEvent(event);
790
791 m_mousePos = transform().map(event->pos());
792 if (m_autoScrollTimer && !m_autoScrollTimer->isActive()) {
793 m_autoScrollTimer->start(InitialAutoScrollDelay);
794 }
795 }
796
797 void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
798 {
799 QGraphicsWidget::dragLeaveEvent(event);
800 setAutoScroll(false);
801 }
802
803 void KItemListView::dropEvent(QGraphicsSceneDragDropEvent* event)
804 {
805 QGraphicsWidget::dropEvent(event);
806 setAutoScroll(false);
807 }
808
809 QList<KItemListWidget*> KItemListView::visibleItemListWidgets() const
810 {
811 return m_visibleItems.values();
812 }
813
814 void KItemListView::slotItemsInserted(const KItemRangeList& itemRanges)
815 {
816 if (m_itemSize.isEmpty()) {
817 updatePreferredColumnWidths(itemRanges);
818 }
819
820 const bool hasMultipleRanges = (itemRanges.count() > 1);
821 if (hasMultipleRanges) {
822 beginTransaction();
823 }
824
825 m_layouter->markAsDirty();
826
827 int previouslyInsertedCount = 0;
828 foreach (const KItemRange& range, itemRanges) {
829 // range.index is related to the model before anything has been inserted.
830 // As in each loop the current item-range gets inserted the index must
831 // be increased by the already previously inserted items.
832 const int index = range.index + previouslyInsertedCount;
833 const int count = range.count;
834 if (index < 0 || count <= 0) {
835 kWarning() << "Invalid item range (index:" << index << ", count:" << count << ")";
836 continue;
837 }
838 previouslyInsertedCount += count;
839
840 m_sizeHintResolver->itemsInserted(index, count);
841
842 // Determine which visible items must be moved
843 QList<int> itemsToMove;
844 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
845 while (it.hasNext()) {
846 it.next();
847 const int visibleItemIndex = it.key();
848 if (visibleItemIndex >= index) {
849 itemsToMove.append(visibleItemIndex);
850 }
851 }
852
853 // Update the indexes of all KItemListWidget instances that are located
854 // after the inserted items. It is important to adjust the indexes in the order
855 // from the highest index to the lowest index to prevent overlaps when setting the new index.
856 qSort(itemsToMove);
857 for (int i = itemsToMove.count() - 1; i >= 0; --i) {
858 KItemListWidget* widget = m_visibleItems.value(itemsToMove[i]);
859 Q_ASSERT(widget);
860 const int newIndex = widget->index() + count;
861 if (hasMultipleRanges) {
862 setWidgetIndex(widget, newIndex);
863 } else {
864 // Try to animate the moving of the item
865 moveWidgetToIndex(widget, newIndex);
866 }
867 }
868
869 if (m_model->count() == count && m_activeTransactions == 0) {
870 // Check whether a scrollbar is required to show the inserted items. In this case
871 // the size of the layouter will be decreased before calling doLayout(): This prevents
872 // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
873 const bool verticalScrollOrientation = (scrollOrientation() == Qt::Vertical);
874 const bool decreaseLayouterSize = ( verticalScrollOrientation && maximumScrollOffset() > size().height()) ||
875 (!verticalScrollOrientation && maximumScrollOffset() > size().width());
876 if (decreaseLayouterSize) {
877 const int scrollBarExtent = style()->pixelMetric(QStyle::PM_ScrollBarExtent);
878 QSizeF layouterSize = m_layouter->size();
879 if (verticalScrollOrientation) {
880 layouterSize.rwidth() -= scrollBarExtent;
881 } else {
882 layouterSize.rheight() -= scrollBarExtent;
883 }
884 m_layouter->setSize(layouterSize);
885 }
886 }
887
888 if (!hasMultipleRanges) {
889 doLayout(animateChangedItemCount(count) ? Animation : NoAnimation, index, count);
890 updateSiblingsInformation();
891 }
892 }
893
894 if (m_controller) {
895 m_controller->selectionManager()->itemsInserted(itemRanges);
896 }
897
898 if (hasMultipleRanges) {
899 #ifndef QT_NO_DEBUG
900 // Important: Don't read any m_layouter-property inside the for-loop in case if
901 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
902 // updated in each loop-cycle and has only a consistent state after the loop.
903 Q_ASSERT(m_layouter->isDirty());
904 #endif
905 m_endTransactionAnimationHint = NoAnimation;
906 endTransaction();
907 updateSiblingsInformation();
908 }
909
910 if (useAlternateBackgrounds()) {
911 updateAlternateBackgrounds();
912 }
913 }
914
915 void KItemListView::slotItemsRemoved(const KItemRangeList& itemRanges)
916 {
917 if (m_itemSize.isEmpty()) {
918 // Don't pass the item-range: The preferred column-widths of
919 // all items must be adjusted when removing items.
920 updatePreferredColumnWidths();
921 }
922
923 const bool hasMultipleRanges = (itemRanges.count() > 1);
924 if (hasMultipleRanges) {
925 beginTransaction();
926 }
927
928 m_layouter->markAsDirty();
929
930 for (int i = itemRanges.count() - 1; i >= 0; --i) {
931 const KItemRange& range = itemRanges.at(i);
932 const int index = range.index;
933 const int count = range.count;
934 if (index < 0 || count <= 0) {
935 kWarning() << "Invalid item range (index:" << index << ", count:" << count << ")";
936 continue;
937 }
938
939 m_sizeHintResolver->itemsRemoved(index, count);
940
941 const int firstRemovedIndex = index;
942 const int lastRemovedIndex = index + count - 1;
943 const int lastIndex = m_model->count() + count - 1;
944
945 // Remove all KItemListWidget instances that got deleted
946 for (int i = firstRemovedIndex; i <= lastRemovedIndex; ++i) {
947 KItemListWidget* widget = m_visibleItems.value(i);
948 if (!widget) {
949 continue;
950 }
951
952 m_animation->stop(widget);
953 // Stopping the animation might lead to recycling the widget if
954 // it is invisible (see slotAnimationFinished()).
955 // Check again whether it is still visible:
956 if (!m_visibleItems.contains(i)) {
957 continue;
958 }
959
960 if (m_model->count() == 0 || hasMultipleRanges || !animateChangedItemCount(count)) {
961 // Remove the widget without animation
962 recycleWidget(widget);
963 } else {
964 // Animate the removing of the items. Special case: When removing an item there
965 // is no valid model index available anymore. For the
966 // remove-animation the item gets removed from m_visibleItems but the widget
967 // will stay alive until the animation has been finished and will
968 // be recycled (deleted) in KItemListView::slotAnimationFinished().
969 m_visibleItems.remove(i);
970 widget->setIndex(-1);
971 m_animation->start(widget, KItemListViewAnimation::DeleteAnimation);
972 }
973 }
974
975 // Update the indexes of all KItemListWidget instances that are located
976 // after the deleted items
977 for (int i = lastRemovedIndex + 1; i <= lastIndex; ++i) {
978 KItemListWidget* widget = m_visibleItems.value(i);
979 if (widget) {
980 const int newIndex = i - count;
981 if (hasMultipleRanges) {
982 setWidgetIndex(widget, newIndex);
983 } else {
984 // Try to animate the moving of the item
985 moveWidgetToIndex(widget, newIndex);
986 }
987 }
988 }
989
990 if (!hasMultipleRanges) {
991 // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
992 // assumes an updated geometry. If items are removed during an active transaction,
993 // the transaction will be temporary deactivated so that doLayout() triggers a
994 // geometry update if necessary.
995 const int activeTransactions = m_activeTransactions;
996 m_activeTransactions = 0;
997 doLayout(animateChangedItemCount(count) ? Animation : NoAnimation, index, -count);
998 m_activeTransactions = activeTransactions;
999 updateSiblingsInformation();
1000 }
1001 }
1002
1003 if (m_controller) {
1004 m_controller->selectionManager()->itemsRemoved(itemRanges);
1005 }
1006
1007 if (hasMultipleRanges) {
1008 #ifndef QT_NO_DEBUG
1009 // Important: Don't read any m_layouter-property inside the for-loop in case if
1010 // multiple ranges are given! m_layouter accesses m_sizeHintResolver which is
1011 // updated in each loop-cycle and has only a consistent state after the loop.
1012 Q_ASSERT(m_layouter->isDirty());
1013 #endif
1014 m_endTransactionAnimationHint = NoAnimation;
1015 endTransaction();
1016 updateSiblingsInformation();
1017 }
1018
1019 if (useAlternateBackgrounds()) {
1020 updateAlternateBackgrounds();
1021 }
1022 }
1023
1024 void KItemListView::slotItemsMoved(const KItemRange& itemRange, const QList<int>& movedToIndexes)
1025 {
1026 m_sizeHintResolver->itemsMoved(itemRange.index, itemRange.count);
1027 m_layouter->markAsDirty();
1028
1029 if (m_controller) {
1030 m_controller->selectionManager()->itemsMoved(itemRange, movedToIndexes);
1031 }
1032
1033 const int firstVisibleMovedIndex = qMax(firstVisibleIndex(), itemRange.index);
1034 const int lastVisibleMovedIndex = qMin(lastVisibleIndex(), itemRange.index + itemRange.count - 1);
1035
1036 for (int index = firstVisibleMovedIndex; index <= lastVisibleMovedIndex; ++index) {
1037 KItemListWidget* widget = m_visibleItems.value(index);
1038 if (widget) {
1039 updateWidgetProperties(widget, index);
1040 initializeItemListWidget(widget);
1041 }
1042 }
1043
1044 doLayout(NoAnimation);
1045 updateSiblingsInformation();
1046 }
1047
1048 void KItemListView::slotItemsChanged(const KItemRangeList& itemRanges,
1049 const QSet<QByteArray>& roles)
1050 {
1051 const bool updateSizeHints = itemSizeHintUpdateRequired(roles);
1052 if (updateSizeHints && m_itemSize.isEmpty()) {
1053 updatePreferredColumnWidths(itemRanges);
1054 }
1055
1056 foreach (const KItemRange& itemRange, itemRanges) {
1057 const int index = itemRange.index;
1058 const int count = itemRange.count;
1059
1060 if (updateSizeHints) {
1061 m_sizeHintResolver->itemsChanged(index, count, roles);
1062 m_layouter->markAsDirty();
1063
1064 if (!m_layoutTimer->isActive()) {
1065 m_layoutTimer->start();
1066 }
1067 }
1068
1069 // Apply the changed roles to the visible item-widgets
1070 const int lastIndex = index + count - 1;
1071 for (int i = index; i <= lastIndex; ++i) {
1072 KItemListWidget* widget = m_visibleItems.value(i);
1073 if (widget) {
1074 widget->setData(m_model->data(i), roles);
1075 }
1076 }
1077
1078 if (m_grouped && roles.contains(m_model->sortRole())) {
1079 // The sort-role has been changed which might result
1080 // in modified group headers
1081 updateVisibleGroupHeaders();
1082 doLayout(NoAnimation);
1083 }
1084 }
1085 }
1086
1087 void KItemListView::slotGroupedSortingChanged(bool current)
1088 {
1089 m_grouped = current;
1090 m_layouter->markAsDirty();
1091
1092 if (m_grouped) {
1093 updateGroupHeaderHeight();
1094 } else {
1095 // Clear all visible headers
1096 QMutableHashIterator<KItemListWidget*, KItemListGroupHeader*> it (m_visibleGroups);
1097 while (it.hasNext()) {
1098 it.next();
1099 recycleGroupHeaderForWidget(it.key());
1100 }
1101 Q_ASSERT(m_visibleGroups.isEmpty());
1102 }
1103
1104 if (useAlternateBackgrounds()) {
1105 // Changing the group mode requires to update the alternate backgrounds
1106 // as with the enabled group mode the altering is done on base of the first
1107 // group item.
1108 updateAlternateBackgrounds();
1109 }
1110 updateSiblingsInformation();
1111 doLayout(NoAnimation);
1112 }
1113
1114 void KItemListView::slotSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous)
1115 {
1116 Q_UNUSED(current);
1117 Q_UNUSED(previous);
1118 if (m_grouped) {
1119 updateVisibleGroupHeaders();
1120 doLayout(NoAnimation);
1121 }
1122 }
1123
1124 void KItemListView::slotSortRoleChanged(const QByteArray& current, const QByteArray& previous)
1125 {
1126 Q_UNUSED(current);
1127 Q_UNUSED(previous);
1128 if (m_grouped) {
1129 updateVisibleGroupHeaders();
1130 doLayout(NoAnimation);
1131 }
1132 }
1133
1134 void KItemListView::slotCurrentChanged(int current, int previous)
1135 {
1136 Q_UNUSED(previous);
1137
1138 KItemListWidget* previousWidget = m_visibleItems.value(previous, 0);
1139 if (previousWidget) {
1140 previousWidget->setCurrent(false);
1141 }
1142
1143 KItemListWidget* currentWidget = m_visibleItems.value(current, 0);
1144 if (currentWidget) {
1145 currentWidget->setCurrent(true);
1146 }
1147 }
1148
1149 void KItemListView::slotSelectionChanged(const QSet<int>& current, const QSet<int>& previous)
1150 {
1151 Q_UNUSED(previous);
1152
1153 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
1154 while (it.hasNext()) {
1155 it.next();
1156 const int index = it.key();
1157 KItemListWidget* widget = it.value();
1158 widget->setSelected(current.contains(index));
1159 }
1160 }
1161
1162 void KItemListView::slotAnimationFinished(QGraphicsWidget* widget,
1163 KItemListViewAnimation::AnimationType type)
1164 {
1165 KItemListWidget* itemListWidget = qobject_cast<KItemListWidget*>(widget);
1166 Q_ASSERT(itemListWidget);
1167
1168 switch (type) {
1169 case KItemListViewAnimation::DeleteAnimation: {
1170 // As we recycle the widget in this case it is important to assure that no
1171 // other animation has been started. This is a convention in KItemListView and
1172 // not a requirement defined by KItemListViewAnimation.
1173 Q_ASSERT(!m_animation->isStarted(itemListWidget));
1174
1175 // All KItemListWidgets that are animated by the DeleteAnimation are not maintained
1176 // by m_visibleWidgets and must be deleted manually after the animation has
1177 // been finished.
1178 recycleGroupHeaderForWidget(itemListWidget);
1179 m_widgetCreator->recycle(itemListWidget);
1180 break;
1181 }
1182
1183 case KItemListViewAnimation::CreateAnimation:
1184 case KItemListViewAnimation::MovingAnimation:
1185 case KItemListViewAnimation::ResizeAnimation: {
1186 const int index = itemListWidget->index();
1187 const bool invisible = (index < m_layouter->firstVisibleIndex()) ||
1188 (index > m_layouter->lastVisibleIndex());
1189 if (invisible && !m_animation->isStarted(itemListWidget)) {
1190 recycleWidget(itemListWidget);
1191 }
1192 break;
1193 }
1194
1195 default: break;
1196 }
1197 }
1198
1199 void KItemListView::slotLayoutTimerFinished()
1200 {
1201 m_layouter->setSize(geometry().size());
1202 doLayout(Animation);
1203 }
1204
1205 void KItemListView::slotRubberBandPosChanged()
1206 {
1207 update();
1208 }
1209
1210 void KItemListView::slotRubberBandActivationChanged(bool active)
1211 {
1212 if (active) {
1213 connect(m_rubberBand, SIGNAL(startPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1214 connect(m_rubberBand, SIGNAL(endPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1215 m_skipAutoScrollForRubberBand = true;
1216 } else {
1217 disconnect(m_rubberBand, SIGNAL(startPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1218 disconnect(m_rubberBand, SIGNAL(endPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandPosChanged()));
1219 m_skipAutoScrollForRubberBand = false;
1220 }
1221
1222 update();
1223 }
1224
1225 void KItemListView::slotHeaderColumnWidthChanged(const QByteArray& role,
1226 qreal currentWidth,
1227 qreal previousWidth)
1228 {
1229 Q_UNUSED(role);
1230 Q_UNUSED(currentWidth);
1231 Q_UNUSED(previousWidth);
1232
1233 m_headerWidget->setAutomaticColumnResizing(false);
1234 applyColumnWidthsFromHeader();
1235 doLayout(NoAnimation);
1236 }
1237
1238 void KItemListView::slotHeaderColumnMoved(const QByteArray& role,
1239 int currentIndex,
1240 int previousIndex)
1241 {
1242 Q_ASSERT(m_visibleRoles[previousIndex] == role);
1243
1244 const QList<QByteArray> previous = m_visibleRoles;
1245
1246 QList<QByteArray> current = m_visibleRoles;
1247 current.removeAt(previousIndex);
1248 current.insert(currentIndex, role);
1249
1250 setVisibleRoles(current);
1251
1252 emit visibleRolesChanged(current, previous);
1253 }
1254
1255 void KItemListView::triggerAutoScrolling()
1256 {
1257 if (!m_autoScrollTimer) {
1258 return;
1259 }
1260
1261 int pos = 0;
1262 int visibleSize = 0;
1263 if (scrollOrientation() == Qt::Vertical) {
1264 pos = m_mousePos.y();
1265 visibleSize = size().height();
1266 } else {
1267 pos = m_mousePos.x();
1268 visibleSize = size().width();
1269 }
1270
1271 if (m_autoScrollTimer->interval() == InitialAutoScrollDelay) {
1272 m_autoScrollIncrement = 0;
1273 }
1274
1275 m_autoScrollIncrement = calculateAutoScrollingIncrement(pos, visibleSize, m_autoScrollIncrement);
1276 if (m_autoScrollIncrement == 0) {
1277 // The mouse position is not above an autoscroll margin (the autoscroll timer
1278 // will be restarted in mouseMoveEvent())
1279 m_autoScrollTimer->stop();
1280 return;
1281 }
1282
1283 if (m_rubberBand->isActive() && m_skipAutoScrollForRubberBand) {
1284 // If a rubberband selection is ongoing the autoscrolling may only get triggered
1285 // if the direction of the rubberband is similar to the autoscroll direction. This
1286 // prevents that starting to create a rubberband within the autoscroll margins starts
1287 // an autoscrolling.
1288
1289 const qreal minDiff = 4; // Ignore any autoscrolling if the rubberband is very small
1290 const qreal diff = (scrollOrientation() == Qt::Vertical)
1291 ? m_rubberBand->endPosition().y() - m_rubberBand->startPosition().y()
1292 : m_rubberBand->endPosition().x() - m_rubberBand->startPosition().x();
1293 if (qAbs(diff) < minDiff || (m_autoScrollIncrement < 0 && diff > 0) || (m_autoScrollIncrement > 0 && diff < 0)) {
1294 // The rubberband direction is different from the scroll direction (e.g. the rubberband has
1295 // been moved up although the autoscroll direction might be down)
1296 m_autoScrollTimer->stop();
1297 return;
1298 }
1299 }
1300
1301 // As soon as the autoscrolling has been triggered at least once despite having an active rubberband,
1302 // the autoscrolling may not get skipped anymore until a new rubberband is created
1303 m_skipAutoScrollForRubberBand = false;
1304
1305 const qreal maxVisibleOffset = qMax(qreal(0), maximumScrollOffset() - visibleSize);
1306 const qreal newScrollOffset = qMin(scrollOffset() + m_autoScrollIncrement, maxVisibleOffset);
1307 setScrollOffset(newScrollOffset);
1308
1309 // Trigger the autoscroll timer which will periodically call
1310 // triggerAutoScrolling()
1311 m_autoScrollTimer->start(RepeatingAutoScrollDelay);
1312 }
1313
1314 void KItemListView::slotGeometryOfGroupHeaderParentChanged()
1315 {
1316 KItemListWidget* widget = qobject_cast<KItemListWidget*>(sender());
1317 Q_ASSERT(widget);
1318 KItemListGroupHeader* groupHeader = m_visibleGroups.value(widget);
1319 Q_ASSERT(groupHeader);
1320 updateGroupHeaderLayout(widget);
1321 }
1322
1323 void KItemListView::setController(KItemListController* controller)
1324 {
1325 if (m_controller != controller) {
1326 KItemListController* previous = m_controller;
1327 if (previous) {
1328 KItemListSelectionManager* selectionManager = previous->selectionManager();
1329 disconnect(selectionManager, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1330 disconnect(selectionManager, SIGNAL(selectionChanged(QSet<int>,QSet<int>)), this, SLOT(slotSelectionChanged(QSet<int>,QSet<int>)));
1331 }
1332
1333 m_controller = controller;
1334
1335 if (controller) {
1336 KItemListSelectionManager* selectionManager = controller->selectionManager();
1337 connect(selectionManager, SIGNAL(currentChanged(int,int)), this, SLOT(slotCurrentChanged(int,int)));
1338 connect(selectionManager, SIGNAL(selectionChanged(QSet<int>,QSet<int>)), this, SLOT(slotSelectionChanged(QSet<int>,QSet<int>)));
1339 }
1340
1341 onControllerChanged(controller, previous);
1342 }
1343 }
1344
1345 void KItemListView::setModel(KItemModelBase* model)
1346 {
1347 if (m_model == model) {
1348 return;
1349 }
1350
1351 KItemModelBase* previous = m_model;
1352
1353 if (m_model) {
1354 disconnect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
1355 this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
1356 disconnect(m_model, SIGNAL(itemsInserted(KItemRangeList)),
1357 this, SLOT(slotItemsInserted(KItemRangeList)));
1358 disconnect(m_model, SIGNAL(itemsRemoved(KItemRangeList)),
1359 this, SLOT(slotItemsRemoved(KItemRangeList)));
1360 disconnect(m_model, SIGNAL(itemsMoved(KItemRange,QList<int>)),
1361 this, SLOT(slotItemsMoved(KItemRange,QList<int>)));
1362 disconnect(m_model, SIGNAL(groupedSortingChanged(bool)),
1363 this, SLOT(slotGroupedSortingChanged(bool)));
1364 disconnect(m_model, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)),
1365 this, SLOT(slotSortOrderChanged(Qt::SortOrder,Qt::SortOrder)));
1366 disconnect(m_model, SIGNAL(sortRoleChanged(QByteArray,QByteArray)),
1367 this, SLOT(slotSortRoleChanged(QByteArray,QByteArray)));
1368 }
1369
1370 m_model = model;
1371 m_layouter->setModel(model);
1372 m_grouped = model->groupedSorting();
1373
1374 if (m_model) {
1375 connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
1376 this, SLOT(slotItemsChanged(KItemRangeList,QSet<QByteArray>)));
1377 connect(m_model, SIGNAL(itemsInserted(KItemRangeList)),
1378 this, SLOT(slotItemsInserted(KItemRangeList)));
1379 connect(m_model, SIGNAL(itemsRemoved(KItemRangeList)),
1380 this, SLOT(slotItemsRemoved(KItemRangeList)));
1381 connect(m_model, SIGNAL(itemsMoved(KItemRange,QList<int>)),
1382 this, SLOT(slotItemsMoved(KItemRange,QList<int>)));
1383 connect(m_model, SIGNAL(groupedSortingChanged(bool)),
1384 this, SLOT(slotGroupedSortingChanged(bool)));
1385 connect(m_model, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)),
1386 this, SLOT(slotSortOrderChanged(Qt::SortOrder,Qt::SortOrder)));
1387 connect(m_model, SIGNAL(sortRoleChanged(QByteArray,QByteArray)),
1388 this, SLOT(slotSortRoleChanged(QByteArray,QByteArray)));
1389 }
1390
1391 onModelChanged(model, previous);
1392 }
1393
1394 KItemListRubberBand* KItemListView::rubberBand() const
1395 {
1396 return m_rubberBand;
1397 }
1398
1399 void KItemListView::doLayout(LayoutAnimationHint hint, int changedIndex, int changedCount)
1400 {
1401 if (m_layoutTimer->isActive()) {
1402 m_layoutTimer->stop();
1403 }
1404
1405 if (m_activeTransactions > 0) {
1406 if (hint == NoAnimation) {
1407 // As soon as at least one property change should be done without animation,
1408 // the whole transaction will be marked as not animated.
1409 m_endTransactionAnimationHint = NoAnimation;
1410 }
1411 return;
1412 }
1413
1414 if (!m_model || m_model->count() < 0) {
1415 return;
1416 }
1417
1418 int firstVisibleIndex = m_layouter->firstVisibleIndex();
1419 if (firstVisibleIndex < 0) {
1420 emitOffsetChanges();
1421 return;
1422 }
1423
1424 // Do a sanity check of the scroll-offset property: When properties of the itemlist-view have been changed
1425 // it might be possible that the maximum offset got changed too. Assure that the full visible range
1426 // is still shown if the maximum offset got decreased.
1427 const qreal visibleOffsetRange = (scrollOrientation() == Qt::Horizontal) ? size().width() : size().height();
1428 const qreal maxOffsetToShowFullRange = maximumScrollOffset() - visibleOffsetRange;
1429 if (scrollOffset() > maxOffsetToShowFullRange) {
1430 m_layouter->setScrollOffset(qMax(qreal(0), maxOffsetToShowFullRange));
1431 firstVisibleIndex = m_layouter->firstVisibleIndex();
1432 }
1433
1434 const int lastVisibleIndex = m_layouter->lastVisibleIndex();
1435
1436 int firstSibblingIndex = -1;
1437 int lastSibblingIndex = -1;
1438 const bool supportsExpanding = supportsItemExpanding();
1439
1440 QList<int> reusableItems = recycleInvisibleItems(firstVisibleIndex, lastVisibleIndex, hint);
1441
1442 // Assure that for each visible item a KItemListWidget is available. KItemListWidget
1443 // instances from invisible items are reused. If no reusable items are
1444 // found then new KItemListWidget instances get created.
1445 const bool animate = (hint == Animation);
1446 for (int i = firstVisibleIndex; i <= lastVisibleIndex; ++i) {
1447 bool applyNewPos = true;
1448 bool wasHidden = false;
1449
1450 const QRectF itemBounds = m_layouter->itemRect(i);
1451 const QPointF newPos = itemBounds.topLeft();
1452 KItemListWidget* widget = m_visibleItems.value(i);
1453 if (!widget) {
1454 wasHidden = true;
1455 if (!reusableItems.isEmpty()) {
1456 // Reuse a KItemListWidget instance from an invisible item
1457 const int oldIndex = reusableItems.takeLast();
1458 widget = m_visibleItems.value(oldIndex);
1459 setWidgetIndex(widget, i);
1460 updateWidgetProperties(widget, i);
1461 initializeItemListWidget(widget);
1462 } else {
1463 // No reusable KItemListWidget instance is available, create a new one
1464 widget = createWidget(i);
1465 }
1466 widget->resize(itemBounds.size());
1467
1468 if (animate && changedCount < 0) {
1469 // Items have been deleted, move the created item to the
1470 // imaginary old position. They will get animated to the new position
1471 // later.
1472 const QRectF itemRect = m_layouter->itemRect(i - changedCount);
1473 if (itemRect.isEmpty()) {
1474 const QPointF invisibleOldPos = (scrollOrientation() == Qt::Vertical)
1475 ? QPointF(0, size().height()) : QPointF(size().width(), 0);
1476 widget->setPos(invisibleOldPos);
1477 } else {
1478 widget->setPos(itemRect.topLeft());
1479 }
1480 applyNewPos = false;
1481 }
1482
1483 if (supportsExpanding && changedCount == 0) {
1484 if (firstSibblingIndex < 0) {
1485 firstSibblingIndex = i;
1486 }
1487 lastSibblingIndex = i;
1488 }
1489 }
1490
1491 if (animate) {
1492 const bool itemsRemoved = (changedCount < 0);
1493 const bool itemsInserted = (changedCount > 0);
1494 if (itemsRemoved && (i >= changedIndex + changedCount + 1)) {
1495 // The item is located after the removed items. Animate the moving of the position.
1496 applyNewPos = !moveWidget(widget, newPos);
1497 } else if (itemsInserted && i >= changedIndex) {
1498 // The item is located after the first inserted item
1499 if (i <= changedIndex + changedCount - 1) {
1500 // The item is an inserted item. Animate the appearing of the item.
1501 // For performance reasons no animation is done when changedCount is equal
1502 // to all available items.
1503 if (changedCount < m_model->count()) {
1504 m_animation->start(widget, KItemListViewAnimation::CreateAnimation);
1505 }
1506 } else if (!m_animation->isStarted(widget, KItemListViewAnimation::CreateAnimation)) {
1507 // The item was already there before, so animate the moving of the position.
1508 // No moving animation is done if the item is animated by a create animation: This
1509 // prevents a "move animation mess" when inserting several ranges in parallel.
1510 applyNewPos = !moveWidget(widget, newPos);
1511 }
1512 } else if (!itemsRemoved && !itemsInserted && !wasHidden) {
1513 // The size of the view might have been changed. Animate the moving of the position.
1514 applyNewPos = !moveWidget(widget, newPos);
1515 }
1516 } else {
1517 m_animation->stop(widget);
1518 }
1519
1520 if (applyNewPos) {
1521 widget->setPos(newPos);
1522 }
1523
1524 Q_ASSERT(widget->index() == i);
1525 widget->setVisible(true);
1526
1527 if (widget->size() != itemBounds.size()) {
1528 // Resize the widget for the item to the changed size.
1529 if (animate) {
1530 // If a dynamic item size is used then no animation is done in the direction
1531 // of the dynamic size.
1532 if (m_itemSize.width() <= 0) {
1533 // The width is dynamic, apply the new width without animation.
1534 widget->resize(itemBounds.width(), widget->size().height());
1535 } else if (m_itemSize.height() <= 0) {
1536 // The height is dynamic, apply the new height without animation.
1537 widget->resize(widget->size().width(), itemBounds.height());
1538 }
1539 m_animation->start(widget, KItemListViewAnimation::ResizeAnimation, itemBounds.size());
1540 } else {
1541 widget->resize(itemBounds.size());
1542 }
1543 }
1544
1545 // Updating the cell-information must be done as last step: The decision whether the
1546 // moving-animation should be started at all is based on the previous cell-information.
1547 const Cell cell(m_layouter->itemColumn(i), m_layouter->itemRow(i));
1548 m_visibleCells.insert(i, cell);
1549 }
1550
1551 // Delete invisible KItemListWidget instances that have not been reused
1552 foreach (int index, reusableItems) {
1553 recycleWidget(m_visibleItems.value(index));
1554 }
1555
1556 if (supportsExpanding && firstSibblingIndex >= 0) {
1557 Q_ASSERT(lastSibblingIndex >= 0);
1558 updateSiblingsInformation(firstSibblingIndex, lastSibblingIndex);
1559 }
1560
1561 if (m_grouped) {
1562 // Update the layout of all visible group headers
1563 QHashIterator<KItemListWidget*, KItemListGroupHeader*> it(m_visibleGroups);
1564 while (it.hasNext()) {
1565 it.next();
1566 updateGroupHeaderLayout(it.key());
1567 }
1568 }
1569
1570 emitOffsetChanges();
1571 }
1572
1573 QList<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex,
1574 int lastVisibleIndex,
1575 LayoutAnimationHint hint)
1576 {
1577 // Determine all items that are completely invisible and might be
1578 // reused for items that just got (at least partly) visible. If the
1579 // animation hint is set to 'Animation' items that do e.g. an animated
1580 // moving of their position are not marked as invisible: This assures
1581 // that a scrolling inside the view can be done without breaking an animation.
1582
1583 QList<int> items;
1584
1585 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
1586 while (it.hasNext()) {
1587 it.next();
1588
1589 KItemListWidget* widget = it.value();
1590 const int index = widget->index();
1591 const bool invisible = (index < firstVisibleIndex) || (index > lastVisibleIndex);
1592
1593 if (invisible) {
1594 if (m_animation->isStarted(widget)) {
1595 if (hint == NoAnimation) {
1596 // Stopping the animation will call KItemListView::slotAnimationFinished()
1597 // and the widget will be recycled if necessary there.
1598 m_animation->stop(widget);
1599 }
1600 } else {
1601 widget->setVisible(false);
1602 items.append(index);
1603
1604 if (m_grouped) {
1605 recycleGroupHeaderForWidget(widget);
1606 }
1607 }
1608 }
1609 }
1610
1611 return items;
1612 }
1613
1614 bool KItemListView::moveWidget(KItemListWidget* widget,const QPointF& newPos)
1615 {
1616 if (widget->pos() == newPos) {
1617 return false;
1618 }
1619
1620 bool startMovingAnim = false;
1621
1622 // When having a grid the moving-animation should only be started, if it is done within
1623 // one row in the vertical scroll-orientation or one column in the horizontal scroll-orientation.
1624 // Otherwise instead of a moving-animation a create-animation on the new position will be used
1625 // instead. This is done to prevent overlapping (and confusing) moving-animations.
1626 const int index = widget->index();
1627 const Cell cell = m_visibleCells.value(index);
1628 if (cell.column >= 0 && cell.row >= 0) {
1629 if (scrollOrientation() == Qt::Vertical) {
1630 startMovingAnim = (cell.row == m_layouter->itemRow(index));
1631 } else {
1632 startMovingAnim = (cell.column == m_layouter->itemColumn(index));
1633 }
1634 }
1635
1636 if (startMovingAnim) {
1637 m_animation->start(widget, KItemListViewAnimation::MovingAnimation, newPos);
1638 return true;
1639 }
1640
1641 m_animation->stop(widget);
1642 m_animation->start(widget, KItemListViewAnimation::CreateAnimation);
1643 return false;
1644 }
1645
1646 void KItemListView::emitOffsetChanges()
1647 {
1648 const qreal newScrollOffset = m_layouter->scrollOffset();
1649 if (m_oldScrollOffset != newScrollOffset) {
1650 emit scrollOffsetChanged(newScrollOffset, m_oldScrollOffset);
1651 m_oldScrollOffset = newScrollOffset;
1652 }
1653
1654 const qreal newMaximumScrollOffset = m_layouter->maximumScrollOffset();
1655 if (m_oldMaximumScrollOffset != newMaximumScrollOffset) {
1656 emit maximumScrollOffsetChanged(newMaximumScrollOffset, m_oldMaximumScrollOffset);
1657 m_oldMaximumScrollOffset = newMaximumScrollOffset;
1658 }
1659
1660 const qreal newItemOffset = m_layouter->itemOffset();
1661 if (m_oldItemOffset != newItemOffset) {
1662 emit itemOffsetChanged(newItemOffset, m_oldItemOffset);
1663 m_oldItemOffset = newItemOffset;
1664 }
1665
1666 const qreal newMaximumItemOffset = m_layouter->maximumItemOffset();
1667 if (m_oldMaximumItemOffset != newMaximumItemOffset) {
1668 emit maximumItemOffsetChanged(newMaximumItemOffset, m_oldMaximumItemOffset);
1669 m_oldMaximumItemOffset = newMaximumItemOffset;
1670 }
1671 }
1672
1673 KItemListWidget* KItemListView::createWidget(int index)
1674 {
1675 KItemListWidget* widget = m_widgetCreator->create(this);
1676 widget->setFlag(QGraphicsItem::ItemStacksBehindParent);
1677
1678 m_visibleItems.insert(index, widget);
1679 m_visibleCells.insert(index, Cell());
1680 updateWidgetProperties(widget, index);
1681 initializeItemListWidget(widget);
1682 return widget;
1683 }
1684
1685 void KItemListView::recycleWidget(KItemListWidget* widget)
1686 {
1687 if (m_grouped) {
1688 recycleGroupHeaderForWidget(widget);
1689 }
1690
1691 const int index = widget->index();
1692 m_visibleItems.remove(index);
1693 m_visibleCells.remove(index);
1694
1695 m_widgetCreator->recycle(widget);
1696 }
1697
1698 void KItemListView::setWidgetIndex(KItemListWidget* widget, int index)
1699 {
1700 const int oldIndex = widget->index();
1701 m_visibleItems.remove(oldIndex);
1702 m_visibleCells.remove(oldIndex);
1703
1704 m_visibleItems.insert(index, widget);
1705 m_visibleCells.insert(index, Cell());
1706
1707 widget->setIndex(index);
1708 }
1709
1710 void KItemListView::moveWidgetToIndex(KItemListWidget* widget, int index)
1711 {
1712 const int oldIndex = widget->index();
1713 const Cell oldCell = m_visibleCells.value(oldIndex);
1714
1715 setWidgetIndex(widget, index);
1716
1717 const Cell newCell(m_layouter->itemColumn(index), m_layouter->itemRow(index));
1718 const bool vertical = (scrollOrientation() == Qt::Vertical);
1719 const bool updateCell = (vertical && oldCell.row == newCell.row) ||
1720 (!vertical && oldCell.column == newCell.column);
1721 if (updateCell) {
1722 m_visibleCells.insert(index, newCell);
1723 }
1724 }
1725
1726 void KItemListView::setLayouterSize(const QSizeF& size, SizeType sizeType)
1727 {
1728 switch (sizeType) {
1729 case LayouterSize: m_layouter->setSize(size); break;
1730 case ItemSize: m_layouter->setItemSize(size); break;
1731 default: break;
1732 }
1733 }
1734
1735 void KItemListView::updateWidgetProperties(KItemListWidget* widget, int index)
1736 {
1737 widget->setVisibleRoles(m_visibleRoles);
1738 updateWidgetColumnWidths(widget);
1739 widget->setStyleOption(m_styleOption);
1740
1741 const KItemListSelectionManager* selectionManager = m_controller->selectionManager();
1742 widget->setCurrent(index == selectionManager->currentItem());
1743 widget->setSelected(selectionManager->isSelected(index));
1744 widget->setHovered(false);
1745 widget->setEnabledSelectionToggle(enabledSelectionToggles());
1746 widget->setIndex(index);
1747 widget->setData(m_model->data(index));
1748 widget->setSiblingsInformation(QBitArray());
1749 updateAlternateBackgroundForWidget(widget);
1750
1751 if (m_grouped) {
1752 updateGroupHeaderForWidget(widget);
1753 }
1754 }
1755
1756 void KItemListView::updateGroupHeaderForWidget(KItemListWidget* widget)
1757 {
1758 Q_ASSERT(m_grouped);
1759
1760 const int index = widget->index();
1761 if (!m_layouter->isFirstGroupItem(index)) {
1762 // The widget does not represent the first item of a group
1763 // and hence requires no header
1764 recycleGroupHeaderForWidget(widget);
1765 return;
1766 }
1767
1768 const QList<QPair<int, QVariant> > groups = model()->groups();
1769 if (groups.isEmpty()) {
1770 return;
1771 }
1772
1773 KItemListGroupHeader* groupHeader = m_visibleGroups.value(widget);
1774 if (!groupHeader) {
1775 groupHeader = m_groupHeaderCreator->create(this);
1776 groupHeader->setParentItem(widget);
1777 m_visibleGroups.insert(widget, groupHeader);
1778 connect(widget, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1779 }
1780 Q_ASSERT(groupHeader->parentItem() == widget);
1781
1782 const int groupIndex = groupIndexForItem(index);
1783 Q_ASSERT(groupIndex >= 0);
1784 groupHeader->setData(groups.at(groupIndex).second);
1785 groupHeader->setRole(model()->sortRole());
1786 groupHeader->setStyleOption(m_styleOption);
1787 groupHeader->setScrollOrientation(scrollOrientation());
1788 groupHeader->setItemIndex(index);
1789
1790 groupHeader->show();
1791 }
1792
1793 void KItemListView::updateGroupHeaderLayout(KItemListWidget* widget)
1794 {
1795 KItemListGroupHeader* groupHeader = m_visibleGroups.value(widget);
1796 Q_ASSERT(groupHeader);
1797
1798 const int index = widget->index();
1799 const QRectF groupHeaderRect = m_layouter->groupHeaderRect(index);
1800 const QRectF itemRect = m_layouter->itemRect(index);
1801
1802 // The group-header is a child of the itemlist widget. Translate the
1803 // group header position to the relative position.
1804 if (scrollOrientation() == Qt::Vertical) {
1805 // In the vertical scroll orientation the group header should always span
1806 // the whole width no matter which temporary position the parent widget
1807 // has. In this case the x-position and width will be adjusted manually.
1808 groupHeader->setPos(-widget->x(), -groupHeaderRect.height());
1809 groupHeader->resize(size().width(), groupHeaderRect.size().height());
1810 } else {
1811 groupHeader->setPos(groupHeaderRect.x() - itemRect.x(), -widget->y());
1812 groupHeader->resize(groupHeaderRect.size());
1813 }
1814 }
1815
1816 void KItemListView::recycleGroupHeaderForWidget(KItemListWidget* widget)
1817 {
1818 KItemListGroupHeader* header = m_visibleGroups.value(widget);
1819 if (header) {
1820 header->setParentItem(0);
1821 m_groupHeaderCreator->recycle(header);
1822 m_visibleGroups.remove(widget);
1823 disconnect(widget, SIGNAL(geometryChanged()), this, SLOT(slotGeometryOfGroupHeaderParentChanged()));
1824 }
1825 }
1826
1827 void KItemListView::updateVisibleGroupHeaders()
1828 {
1829 Q_ASSERT(m_grouped);
1830 m_layouter->markAsDirty();
1831
1832 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
1833 while (it.hasNext()) {
1834 it.next();
1835 updateGroupHeaderForWidget(it.value());
1836 }
1837 }
1838
1839 int KItemListView::groupIndexForItem(int index) const
1840 {
1841 Q_ASSERT(m_grouped);
1842
1843 const QList<QPair<int, QVariant> > groups = model()->groups();
1844 if (groups.isEmpty()) {
1845 return -1;
1846 }
1847
1848 int min = 0;
1849 int max = groups.count() - 1;
1850 int mid = 0;
1851 do {
1852 mid = (min + max) / 2;
1853 if (index > groups[mid].first) {
1854 min = mid + 1;
1855 } else {
1856 max = mid - 1;
1857 }
1858 } while (groups[mid].first != index && min <= max);
1859
1860 if (min > max) {
1861 while (groups[mid].first > index && mid > 0) {
1862 --mid;
1863 }
1864 }
1865
1866 return mid;
1867 }
1868
1869 void KItemListView::updateAlternateBackgrounds()
1870 {
1871 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
1872 while (it.hasNext()) {
1873 it.next();
1874 updateAlternateBackgroundForWidget(it.value());
1875 }
1876 }
1877
1878 void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget* widget)
1879 {
1880 bool enabled = useAlternateBackgrounds();
1881 if (enabled) {
1882 const int index = widget->index();
1883 enabled = (index & 0x1) > 0;
1884 if (m_grouped) {
1885 const int groupIndex = groupIndexForItem(index);
1886 if (groupIndex >= 0) {
1887 const QList<QPair<int, QVariant> > groups = model()->groups();
1888 const int indexOfFirstGroupItem = groups[groupIndex].first;
1889 const int relativeIndex = index - indexOfFirstGroupItem;
1890 enabled = (relativeIndex & 0x1) > 0;
1891 }
1892 }
1893 }
1894 widget->setAlternateBackground(enabled);
1895 }
1896
1897 bool KItemListView::useAlternateBackgrounds() const
1898 {
1899 return m_itemSize.isEmpty() && m_visibleRoles.count() > 1;
1900 }
1901
1902 QHash<QByteArray, qreal> KItemListView::preferredColumnWidths(const KItemRangeList& itemRanges) const
1903 {
1904 QElapsedTimer timer;
1905 timer.start();
1906
1907 QHash<QByteArray, qreal> widths;
1908
1909 int calculatedItemCount = 0;
1910 bool maxTimeExceeded = false;
1911 foreach (const KItemRange& itemRange, itemRanges) {
1912 const int startIndex = itemRange.index;
1913 const int endIndex = startIndex + itemRange.count - 1;
1914
1915 for (int i = startIndex; i <= endIndex; ++i) {
1916 foreach (const QByteArray& visibleRole, visibleRoles()) {
1917 qreal maxWidth = widths.value(visibleRole, 0);
1918 const qreal width = preferredColumnWidth(i, visibleRole);
1919 maxWidth = qMax(width, maxWidth);
1920 widths.insert(visibleRole, maxWidth);
1921 }
1922
1923 if (calculatedItemCount > 100 && timer.elapsed() > 200) {
1924 // When having several thousands of items calculating the sizes can get
1925 // very expensive. We accept a possibly too small role-size in favour
1926 // of having no blocking user interface.
1927 maxTimeExceeded = true;
1928 break;
1929 }
1930 ++calculatedItemCount;
1931 }
1932 if (maxTimeExceeded) {
1933 break;
1934 }
1935 }
1936
1937 return widths;
1938 }
1939
1940 void KItemListView::applyColumnWidthsFromHeader()
1941 {
1942 // Apply the new size to the layouter
1943 const qreal requiredWidth = columnWidthsSum();
1944 const QSizeF dynamicItemSize(qMax(size().width(), requiredWidth),
1945 m_itemSize.height());
1946 m_layouter->setItemSize(dynamicItemSize);
1947 m_headerWidget->resize(dynamicItemSize.width(), m_headerWidget->size().height());
1948
1949 // Update the role sizes for all visible widgets
1950 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
1951 while (it.hasNext()) {
1952 it.next();
1953 updateWidgetColumnWidths(it.value());
1954 }
1955 }
1956
1957 void KItemListView::updateWidgetColumnWidths(KItemListWidget* widget)
1958 {
1959 foreach (const QByteArray& role, m_visibleRoles) {
1960 widget->setColumnWidth(role, m_headerWidget->columnWidth(role));
1961 }
1962 }
1963
1964 void KItemListView::updatePreferredColumnWidths(const KItemRangeList& itemRanges)
1965 {
1966 Q_ASSERT(m_itemSize.isEmpty());
1967 const int itemCount = m_model->count();
1968 int rangesItemCount = 0;
1969 foreach (const KItemRange& range, itemRanges) {
1970 rangesItemCount += range.count;
1971 }
1972
1973 if (itemCount == rangesItemCount) {
1974 const QHash<QByteArray, qreal> preferredWidths = preferredColumnWidths(itemRanges);
1975 foreach (const QByteArray& role, m_visibleRoles) {
1976 m_headerWidget->setPreferredColumnWidth(role, preferredWidths.value(role));
1977 }
1978 } else {
1979 // Only a sub range of the roles need to be determined.
1980 // The chances are good that the widths of the sub ranges
1981 // already fit into the available widths and hence no
1982 // expensive update might be required.
1983 bool changed = false;
1984
1985 const QHash<QByteArray, qreal> updatedWidths = preferredColumnWidths(itemRanges);
1986 QHashIterator<QByteArray, qreal> it(updatedWidths);
1987 while (it.hasNext()) {
1988 it.next();
1989 const QByteArray& role = it.key();
1990 const qreal updatedWidth = it.value();
1991 const qreal currentWidth = m_headerWidget->preferredColumnWidth(role);
1992 if (updatedWidth > currentWidth) {
1993 m_headerWidget->setPreferredColumnWidth(role, updatedWidth);
1994 changed = true;
1995 }
1996 }
1997
1998 if (!changed) {
1999 // All the updated sizes are smaller than the current sizes and no change
2000 // of the stretched roles-widths is required
2001 return;
2002 }
2003 }
2004
2005 if (m_headerWidget->automaticColumnResizing()) {
2006 applyAutomaticColumnWidths();
2007 }
2008 }
2009
2010 void KItemListView::updatePreferredColumnWidths()
2011 {
2012 if (!m_model) {
2013 return;
2014 }
2015
2016 const int itemCount = m_model->count();
2017 if (itemCount > 0) {
2018 updatePreferredColumnWidths(KItemRangeList() << KItemRange(0, itemCount));
2019 }
2020 }
2021
2022 void KItemListView::applyAutomaticColumnWidths()
2023 {
2024 Q_ASSERT(m_itemSize.isEmpty());
2025 Q_ASSERT(m_headerWidget->automaticColumnResizing());
2026
2027 // Calculate the maximum size of an item by considering the
2028 // visible role sizes and apply them to the layouter. If the
2029 // size does not use the available view-size the size of the
2030 // first role will get stretched.
2031
2032 foreach (const QByteArray& role, m_visibleRoles) {
2033 const qreal preferredWidth = m_headerWidget->preferredColumnWidth(role);
2034 m_headerWidget->setColumnWidth(role, preferredWidth);
2035 }
2036
2037 const QByteArray firstRole = m_visibleRoles.first();
2038 qreal firstColumnWidth = m_headerWidget->columnWidth(firstRole);
2039 QSizeF dynamicItemSize = m_itemSize;
2040
2041 qreal requiredWidth = columnWidthsSum();
2042 const qreal availableWidth = size().width();
2043 if (requiredWidth < availableWidth) {
2044 // Stretch the first column to use the whole remaining width
2045 firstColumnWidth += availableWidth - requiredWidth;
2046 m_headerWidget->setColumnWidth(firstRole, firstColumnWidth);
2047 } else if (requiredWidth > availableWidth) {
2048 // Shrink the first column to be able to show as much other
2049 // columns as possible
2050 qreal shrinkedFirstColumnWidth = firstColumnWidth - requiredWidth + availableWidth;
2051
2052 // TODO: A proper calculation of the minimum width depends on the implementation
2053 // of KItemListWidget. Probably a kind of minimum size-hint should be introduced
2054 // later.
2055 const qreal minWidth = qMin(firstColumnWidth, qreal(m_styleOption.iconSize * 2 + 200));
2056 if (shrinkedFirstColumnWidth < minWidth) {
2057 shrinkedFirstColumnWidth = minWidth;
2058 }
2059
2060 m_headerWidget->setColumnWidth(firstRole, shrinkedFirstColumnWidth);
2061 requiredWidth -= firstColumnWidth - shrinkedFirstColumnWidth;
2062 }
2063
2064 dynamicItemSize.rwidth() = qMax(requiredWidth, availableWidth);
2065
2066 m_layouter->setItemSize(dynamicItemSize);
2067 m_headerWidget->resize(dynamicItemSize.width(), m_headerWidget->size().height());
2068
2069 // Update the role sizes for all visible widgets
2070 QHashIterator<int, KItemListWidget*> it(m_visibleItems);
2071 while (it.hasNext()) {
2072 it.next();
2073 updateWidgetColumnWidths(it.value());
2074 }
2075 }
2076
2077 qreal KItemListView::columnWidthsSum() const
2078 {
2079 qreal widthsSum = 0;
2080 foreach (const QByteArray& role, m_visibleRoles) {
2081 widthsSum += m_headerWidget->columnWidth(role);
2082 }
2083 return widthsSum;
2084 }
2085
2086 QRectF KItemListView::headerBoundaries() const
2087 {
2088 return m_headerWidget->isVisible() ? m_headerWidget->geometry() : QRectF();
2089 }
2090
2091 bool KItemListView::changesItemGridLayout(const QSizeF& newGridSize,
2092 const QSizeF& newItemSize,
2093 const QSizeF& newItemMargin) const
2094 {
2095 if (newItemSize.isEmpty() || newGridSize.isEmpty()) {
2096 return false;
2097 }
2098
2099 if (m_layouter->scrollOrientation() == Qt::Vertical) {
2100 const qreal itemWidth = m_layouter->itemSize().width();
2101 if (itemWidth > 0) {
2102 const int newColumnCount = itemsPerSize(newGridSize.width(),
2103 newItemSize.width(),
2104 newItemMargin.width());
2105 if (m_model->count() > newColumnCount) {
2106 const int oldColumnCount = itemsPerSize(m_layouter->size().width(),
2107 itemWidth,
2108 m_layouter->itemMargin().width());
2109 return oldColumnCount != newColumnCount;
2110 }
2111 }
2112 } else {
2113 const qreal itemHeight = m_layouter->itemSize().height();
2114 if (itemHeight > 0) {
2115 const int newRowCount = itemsPerSize(newGridSize.height(),
2116 newItemSize.height(),
2117 newItemMargin.height());
2118 if (m_model->count() > newRowCount) {
2119 const int oldRowCount = itemsPerSize(m_layouter->size().height(),
2120 itemHeight,
2121 m_layouter->itemMargin().height());
2122 return oldRowCount != newRowCount;
2123 }
2124 }
2125 }
2126
2127 return false;
2128 }
2129
2130 bool KItemListView::animateChangedItemCount(int changedItemCount) const
2131 {
2132 if (m_layouter->size().isEmpty() || m_layouter->itemSize().isEmpty()) {
2133 return false;
2134 }
2135
2136 const int maximum = (scrollOrientation() == Qt::Vertical)
2137 ? m_layouter->size().width() / m_layouter->itemSize().width()
2138 : m_layouter->size().height() / m_layouter->itemSize().height();
2139 // Only animate if up to 2/3 of a row or column are inserted or removed
2140 return changedItemCount <= maximum * 2 / 3;
2141 }
2142
2143
2144 bool KItemListView::scrollBarRequired(const QSizeF& size) const
2145 {
2146 const QSizeF oldSize = m_layouter->size();
2147
2148 m_layouter->setSize(size);
2149 const qreal maxOffset = m_layouter->maximumScrollOffset();
2150 m_layouter->setSize(oldSize);
2151
2152 return m_layouter->scrollOrientation() == Qt::Vertical ? maxOffset > size.height()
2153 : maxOffset > size.width();
2154 }
2155
2156 void KItemListView::updateGroupHeaderHeight()
2157 {
2158 qreal groupHeaderHeight = m_styleOption.fontMetrics.height();
2159 qreal groupHeaderMargin = 0;
2160
2161 if (scrollOrientation() == Qt::Horizontal) {
2162 // The vertical margin above and below the header should be
2163 // equal to the horizontal margin, not the vertical margin
2164 // from m_styleOption.
2165 groupHeaderHeight += 2 * m_styleOption.horizontalMargin;
2166 groupHeaderMargin = m_styleOption.horizontalMargin;
2167 } else if (m_itemSize.isEmpty()){
2168 groupHeaderHeight += 4 * m_styleOption.padding;
2169 groupHeaderMargin = m_styleOption.iconSize / 2;
2170 } else {
2171 groupHeaderHeight += 2 * m_styleOption.padding + m_styleOption.verticalMargin;
2172 groupHeaderMargin = m_styleOption.iconSize / 4;
2173 }
2174 m_layouter->setGroupHeaderHeight(groupHeaderHeight);
2175 m_layouter->setGroupHeaderMargin(groupHeaderMargin);
2176
2177 updateVisibleGroupHeaders();
2178 }
2179
2180 void KItemListView::updateSiblingsInformation(int firstIndex, int lastIndex)
2181 {
2182 if (!supportsItemExpanding() || !m_model) {
2183 return;
2184 }
2185
2186 if (firstIndex < 0 || lastIndex < 0) {
2187 firstIndex = m_layouter->firstVisibleIndex();
2188 lastIndex = m_layouter->lastVisibleIndex();
2189 } else {
2190 const bool isRangeVisible = (firstIndex <= m_layouter->lastVisibleIndex() &&
2191 lastIndex >= m_layouter->firstVisibleIndex());
2192 if (!isRangeVisible) {
2193 return;
2194 }
2195 }
2196
2197 int previousParents = 0;
2198 QBitArray previousSiblings;
2199
2200 // The rootIndex describes the first index where the siblings get
2201 // calculated from. For the calculation the upper most parent item
2202 // is required. For performance reasons it is checked first whether
2203 // the visible items before or after the current range already
2204 // contain a siblings information which can be used as base.
2205 int rootIndex = firstIndex;
2206
2207 KItemListWidget* widget = m_visibleItems.value(firstIndex - 1);
2208 if (!widget) {
2209 // There is no visible widget before the range, check whether there
2210 // is one after the range:
2211 widget = m_visibleItems.value(lastIndex + 1);
2212 if (widget) {
2213 // The sibling information of the widget may only be used if
2214 // all items of the range have the same number of parents.
2215 const int parents = m_model->expandedParentsCount(lastIndex + 1);
2216 for (int i = lastIndex; i >= firstIndex; --i) {
2217 if (m_model->expandedParentsCount(i) != parents) {
2218 widget = 0;
2219 break;
2220 }
2221 }
2222 }
2223 }
2224
2225 if (widget) {
2226 // Performance optimization: Use the sibling information of the visible
2227 // widget beside the given range.
2228 previousSiblings = widget->siblingsInformation();
2229 if (previousSiblings.isEmpty()) {
2230 return;
2231 }
2232 previousParents = previousSiblings.count() - 1;
2233 previousSiblings.truncate(previousParents);
2234 } else {
2235 // Potentially slow path: Go back to the upper most parent of firstIndex
2236 // to be able to calculate the initial value for the siblings.
2237 while (rootIndex > 0 && m_model->expandedParentsCount(rootIndex) > 0) {
2238 --rootIndex;
2239 }
2240 }
2241
2242 Q_ASSERT(previousParents >= 0);
2243 for (int i = rootIndex; i <= lastIndex; ++i) {
2244 // Update the parent-siblings in case if the current item represents
2245 // a child or an upper parent.
2246 const int currentParents = m_model->expandedParentsCount(i);
2247 Q_ASSERT(currentParents >= 0);
2248 if (previousParents < currentParents) {
2249 previousParents = currentParents;
2250 previousSiblings.resize(currentParents);
2251 previousSiblings.setBit(currentParents - 1, hasSiblingSuccessor(i - 1));
2252 } else if (previousParents > currentParents) {
2253 previousParents = currentParents;
2254 previousSiblings.truncate(currentParents);
2255 }
2256
2257 if (i >= firstIndex) {
2258 // The index represents a visible item. Apply the parent-siblings
2259 // and update the sibling of the current item.
2260 KItemListWidget* widget = m_visibleItems.value(i);
2261 if (!widget) {
2262 continue;
2263 }
2264
2265 QBitArray siblings = previousSiblings;
2266 siblings.resize(siblings.count() + 1);
2267 siblings.setBit(siblings.count() - 1, hasSiblingSuccessor(i));
2268
2269 widget->setSiblingsInformation(siblings);
2270 }
2271 }
2272 }
2273
2274 bool KItemListView::hasSiblingSuccessor(int index) const
2275 {
2276 bool hasSuccessor = false;
2277 const int parentsCount = m_model->expandedParentsCount(index);
2278 int successorIndex = index + 1;
2279
2280 // Search the next sibling
2281 const int itemCount = m_model->count();
2282 while (successorIndex < itemCount) {
2283 const int currentParentsCount = m_model->expandedParentsCount(successorIndex);
2284 if (currentParentsCount == parentsCount) {
2285 hasSuccessor = true;
2286 break;
2287 } else if (currentParentsCount < parentsCount) {
2288 break;
2289 }
2290 ++successorIndex;
2291 }
2292
2293 if (m_grouped && hasSuccessor) {
2294 // If the sibling is part of another group, don't mark it as
2295 // successor as the group header is between the sibling connections.
2296 for (int i = index + 1; i <= successorIndex; ++i) {
2297 if (m_layouter->isFirstGroupItem(i)) {
2298 hasSuccessor = false;
2299 break;
2300 }
2301 }
2302 }
2303
2304 return hasSuccessor;
2305 }
2306
2307 int KItemListView::calculateAutoScrollingIncrement(int pos, int range, int oldInc)
2308 {
2309 int inc = 0;
2310
2311 const int minSpeed = 4;
2312 const int maxSpeed = 128;
2313 const int speedLimiter = 96;
2314 const int autoScrollBorder = 64;
2315
2316 // Limit the increment that is allowed to be added in comparison to 'oldInc'.
2317 // This assures that the autoscrolling speed grows gradually.
2318 const int incLimiter = 1;
2319
2320 if (pos < autoScrollBorder) {
2321 inc = -minSpeed + qAbs(pos - autoScrollBorder) * (pos - autoScrollBorder) / speedLimiter;
2322 inc = qMax(inc, -maxSpeed);
2323 inc = qMax(inc, oldInc - incLimiter);
2324 } else if (pos > range - autoScrollBorder) {
2325 inc = minSpeed + qAbs(pos - range + autoScrollBorder) * (pos - range + autoScrollBorder) / speedLimiter;
2326 inc = qMin(inc, maxSpeed);
2327 inc = qMin(inc, oldInc + incLimiter);
2328 }
2329
2330 return inc;
2331 }
2332
2333 int KItemListView::itemsPerSize(qreal size, qreal itemSize, qreal itemMargin)
2334 {
2335 const qreal availableSize = size - itemMargin;
2336 const int count = availableSize / (itemSize + itemMargin);
2337 return count;
2338 }
2339
2340
2341
2342 KItemListCreatorBase::~KItemListCreatorBase()
2343 {
2344 qDeleteAll(m_recycleableWidgets);
2345 qDeleteAll(m_createdWidgets);
2346 }
2347
2348 void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget* widget)
2349 {
2350 m_createdWidgets.insert(widget);
2351 }
2352
2353 void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget* widget)
2354 {
2355 Q_ASSERT(m_createdWidgets.contains(widget));
2356 m_createdWidgets.remove(widget);
2357
2358 if (m_recycleableWidgets.count() < 100) {
2359 m_recycleableWidgets.append(widget);
2360 widget->setVisible(false);
2361 } else {
2362 delete widget;
2363 }
2364 }
2365
2366 QGraphicsWidget* KItemListCreatorBase::popRecycleableWidget()
2367 {
2368 if (m_recycleableWidgets.isEmpty()) {
2369 return 0;
2370 }
2371
2372 QGraphicsWidget* widget = m_recycleableWidgets.takeLast();
2373 m_createdWidgets.insert(widget);
2374 return widget;
2375 }
2376
2377 KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase()
2378 {
2379 }
2380
2381 void KItemListWidgetCreatorBase::recycle(KItemListWidget* widget)
2382 {
2383 widget->setParentItem(0);
2384 widget->setOpacity(1.0);
2385 pushRecycleableWidget(widget);
2386 }
2387
2388 KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase()
2389 {
2390 }
2391
2392 void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader* header)
2393 {
2394 header->setOpacity(1.0);
2395 pushRecycleableWidget(header);
2396 }
2397
2398 #include "kitemlistview.moc"