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