on 6267307 help sign in
unity8/plugins/ListViewWithPageHeader/listviewwithpageheader.cpp
1201 lines 47 kB history raw
1/*
2 * Copyright (C) 2013 Canonical, Ltd.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; version 3.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
17/*
18 * Some documentation on how this thing works:
19 *
20 * A flickable has two very important concepts that define the top and
21 * height of the flickable area.
22 * The top is returned in minYExtent()
23 * The height is set using setContentHeight()
24 * By changing those two values we can make the list grow up or down
25 * as needed. e.g. if we are in the middle of the list
26 * and something that is above the viewport grows, since we do not
27 * want to change the viewport because of that we just adjust the
28 * minYExtent so that the list grows up.
29 *
30 * The implementation on the list relies on the delegateModel doing
31 * most of the instantiation work. You call createItem() when you
32 * need to create an item asking for it async or not. If returns null
33 * it means the item will be created async and the model will call the
34 * itemCreated slot with the item.
35 *
36 * updatePolish is the central point of dispatch for the work of the
37 * class. It is called by the scene graph just before drawing the class.
38 * In it we:
39 * * Make sure all items are positioned correctly
40 * * Add/Remove items if needed
41 * * Update the content height if it was dirty
42 *
43 * m_visibleItems contains all the items we have created at the moment.
44 * Actually not all of them are visible since it includes the ones
45 * in the cache area we create asynchronously to help performance.
46 * The first item in m_visibleItems has the m_firstVisibleIndex in
47 * the model. If you actually want to know what is the first
48 * item in the viewport you have to find the first non culled element
49 * in m_visibleItems
50 *
51 * All the items (except the header) are childs of m_clipItem which
52 * is a child of the contentItem() of the flickable (The contentItem()
53 * is what actually 'moves' in a a flickable). This way
54 * we can implement the clipping needed so we can have the header
55 * shown in the middle of the list over the items without the items
56 * leaking under the header in case it is transparent.
57 *
58 * The first item of m_visibleItems is the one that defines the
59 * positions of all the rest of items (see updatePolish()) and
60 * this is why sometimes we move it even if it's not the item
61 * that has triggered the function (i.e. in itemGeometryChanged())
62 *
63 * m_visibleItems is a list of ListItem. Each ListItem
64 * will contain a item and potentially a sectionItem. The sectionItem
65 * is only there when the list is using sectionDelegate+sectionProperty
66 * and this is the first item of the section. Each ListItem is vertically
67 * layouted with the sectionItem first and then the item.
68 *
69 * For sectioning we also have a section item alone (m_topSectionItem)
70 * that is used for the cases we need to show the sticky section item at
71 * the top of the view.
72 *
73 * Each delegate item has a context property called heightToClip that is
74 * used to communicate to the delegate implementation in case it has to
75 * clip itself because of overlapping with the top sticky section item.
76 * This is an implementation decision since it has been agreed it
77 * is easier to implement the clipping in QML with this info than to
78 * do it at the C++ level.
79 *
80 * Note that minYExtent and height are not always totally accurate, since
81 * we don't have the items created we can't guess their heights
82 * so we can only guarantee the values are correct when the first/last
83 * items of the list are visible, otherwise we just live with good enough
84 * values that make the list scrollable
85 *
86 * There are a few things that are not really implemented or tested properly
87 * which we don't use at the moment like changing the model, changing
88 * the section delegate, having a section delegate that changes its size, etc.
89 * The known missing features are marked with TODOs along the code.
90 */
92#include "listviewwithpageheader.h"
94#include <QDebug>
95#include <qqmlinfo.h>
96#include <qqmlengine.h>
97#pragma GCC diagnostic push
98#pragma GCC diagnostic ignored "-pedantic"
99#if (QT_VERSION < QT_VERSION_CHECK(5, 1, 0))
100#include <private/qquickvisualdatamodel_p.h>
101#else
102#include <private/qqmldelegatemodel_p.h>
103#endif
104#include <private/qqmlglobal_p.h>
105#include <private/qquickitem_p.h>
106#include <private/qquickanimation_p.h>
107#pragma GCC diagnostic pop
108// #include <private/qquickrectangle_p.h>
110static const qreal bufferRatio = 0.5;
112qreal ListViewWithPageHeader::ListItem::height() const
114 return m_item->height() + (m_sectionItem ? m_sectionItem->height() : 0);
117qreal ListViewWithPageHeader::ListItem::y() const
119 return m_item->y() - (m_sectionItem ? m_sectionItem->height() : 0);
122void ListViewWithPageHeader::ListItem::setY(qreal newY)
124 if (m_sectionItem) {
125 m_sectionItem->setY(newY);
126 m_item->setY(newY + m_sectionItem->height());
127 } else {
128 m_item->setY(newY);
129 }
132bool ListViewWithPageHeader::ListItem::culled() const
134 return QQuickItemPrivate::get(m_item)->culled;
137void ListViewWithPageHeader::ListItem::setCulled(bool culled)
139 QQuickItemPrivate::get(m_item)->setCulled(culled);
140 if (m_sectionItem)
141 QQuickItemPrivate::get(m_sectionItem)->setCulled(culled);
144ListViewWithPageHeader::ListViewWithPageHeader()
145 : m_delegateModel(nullptr)
146 , m_asyncRequestedIndex(-1)
147 , m_delegateValidated(false)
148 , m_firstVisibleIndex(-1)
149 , m_minYExtent(0)
150 , m_contentHeightDirty(false)
151 , m_headerItem(nullptr)
152 , m_previousContentY(0)
153 , m_headerItemShownHeight(0)
154 , m_sectionDelegate(nullptr)
155 , m_topSectionItem(nullptr)
156 , m_forceNoClip(false)
157 , m_inLayout(false)
159 m_clipItem = new QQuickItem(contentItem());
160// m_clipItem = new QQuickRectangle(contentItem());
161// ((QQuickRectangle*)m_clipItem)->setColor(Qt::gray);
163 m_contentYAnimation = new QQuickNumberAnimation(this);
164 m_contentYAnimation->setEasing(QEasingCurve::OutQuad);
165 m_contentYAnimation->setProperty("contentY");
166 m_contentYAnimation->setDuration(200);
167 m_contentYAnimation->setTargetObject(this);
169 connect(this, SIGNAL(contentWidthChanged()), this, SLOT(onContentWidthChanged()));
170 connect(this, SIGNAL(contentHeightChanged()), this, SLOT(onContentHeightChanged()));
171 connect(this, SIGNAL(heightChanged()), this, SLOT(onHeightChanged()));
172 connect(m_contentYAnimation, SIGNAL(stopped()), this, SLOT(onShowHeaderAnimationFinished()));
175ListViewWithPageHeader::~ListViewWithPageHeader()
179QAbstractItemModel *ListViewWithPageHeader::model() const
181 return m_delegateModel ? m_delegateModel->model().value<QAbstractItemModel *>() : nullptr;
184void ListViewWithPageHeader::setModel(QAbstractItemModel *model)
186 if (model != this->model()) {
187 if (!m_delegateModel) {
188 createDelegateModel();
189 } else {
190#if (QT_VERSION < QT_VERSION_CHECK(5, 1, 0))
191 disconnect(m_delegateModel, SIGNAL(modelUpdated(QQuickChangeSet,bool)), this, SLOT(onModelUpdated(QQuickChangeSet,bool)));
192 }
193 m_delegateModel->setModel(QVariant::fromValue<QAbstractItemModel *>(model));
194 connect(m_delegateModel, SIGNAL(modelUpdated(QQuickChangeSet,bool)), this, SLOT(onModelUpdated(QQuickChangeSet,bool)));
195#else
196 disconnect(m_delegateModel, SIGNAL(modelUpdated(QQmlChangeSet,bool)), this, SLOT(onModelUpdated(QQmlChangeSet,bool)));
197 }
198 m_delegateModel->setModel(QVariant::fromValue<QAbstractItemModel *>(model));
199 connect(m_delegateModel, SIGNAL(modelUpdated(QQmlChangeSet,bool)), this, SLOT(onModelUpdated(QQmlChangeSet,bool)));
200#endif
201 Q_EMIT modelChanged();
202 // TODO?
203// Q_EMIT contentHeightChanged();
204// Q_EMIT contentYChanged();
205 }
208QQmlComponent *ListViewWithPageHeader::delegate() const
210 return m_delegateModel ? m_delegateModel->delegate() : nullptr;
213void ListViewWithPageHeader::setDelegate(QQmlComponent *delegate)
215 if (delegate != this->delegate()) {
216 if (!m_delegateModel) {
217 createDelegateModel();
218 }
220 // Cleanup the existing items
221 Q_FOREACH(ListItem *item, m_visibleItems)
222 releaseItem(item);
223 m_visibleItems.clear();
224 m_firstVisibleIndex = -1;
225 adjustMinYExtent();
226 setContentY(0);
227 m_clipItem->setY(0);
228 if (m_topSectionItem) {
229 QQuickItemPrivate::get(m_topSectionItem)->setCulled(true);
230 }
232 m_delegateModel->setDelegate(delegate);
234 Q_EMIT delegateChanged();
235 m_delegateValidated = false;
236 m_contentHeightDirty = true;
237 polish();
238 }
241QQuickItem *ListViewWithPageHeader::header() const
243 return m_headerItem;
246void ListViewWithPageHeader::setHeader(QQuickItem *headerItem)
248 if (m_headerItem != headerItem) {
249 qreal oldHeaderHeight = 0;
250 qreal oldHeaderY = 0;
251 if (m_headerItem) {
252 oldHeaderHeight = m_headerItem->height();
253 oldHeaderY = m_headerItem->y();
254 m_headerItem->setParentItem(nullptr);
255 }
256 m_headerItem = headerItem;
257 if (m_headerItem) {
258 m_headerItem->setParentItem(contentItem());
259 m_headerItem->setZ(1);
260 }
261 qreal newHeaderHeight = m_headerItem ? m_headerItem->height() : 0;
262 if (!m_visibleItems.isEmpty() && newHeaderHeight != oldHeaderHeight) {
263 headerHeightChanged(newHeaderHeight, oldHeaderHeight, oldHeaderY);
264 polish();
265 m_contentHeightDirty = true;
266 }
267 Q_EMIT headerChanged();
268 }
271QQmlComponent *ListViewWithPageHeader::sectionDelegate() const
273 return m_sectionDelegate;
276void ListViewWithPageHeader::setSectionDelegate(QQmlComponent *delegate)
278 if (delegate != m_sectionDelegate) {
279 // TODO clean existing sections
281 m_sectionDelegate = delegate;
283 m_topSectionItem = getSectionItem(-1, QString());
284 m_topSectionItem->setZ(3);
285 QQuickItemPrivate::get(m_topSectionItem)->setCulled(true);
287 // TODO create sections for existing items
289 Q_EMIT sectionDelegateChanged();
290 }
293QString ListViewWithPageHeader::sectionProperty() const
295 return m_sectionProperty;
298void ListViewWithPageHeader::setSectionProperty(const QString &property)
300 if (property != m_sectionProperty) {
301 m_sectionProperty = property;
303 updateWatchedRoles();
305 // TODO recreate sections
307 Q_EMIT sectionPropertyChanged();
308 }
311bool ListViewWithPageHeader::forceNoClip() const
313 return m_forceNoClip;
316void ListViewWithPageHeader::setForceNoClip(bool noClip)
318 if (noClip != m_forceNoClip) {
319 m_forceNoClip = noClip;
320 updateClipItem();
321 Q_EMIT forceNoClipChanged();
322 }
325void ListViewWithPageHeader::positionAtBeginning()
327 qreal headerHeight = (m_headerItem ? m_headerItem->height() : 0);
328 if (m_firstVisibleIndex != 0) {
329 // TODO This could be optimized by trying to reuse the interesection
330 // of items that may end up intersecting between the existing
331 // m_visibleItems and the items we are creating in the next loop
332 Q_FOREACH(ListItem *item, m_visibleItems)
333 releaseItem(item);
334 m_visibleItems.clear();
335 m_firstVisibleIndex = -1;
337 // Create the item 0, it will be already correctly positioned at createItem()
338 m_clipItem->setY(0);
339 ListItem *item = createItem(0, false);
340 // Create the subsequent items
341 int modelIndex = 1;
342 qreal pos = item->y() + item->height();
343 const qreal buffer = height() * bufferRatio;
344 const qreal bufferTo = height() + buffer;
345 while (modelIndex < m_delegateModel->count() && pos <= bufferTo) {
346 if (!(item = createItem(modelIndex, false)))
347 break;
348 pos += item->height();
349 ++modelIndex;
350 }
352 m_previousContentY = m_visibleItems.first()->y() - headerHeight;
353 }
354 setContentY(m_visibleItems.first()->y() + m_clipItem->y() - headerHeight);
357void ListViewWithPageHeader::showHeader()
359 if (!m_headerItem)
360 return;
362 auto to = qMax(-minYExtent(), contentY() - m_headerItem->height() + m_headerItemShownHeight);
363 if (to != contentY()) {
364 const bool headerShownByItsOwn = contentY() < m_headerItem->y() + m_headerItem->height();
365 if (headerShownByItsOwn && m_headerItemShownHeight == 0) {
366 // We are not clipping since we are just at the top of the viewport
367 // but because of the showHeader animation we will need to, so
368 // enable the clipping without logically moving the items
369 m_headerItemShownHeight = m_headerItem->y() + m_headerItem->height() - contentY();
370 if (!m_visibleItems.isEmpty()) {
371 updateClipItem();
372 ListItem *firstItem = m_visibleItems.first();
373 firstItem->setY(firstItem->y() - m_headerItemShownHeight);
374 layout();
375 }
376 }
377 m_contentYAnimation->setTo(to);
378 contentYAnimationType = ContentYAnimationShowHeader;
379 m_contentYAnimation->start();
380 }
383QQuickItem *ListViewWithPageHeader::item(int modelIndex) const
385 ListItem *item = itemAtIndex(modelIndex);
386 if (item)
387 return item->m_item;
388 else
389 return nullptr;
392void ListViewWithPageHeader::maximizeVisibleArea(int modelIndex)
394 ListItem *listItem = itemAtIndex(modelIndex);
395 if (listItem)
396 {
397 layout();
398 const auto listItemY = m_clipItem->y() + listItem->y();
399 if (listItemY > contentY() && listItemY + listItem->height() > contentY() + height()) {
400 // we can scroll the list up to show more stuff
401 const auto to = qMin(listItemY, listItemY + listItem->height() - height());
402 m_contentYAnimation->setTo(to);
403 contentYAnimationType = ContentYAnimationMaximizeVisibleArea;
404 m_contentYAnimation->start();
405 } else if (listItemY < contentY() && listItemY + listItem->height() < contentY() + height()) {
406 // we can scroll the list down to show more stuff
407 const auto to = qMax(listItemY, listItemY + listItem->height() - height());
408 m_contentYAnimation->setTo(to);
409 contentYAnimationType = ContentYAnimationMaximizeVisibleArea;
410 m_contentYAnimation->start();
411 }
412 }
415qreal ListViewWithPageHeader::minYExtent() const
417// qDebug() << "ListViewWithPageHeader::minYExtent" << m_minYExtent;
418 return m_minYExtent;
421void ListViewWithPageHeader::componentComplete()
423 if (m_delegateModel)
424 m_delegateModel->componentComplete();
426 QQuickFlickable::componentComplete();
428 polish();
431void ListViewWithPageHeader::viewportMoved(Qt::Orientations orient)
433 QQuickFlickable::viewportMoved(orient);
434// qDebug() << "ListViewWithPageHeader::viewportMoved" << contentY();
435 qreal diff = m_previousContentY - contentY();
436 const bool showHeaderAnimationRunning = m_contentYAnimation->isRunning() && contentYAnimationType == ContentYAnimationShowHeader;
437 if (m_headerItem) {
438 auto oldHeaderItemShownHeight = m_headerItemShownHeight;
439 if (contentY() < -m_minYExtent) {
440 // Stick the header item to the top when dragging down
441 m_headerItem->setY(contentY());
442 m_headerItem->setHeight(m_headerItem->implicitHeight() + (-m_minYExtent - contentY()));
443 } else {
444 m_headerItem->setHeight(m_headerItem->implicitHeight());
445 // We are going down (but it's not because of the rebound at the end)
446 // (but the header was not shown by it's own position)
447 // or the header is partially shown and we are not doing a maximizeVisibleArea either
448 const bool scrolledUp = m_previousContentY > contentY();
449 const bool notRebounding = contentY() + height() < contentHeight();
450 const bool notShownByItsOwn = contentY() + diff > m_headerItem->y() + m_headerItem->height();
451 const bool maximizeVisibleAreaRunning = m_contentYAnimation->isRunning() && contentYAnimationType == ContentYAnimationMaximizeVisibleArea;
453 if (!scrolledUp && contentY() == -m_minYExtent) {
454 m_headerItemShownHeight = 0;
455 m_headerItem->setY(contentY());
456 } else if ((scrolledUp && notRebounding && notShownByItsOwn && !maximizeVisibleAreaRunning) || (m_headerItemShownHeight > 0)) {
457 m_headerItemShownHeight += diff;
458 if (contentY() == -m_minYExtent) {
459 m_headerItemShownHeight = 0;
460 } else {
461 m_headerItemShownHeight = qBound(static_cast<qreal>(0.), m_headerItemShownHeight, m_headerItem->height());
462 }
463 if (m_headerItemShownHeight > 0) {
464 m_headerItem->setY(contentY() - m_headerItem->height() + m_headerItemShownHeight);
465 } else {
466 m_headerItem->setY(-m_minYExtent);
467 }
468 }
469 }
470 // We will be changing the clip item, need to accomadate for it
471 // otherwise we move the firstItem down/up twice (unless the
472 // show header animation is running, where we want to keep the viewport stable)
473 if (!showHeaderAnimationRunning) {
474 diff += oldHeaderItemShownHeight - m_headerItemShownHeight;
475 } else {
476 diff = -diff;
477 }
478 }
479 if (!m_visibleItems.isEmpty()) {
480 updateClipItem();
481 ListItem *firstItem = m_visibleItems.first();
482 firstItem->setY(firstItem->y() + diff);
483 if (showHeaderAnimationRunning) {
484 adjustMinYExtent();
485 }
486 }
488 m_previousContentY = contentY();
489 layout();
490 polish();
493void ListViewWithPageHeader::createDelegateModel()
495#if (QT_VERSION < QT_VERSION_CHECK(5, 1, 0))
496 m_delegateModel = new QQuickVisualDataModel(qmlContext(this), this);
497 connect(m_delegateModel, SIGNAL(createdItem(int,QQuickItem*)), this, SLOT(itemCreated(int,QQuickItem*)));
498#else
499 m_delegateModel = new QQmlDelegateModel(qmlContext(this), this);
500 connect(m_delegateModel, SIGNAL(createdItem(int,QObject*)), this, SLOT(itemCreated(int,QObject*)));
501#endif
502 if (isComponentComplete())
503 m_delegateModel->componentComplete();
504 updateWatchedRoles();
507void ListViewWithPageHeader::refill()
509 if (m_inLayout) {
510 return;
511 }
512 if (!isComponentComplete()) {
513 return;
514 }
516 const qreal buffer = height() * bufferRatio;
517 const qreal from = contentY();
518 const qreal to = from + height();
519 const qreal bufferFrom = from - buffer;
520 const qreal bufferTo = to + buffer;
522 bool added = addVisibleItems(from, to, false);
523 bool removed = removeNonVisibleItems(bufferFrom, bufferTo);
524 added |= addVisibleItems(bufferFrom, bufferTo, true);
526 if (added || removed) {
527 m_contentHeightDirty = true;
528 }
531bool ListViewWithPageHeader::addVisibleItems(qreal fillFrom, qreal fillTo, bool asynchronous)
533 if (!delegate())
534 return false;
536 if (m_delegateModel->count() == 0)
537 return false;
539 ListItem *item;
540// qDebug() << "ListViewWithPageHeader::addVisibleItems" << fillFrom << fillTo << asynchronous;
542 int modelIndex = 0;
543 qreal pos = 0;
544 if (!m_visibleItems.isEmpty()) {
545 modelIndex = m_firstVisibleIndex + m_visibleItems.count();
546 item = m_visibleItems.last();
547 pos = item->y() + item->height() + m_clipItem->y();
548 }
549 bool changed = false;
550// qDebug() << (modelIndex < m_delegateModel->count()) << pos << fillTo;
551 while (modelIndex < m_delegateModel->count() && pos <= fillTo) {
552// qDebug() << "refill: append item" << modelIndex << "pos" << pos << "asynchronous" << asynchronous;
553 if (!(item = createItem(modelIndex, asynchronous)))
554 break;
555 pos += item->height();
556 ++modelIndex;
557 changed = true;
558 }
560 modelIndex = 0;
561 pos = 0;
562 if (!m_visibleItems.isEmpty()) {
563 modelIndex = m_firstVisibleIndex - 1;
564 item = m_visibleItems.first();
565 pos = item->y() + m_clipItem->y();
566 }
567 while (modelIndex >= 0 && pos > fillFrom) {
568// qDebug() << "refill: prepend item" << modelIndex << "pos" << pos << "fillFrom" << fillFrom << "asynchronous" << asynchronous;
569 if (!(item = createItem(modelIndex, asynchronous)))
570 break;
571 pos -= item->height();
572 --modelIndex;
573 changed = true;
574 }
576 return changed;
579void ListViewWithPageHeader::reallyReleaseItem(ListItem *listItem)
581 QQuickItem *item = listItem->m_item;
582#if (QT_VERSION < QT_VERSION_CHECK(5, 1, 0))
583 QQuickVisualModel::ReleaseFlags flags = m_delegateModel->release(item);
584 if (flags & QQuickVisualModel::Destroyed) {
585#else
586 QQmlDelegateModel::ReleaseFlags flags = m_delegateModel->release(item);
587 if (flags & QQmlDelegateModel::Destroyed) {
588#endif
589 item->setParentItem(nullptr);
590 }
591 delete listItem->m_sectionItem;
592 delete listItem;
595void ListViewWithPageHeader::releaseItem(ListItem *listItem)
597 QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(listItem->m_item);
598 itemPrivate->removeItemChangeListener(this, QQuickItemPrivate::Geometry);
599 m_itemsToRelease << listItem;
602void ListViewWithPageHeader::updateWatchedRoles()
604 if (m_delegateModel) {
605 QList<QByteArray> roles;
606 if (!m_sectionProperty.isEmpty())
607 roles << m_sectionProperty.toUtf8();
608 m_delegateModel->setWatchedRoles(roles);
609 }
612QQuickItem *ListViewWithPageHeader::getSectionItem(int modelIndex, bool alreadyInserted)
614 if (!m_sectionDelegate)
615 return nullptr;
617 const QString section = m_delegateModel->stringValue(modelIndex, m_sectionProperty);
618 if (modelIndex > 0) {
619 const QString prevSection = m_delegateModel->stringValue(modelIndex - 1, m_sectionProperty);
620 if (section == prevSection)
621 return nullptr;
622 }
623 if (modelIndex + 1 < model()->rowCount() && !alreadyInserted) {
624 // Already inserted items can't steal next section header
625 const QString nextSection = m_delegateModel->stringValue(modelIndex + 1, m_sectionProperty);
626 if (section == nextSection) {
627 // Steal the section header
628 ListItem *nextItem = itemAtIndex(modelIndex); // Not +1 since not yet inserted into m_visibleItems
629 if (nextItem) {
630 QQuickItem *sectionItem = nextItem->m_sectionItem;
631 nextItem->m_sectionItem = nullptr;
632 return sectionItem;
633 }
634 }
635 }
637 return getSectionItem(modelIndex, section);
640QQuickItem *ListViewWithPageHeader::getSectionItem(int modelIndex, const QString &sectionText)
642 QQuickItem *sectionItem = nullptr;
644 QQmlContext *creationContext = m_sectionDelegate->creationContext();
645 QQmlContext *context = new QQmlContext(creationContext ? creationContext : qmlContext(this));
646 context->setContextProperty(QLatin1String("section"), sectionText);
647 context->setContextProperty(QLatin1String("delegateIndex"), modelIndex);
648 QObject *nobj = m_sectionDelegate->beginCreate(context);
649 if (nobj) {
650 QQml_setParent_noEvent(context, nobj);
651 sectionItem = qobject_cast<QQuickItem *>(nobj);
652 if (!sectionItem) {
653 delete nobj;
654 } else {
655 sectionItem->setZ(2);
656 QQml_setParent_noEvent(sectionItem, m_clipItem);
657 sectionItem->setParentItem(m_clipItem);
658 }
659 } else {
660 delete context;
661 }
662 m_sectionDelegate->completeCreate();
664 // TODO attach to sectionItem so we can accomodate to it changing its height
666 return sectionItem;
669bool ListViewWithPageHeader::removeNonVisibleItems(qreal bufferFrom, qreal bufferTo)
671// qDebug() << "ListViewWithPageHeader::removeNonVisibleItems" << bufferFrom << bufferTo;
672 // Do not remove items if we are overshooting up or down, since we'll come back
673 // to the "stable" position and delete/create items without any reason
674 if (contentY() < -m_minYExtent) {
675 return false;
676 } else if (contentY() + height() > contentHeight()) {
677 return false;
678 }
679 bool changed = false;
681 bool foundVisible = false;
682 int i = 0;
683 int removedItems = 0;
684 const auto oldFirstVisibleIndex = m_firstVisibleIndex;
685 while (i < m_visibleItems.count()) {
686 ListItem *item = m_visibleItems[i];
687 const qreal pos = item->y() + m_clipItem->y();
688// qDebug() << i << pos << (pos + item->height()) << bufferFrom << bufferTo;
689 if (pos + item->height() < bufferFrom || pos > bufferTo) {
690// qDebug() << "Releasing" << i << (pos + item->height() < bufferFrom) << pos + item->height() << bufferFrom << (pos > bufferTo) << pos << bufferTo;
691 releaseItem(item);
692 m_visibleItems.removeAt(i);
693 changed = true;
694 ++removedItems;
695 } else {
696 if (!foundVisible) {
697 foundVisible = true;
698 const int itemIndex = m_firstVisibleIndex + removedItems + i;
699 m_firstVisibleIndex = itemIndex;
700 }
701 ++i;
702 }
703 }
704 if (m_firstVisibleIndex != oldFirstVisibleIndex) {
705 adjustMinYExtent();
706 }
708 return changed;
711ListViewWithPageHeader::ListItem *ListViewWithPageHeader::createItem(int modelIndex, bool asynchronous)
713// qDebug() << "CREATE ITEM" << modelIndex;
714 if (asynchronous && m_asyncRequestedIndex != -1)
715 return nullptr;
717 m_asyncRequestedIndex = -1;
718#if (QT_VERSION < QT_VERSION_CHECK(5, 1, 0))
719 QQuickItem *item = m_delegateModel->item(modelIndex, asynchronous);
720#else
721 QObject* object = m_delegateModel->object(modelIndex, asynchronous);
722 QQuickItem *item = qmlobject_cast<QQuickItem*>(object);
723#endif
724 if (!item) {
725#if (QT_VERSION < QT_VERSION_CHECK(5, 1, 0))
726 m_asyncRequestedIndex = modelIndex;
727#else
728 if (object) {
729 m_delegateModel->release(object);
730 if (!m_delegateValidated) {
731 m_delegateValidated = true;
732 QObject* delegateObj = delegate();
733 qmlInfo(delegateObj ? delegateObj : this) << "Delegate must be of Item type";
734 }
735 } else {
736 m_asyncRequestedIndex = modelIndex;
737 }
738#endif
739 return 0;
740 } else {
741// qDebug() << "ListViewWithPageHeader::createItem::We have the item" << modelIndex << item;
742 ListItem *listItem = new ListItem;
743 listItem->m_item = item;
744 listItem->m_sectionItem = getSectionItem(modelIndex, false /*Not yet inserted into m_visibleItems*/);
745 QQuickItemPrivate::get(item)->addItemChangeListener(this, QQuickItemPrivate::Geometry);
746 ListItem *prevItem = itemAtIndex(modelIndex - 1);
747 bool lostItem = false; // Is an item that we requested async but because of model changes
748 // it is no longer attached to any of the existing items (has no prev nor next item)
749 // nor is the first item
750 if (prevItem) {
751 listItem->setY(prevItem->y() + prevItem->height());
752 } else {
753 ListItem *currItem = itemAtIndex(modelIndex);
754 if (currItem) {
755 // There's something already in m_visibleItems at out index, meaning this is an insert, so attach to its top
756 listItem->setY(currItem->y() - listItem->height());
757 } else {
758 ListItem *nextItem = itemAtIndex(modelIndex + 1);
759 if (nextItem) {
760 listItem->setY(nextItem->y() - listItem->height());
761 } else if (modelIndex == 0 && m_headerItem) {
762 listItem->setY(m_headerItem->height());
763 } else if (!m_visibleItems.isEmpty()) {
764 lostItem = true;
765 }
766 }
767 }
768 if (lostItem) {
769 releaseItem(listItem);
770 listItem = nullptr;
771 } else {
772 listItem->setCulled(listItem->y() + listItem->height() + m_clipItem->y() <= contentY() || listItem->y() + m_clipItem->y() >= contentY() + height());
773 if (m_visibleItems.isEmpty()) {
774 m_visibleItems << listItem;
775 } else {
776 m_visibleItems.insert(modelIndex - m_firstVisibleIndex, listItem);
777 }
778 if (m_firstVisibleIndex < 0 || modelIndex < m_firstVisibleIndex) {
779 m_firstVisibleIndex = modelIndex;
780 polish();
781 }
782 if (listItem->m_sectionItem) {
783 QQmlContext *context = QQmlEngine::contextForObject(listItem->m_sectionItem)->parentContext();
784 context->setContextProperty(QLatin1String("delegateIndex"), modelIndex);
785 }
786 adjustMinYExtent();
787 m_contentHeightDirty = true;
788 }
789 return listItem;
790 }
793#if (QT_VERSION < QT_VERSION_CHECK(5, 1, 0))
794void ListViewWithPageHeader::itemCreated(int modelIndex, QQuickItem *item)
796#else
797void ListViewWithPageHeader::itemCreated(int modelIndex, QObject *object)
799 QQuickItem *item = qmlobject_cast<QQuickItem*>(object);
800 if (!item) {
801 qWarning() << "ListViewWithPageHeader::itemCreated got a non item for index" << modelIndex;
802 return;
803 }
804#endif
805// qDebug() << "ListViewWithPageHeader::itemCreated" << modelIndex << item;
807 item->setParentItem(m_clipItem);
808 QQmlContext *context = QQmlEngine::contextForObject(item)->parentContext();
809 context->setContextProperty(QLatin1String("ListViewWithPageHeader"), this);
810 context->setContextProperty(QLatin1String("heightToClip"), QVariant::fromValue<int>(0));
811 if (modelIndex == m_asyncRequestedIndex) {
812 createItem(modelIndex, false);
813 refill();
814 }
817void ListViewWithPageHeader::updateClipItem()
819 m_clipItem->setHeight(height() - m_headerItemShownHeight);
820 m_clipItem->setY(contentY() + m_headerItemShownHeight);
821 m_clipItem->setClip(!m_forceNoClip && m_headerItemShownHeight > 0);
824void ListViewWithPageHeader::onContentHeightChanged()
826 updateClipItem();
829void ListViewWithPageHeader::onContentWidthChanged()
831 m_clipItem->setWidth(contentItem()->width());
834void ListViewWithPageHeader::onHeightChanged()
836 polish();
840#if (QT_VERSION < QT_VERSION_CHECK(5, 1, 0))
841void ListViewWithPageHeader::onModelUpdated(const QQuickChangeSet &changeSet, bool /*reset*/)
842#else
843void ListViewWithPageHeader::onModelUpdated(const QQmlChangeSet &changeSet, bool /*reset*/)
844#endif
846 // TODO Do something with reset
847// qDebug() << "ListViewWithPageHeader::onModelUpdated" << changeSet << reset;
848 const auto oldFirstVisibleIndex = m_firstVisibleIndex;
850#if (QT_VERSION < QT_VERSION_CHECK(5, 1, 0))
851 Q_FOREACH(const QQuickChangeSet::Remove &remove, changeSet.removes()) {
852#else
853 Q_FOREACH(const QQmlChangeSet::Remove &remove, changeSet.removes()) {
854#endif
855// qDebug() << "ListViewWithPageHeader::onModelUpdated Remove" << remove.index << remove.count;
856 if (remove.index + remove.count > m_firstVisibleIndex && remove.index < m_firstVisibleIndex + m_visibleItems.count()) {
857 const qreal oldFirstValidIndexPos = m_visibleItems.first()->y();
858 // If all the items we are removing are either not created or culled
859 // we have to grow down to avoid viewport changing
860 bool growDown = true;
861 for (int i = 0; growDown && i < remove.count; ++i) {
862 const int modelIndex = remove.index + i;
863 ListItem *item = itemAtIndex(modelIndex);
864 if (item && !item->culled()) {
865 growDown = false;
866 }
867 }
868 for (int i = remove.count - 1; i >= 0; --i) {
869 const int visibleIndex = remove.index + i - m_firstVisibleIndex;
870 if (visibleIndex >= 0 && visibleIndex < m_visibleItems.count()) {
871 ListItem *item = m_visibleItems[visibleIndex];
872 // Pass the section item down if needed
873 if (item->m_sectionItem && visibleIndex + 1 < m_visibleItems.count()) {
874 ListItem *nextItem = m_visibleItems[visibleIndex + 1];
875 if (!nextItem->m_sectionItem) {
876 nextItem->m_sectionItem = item->m_sectionItem;
877 item->m_sectionItem = nullptr;
878 }
879 }
880 releaseItem(item);
881 m_visibleItems.removeAt(visibleIndex);
882 }
883 }
884 if (growDown) {
885 adjustMinYExtent();
886 } else if (remove.index <= m_firstVisibleIndex) {
887 if (!m_visibleItems.isEmpty()) {
888 // We removed the first item that is the one that positions the rest
889 // position the new first item correctly
890 m_visibleItems.first()->setY(oldFirstValidIndexPos);
891 } else {
892 m_firstVisibleIndex = -1;
893 }
894 }
895 } else if (remove.index + remove.count <= m_firstVisibleIndex) {
896 m_firstVisibleIndex -= remove.count;
897 }
898 for (int i = remove.count - 1; i >= 0; --i) {
899 const int modelIndex = remove.index + i;
900 if (modelIndex == m_asyncRequestedIndex) {
901 m_asyncRequestedIndex = -1;
902 } else if (modelIndex < m_asyncRequestedIndex) {
903 m_asyncRequestedIndex--;
904 }
905 }
906 }
908#if (QT_VERSION < QT_VERSION_CHECK(5, 1, 0))
909 Q_FOREACH(const QQuickChangeSet::Insert &insert, changeSet.inserts()) {
910#else
911 Q_FOREACH(const QQmlChangeSet::Insert &insert, changeSet.inserts()) {
912#endif
913// qDebug() << "ListViewWithPageHeader::onModelUpdated Insert" << insert.index << insert.count;
914 const bool insertingInValidIndexes = insert.index > m_firstVisibleIndex && insert.index < m_firstVisibleIndex + m_visibleItems.count();
915 const bool firstItemWithViewOnTop = insert.index == 0 && m_firstVisibleIndex == 0 && m_visibleItems.first()->y() + m_clipItem->y() > contentY();
916 if (insertingInValidIndexes || firstItemWithViewOnTop)
917 {
918 // If the items we are adding won't be really visible
919 // we grow up instead of down to not change the viewport
920 bool growUp = false;
921 if (!firstItemWithViewOnTop) {
922 for (int i = 0; i < m_visibleItems.count(); ++i) {
923 if (!m_visibleItems[i]->culled()) {
924 if (insert.index <= m_firstVisibleIndex + i) {
925 growUp = true;
926 }
927 break;
928 }
929 }
930 }
932 const qreal oldFirstValidIndexPos = m_visibleItems.first()->y();
933 for (int i = insert.count - 1; i >= 0; --i) {
934 const int modelIndex = insert.index + i;
935 ListItem *item = createItem(modelIndex, false);
936 if (growUp) {
937 ListItem *firstItem = m_visibleItems.first();
938 firstItem->setY(firstItem->y() - item->height());
939 adjustMinYExtent();
940 }
941 // Adding an item may break a "same section" chain, so check
942 // if we need adding a new section item
943 if (m_sectionDelegate) {
944 ListItem *nextItem = itemAtIndex(modelIndex + 1);
945 if (nextItem && !nextItem->m_sectionItem) {
946 nextItem->m_sectionItem = getSectionItem(modelIndex + 1, true /* alredy inserted into m_visibleItems*/);
947 if (growUp && nextItem->m_sectionItem) {
948 ListItem *firstItem = m_visibleItems.first();
949 firstItem->setY(firstItem->y() - nextItem->m_sectionItem->height());
950 adjustMinYExtent();
951 }
952 }
953 }
954 }
955 if (firstItemWithViewOnTop) {
956 ListItem *firstItem = m_visibleItems.first();
957 firstItem->setY(oldFirstValidIndexPos);
958 }
959 } else if (insert.index <= m_firstVisibleIndex) {
960 m_firstVisibleIndex += insert.count;
961 }
963 for (int i = insert.count - 1; i >= 0; --i) {
964 const int modelIndex = insert.index + i;
965 if (modelIndex <= m_asyncRequestedIndex) {
966 m_asyncRequestedIndex++;
967 }
968 }
969 }
971 if (m_firstVisibleIndex != oldFirstVisibleIndex) {
972 adjustMinYExtent();
973 }
975 for (int i = 0; i < m_visibleItems.count(); ++i) {
976 ListItem *item = m_visibleItems[i];
977 if (item->m_sectionItem) {
978 QQmlContext *context = QQmlEngine::contextForObject(item->m_sectionItem)->parentContext();
979 context->setContextProperty(QLatin1String("delegateIndex"), m_firstVisibleIndex + i);
980 }
981 }
983 layout();
984 polish();
985 m_contentHeightDirty = true;
988void ListViewWithPageHeader::onShowHeaderAnimationFinished()
990 m_contentHeightDirty = true;
991 polish();
994void ListViewWithPageHeader::itemGeometryChanged(QQuickItem * /*item*/, const QRectF &newGeometry, const QRectF &oldGeometry)
996 const qreal heightDiff = newGeometry.height() - oldGeometry.height();
997 if (heightDiff != 0) {
998 if (oldGeometry.y() + oldGeometry.height() + m_clipItem->y() < contentY() && !m_visibleItems.isEmpty()) {
999 ListItem *firstItem = m_visibleItems.first();
1000 firstItem->setY(firstItem->y() - heightDiff);
1001 adjustMinYExtent();
1002 layout();
1004 refill();
1005 adjustMinYExtent();
1006 polish();
1007 m_contentHeightDirty = true;
1011void ListViewWithPageHeader::headerHeightChanged(qreal newHeaderHeight, qreal oldHeaderHeight, qreal oldHeaderY)
1013 const qreal heightDiff = newHeaderHeight - oldHeaderHeight;
1014 if (m_headerItemShownHeight > 0) {
1015 // If the header is shown because of the clip
1016 // Change its size
1017 m_headerItemShownHeight += heightDiff;
1018 m_headerItemShownHeight = qBound(static_cast<qreal>(0.), m_headerItemShownHeight, newHeaderHeight);
1019 updateClipItem();
1020 adjustMinYExtent();
1021 } else {
1022 if (oldHeaderY + oldHeaderHeight > contentY()) {
1023 // If the header is shown because its position
1024 // Change its size
1025 ListItem *firstItem = m_visibleItems.first();
1026 firstItem->setY(firstItem->y() + heightDiff);
1027 layout();
1028 } else {
1029 // If the header is not on screen, just change the start of the list
1030 // so the viewport is not changed
1031 adjustMinYExtent();
1037void ListViewWithPageHeader::adjustMinYExtent()
1039 if (m_visibleItems.isEmpty()) {
1040 m_minYExtent = 0;
1041 } else {
1042 qreal nonCreatedHeight = 0;
1043 if (m_firstVisibleIndex != 0) {
1044 // Calculate the average height of items to estimate the position of the list start
1045 const int visibleItems = m_visibleItems.count();
1046 qreal visibleItemsHeight = 0;
1047 Q_FOREACH(ListItem *item, m_visibleItems) {
1048 visibleItemsHeight += item->height();
1050 nonCreatedHeight = m_firstVisibleIndex * visibleItemsHeight / visibleItems;
1051// qDebug() << m_firstVisibleIndex << visibleItemsHeight << visibleItems << nonCreatedHeight;
1053 m_minYExtent = nonCreatedHeight - m_visibleItems.first()->y() - m_clipItem->y() + (m_headerItem ? m_headerItem->implicitHeight() : 0);
1057ListViewWithPageHeader::ListItem *ListViewWithPageHeader::itemAtIndex(int modelIndex) const
1059 const int visibleIndexedModelIndex = modelIndex - m_firstVisibleIndex;
1060 if (visibleIndexedModelIndex >= 0 && visibleIndexedModelIndex < m_visibleItems.count())
1061 return m_visibleItems[visibleIndexedModelIndex];
1063 return nullptr;
1066void ListViewWithPageHeader::layout()
1068 if (m_inLayout)
1069 return;
1071 m_inLayout = true;
1072 if (!m_visibleItems.isEmpty()) {
1073 const qreal visibleFrom = contentY() - m_clipItem->y() + m_headerItemShownHeight;
1074 const qreal visibleTo = contentY() + height() - m_clipItem->y();
1076 qreal pos = m_visibleItems.first()->y();
1078// qDebug() << "ListViewWithPageHeader::layout Updating positions and heights. contentY" << contentY() << "minYExtent" << minYExtent();
1079 int firstReallyVisibleItem = -1;
1080 int modelIndex = m_firstVisibleIndex;
1081 Q_FOREACH(ListItem *item, m_visibleItems) {
1082 const bool cull = pos + item->height() <= visibleFrom || pos >= visibleTo;
1083 item->setCulled(cull);
1084 item->setY(pos);
1085 if (!cull && firstReallyVisibleItem == -1) {
1086 firstReallyVisibleItem = modelIndex;
1087 if (m_topSectionItem) {
1088 // Positing the top section sticky item is a two step process
1089 // First we set it either we cull it (because it doesn't need to be sticked to the top)
1090 // or stick it to the top
1091 // Then after the loop we'll make sure that if there's another section just below it
1092 // pushed the sticky section up to make it disappear
1093 const qreal topSectionStickPos = m_headerItemShownHeight + contentY() - m_clipItem->y();
1094 if (topSectionStickPos <= pos) {
1095 QQuickItemPrivate::get(m_topSectionItem)->setCulled(true);
1096 if (item->m_sectionItem) {
1097 // This seems it should happen since why would we cull the top section
1098 // if the first visible item has no section header? This only happens briefly
1099 // when increasing the height of a list that is at the bottom, the m_topSectionItem
1100 // gets shown shortly in the next polish call
1101 QQuickItemPrivate::get(item->m_sectionItem)->setCulled(false);
1103 } else {
1104 // Update the top sticky section header
1105 const QString section = m_delegateModel->stringValue(modelIndex, m_sectionProperty);
1106 QQmlContext *context = QQmlEngine::contextForObject(m_topSectionItem)->parentContext();
1107 context->setContextProperty(QLatin1String("section"), section);
1109 QQuickItemPrivate::get(m_topSectionItem)->setCulled(false);
1110 m_topSectionItem->setY(topSectionStickPos);
1111 int delegateIndex = modelIndex;
1112 // Look for the first index with this section text
1113 while (delegateIndex > 0) {
1114 const QString prevSection = m_delegateModel->stringValue(delegateIndex - 1, m_sectionProperty);
1115 if (prevSection != section)
1116 break;
1117 delegateIndex--;
1119 context->setContextProperty(QLatin1String("delegateIndex"), delegateIndex);
1120 if (item->m_sectionItem) {
1121 QQuickItemPrivate::get(item->m_sectionItem)->setCulled(true);
1126 QQmlContext *context = QQmlEngine::contextForObject(item->m_item)->parentContext();
1127 const qreal clipFrom = visibleFrom + (!item->m_sectionItem && m_topSectionItem && !QQuickItemPrivate::get(m_topSectionItem)->culled ? m_topSectionItem->height() : 0);
1128 if (!cull && pos < clipFrom) {
1129 context->setContextProperty(QLatin1String("heightToClip"), clipFrom - pos);
1130 } else {
1131 context->setContextProperty(QLatin1String("heightToClip"), QVariant::fromValue<int>(0));
1133// qDebug() << "ListViewWithPageHeader::layout" << item->m_item;
1134 pos += item->height();
1135 ++modelIndex;
1138 // Second step of section sticky item positioning
1139 // Look at the next section header, check if it's pushing up the sticky one
1140 if (m_topSectionItem) {
1141 if (firstReallyVisibleItem >= 0) {
1142 for (int i = firstReallyVisibleItem - m_firstVisibleIndex + 1; i < m_visibleItems.count(); ++i) {
1143 ListItem *item = m_visibleItems[i];
1144 if (item->m_sectionItem) {
1145 if (m_topSectionItem->y() + m_topSectionItem->height() > item->y()) {
1146 m_topSectionItem->setY(item->y() - m_topSectionItem->height());
1148 break;
1154 m_inLayout = false;
1157void ListViewWithPageHeader::updatePolish()
1159 Q_FOREACH(ListItem *item, m_itemsToRelease)
1160 reallyReleaseItem(item);
1161 m_itemsToRelease.clear();
1163 if (!model())
1164 return;
1166 layout();
1168 refill();
1170 if (m_contentHeightDirty) {
1171 qreal contentHeight;
1172 if (m_visibleItems.isEmpty()) {
1173 contentHeight = m_headerItem ? m_headerItem->height() : 0;
1174 } else {
1175 const int modelCount = model()->rowCount();
1176 const int visibleItems = m_visibleItems.count();
1177 const int lastValidIndex = m_firstVisibleIndex + visibleItems - 1;
1178 qreal nonCreatedHeight = 0;
1179 if (lastValidIndex != modelCount - 1) {
1180 const int visibleItems = m_visibleItems.count();
1181 qreal visibleItemsHeight = 0;
1182 Q_FOREACH(ListItem *item, m_visibleItems) {
1183 visibleItemsHeight += item->height();
1185 const int unknownSizes = modelCount - (m_firstVisibleIndex + visibleItems);
1186 nonCreatedHeight = unknownSizes * visibleItemsHeight / visibleItems;
1188 ListItem *item = m_visibleItems.last();
1189 contentHeight = nonCreatedHeight + item->y() + item->height() + m_clipItem->y();
1190 if (m_firstVisibleIndex != 0) {
1191 // Make sure that if we are shrinking we tell the view we still fit
1192 m_minYExtent = qMax(m_minYExtent, -(contentHeight - height()));
1196 m_contentHeightDirty = false;
1197 setContentHeight(contentHeight);
1201#include "moc_listviewwithpageheader.cpp"