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