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