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