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