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