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