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