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