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