on b4e1ebd help sign in
unity8/plugins/ListViewWithPageHeader/listviewwithpageheader.cpp
1144 lines 44 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_headerShowAnimation = new QQuickNumberAnimation(this);
164 m_headerShowAnimation->setEasing(QEasingCurve::OutQuad);
165 m_headerShowAnimation->setProperty("contentY");
166 m_headerShowAnimation->setDuration(200);
167 m_headerShowAnimation->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_headerShowAnimation, 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(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_headerShowAnimation->setTo(to);
378 m_headerShowAnimation->start();
379 }
382qreal ListViewWithPageHeader::minYExtent() const
384// qDebug() << "ListViewWithPageHeader::minYExtent" << m_minYExtent;
385 return m_minYExtent;
388void ListViewWithPageHeader::componentComplete()
390 if (m_delegateModel)
391 m_delegateModel->componentComplete();
393 QQuickFlickable::componentComplete();
395 polish();
398void ListViewWithPageHeader::viewportMoved(Qt::Orientations orient)
400 QQuickFlickable::viewportMoved(orient);
401// qDebug() << "ListViewWithPageHeader::viewportMoved" << contentY();
402 qreal diff = m_previousContentY - contentY();
403 if (m_headerItem) {
404 auto oldHeaderItemShownHeight = m_headerItemShownHeight;
405 if (contentY() < -m_minYExtent) {
406 // Stick the header item to the top when dragging down
407 m_headerItem->setY(contentY());
408 m_headerItem->setHeight(m_headerItem->implicitHeight() + (-m_minYExtent - contentY()));
409 } else {
410 m_headerItem->setHeight(m_headerItem->implicitHeight());
411 // We are going down (but it's not because of the rebound at the end)
412 // (but the header was not shown by it's own position)
413 // or the header is partially shown
414 const bool scrolledUp = m_previousContentY > contentY();
415 const bool notRebounding = contentY() + height() < contentHeight();
416 const bool notShownByItsOwn = contentY() + diff > m_headerItem->y() + m_headerItem->height();
418 if (!scrolledUp && contentY() == -m_minYExtent) {
419 m_headerItemShownHeight = 0;
420 m_headerItem->setY(contentY());
421 } else if ((scrolledUp && notRebounding && notShownByItsOwn) || (m_headerItemShownHeight > 0)) {
422 m_headerItemShownHeight += diff;
423 if (contentY() == -m_minYExtent) {
424 m_headerItemShownHeight = 0;
425 } else {
426 m_headerItemShownHeight = qBound(static_cast<qreal>(0.), m_headerItemShownHeight, m_headerItem->height());
427 }
428 if (m_headerItemShownHeight > 0) {
429 m_headerItem->setY(contentY() - m_headerItem->height() + m_headerItemShownHeight);
430 } else {
431 m_headerItem->setY(-m_minYExtent);
432 }
433 }
434 }
435 // We will be changing the clip item, need to accomadate for it
436 // otherwise we move the firstItem down/up twice (unless the
437 // show header animation is running, where we want to keep the viewport stable)
438 if (!m_headerShowAnimation->isRunning()) {
439 diff += oldHeaderItemShownHeight - m_headerItemShownHeight;
440 } else {
441 diff = -diff;
442 }
443 }
444 if (!m_visibleItems.isEmpty()) {
445 updateClipItem();
446 ListItem *firstItem = m_visibleItems.first();
447 firstItem->setY(firstItem->y() + diff);
448 if (m_headerShowAnimation->isRunning()) {
449 adjustMinYExtent();
450 }
451 }
453 m_previousContentY = contentY();
454 layout();
455 polish();
458void ListViewWithPageHeader::createDelegateModel()
460#if (QT_VERSION < QT_VERSION_CHECK(5, 1, 0))
461 m_delegateModel = new QQuickVisualDataModel(qmlContext(this), this);
462 connect(m_delegateModel, SIGNAL(createdItem(int,QQuickItem*)), this, SLOT(itemCreated(int,QQuickItem*)));
463#else
464 m_delegateModel = new QQmlDelegateModel(qmlContext(this), this);
465 connect(m_delegateModel, SIGNAL(createdItem(int,QObject*)), this, SLOT(itemCreated(int,QObject*)));
466#endif
467 if (isComponentComplete())
468 m_delegateModel->componentComplete();
469 updateWatchedRoles();
472void ListViewWithPageHeader::refill()
474 if (m_inLayout) {
475 return;
476 }
477 if (!isComponentComplete()) {
478 return;
479 }
481 const qreal buffer = height() * bufferRatio;
482 const qreal from = contentY();
483 const qreal to = from + height();
484 const qreal bufferFrom = from - buffer;
485 const qreal bufferTo = to + buffer;
487 bool added = addVisibleItems(from, to, false);
488 bool removed = removeNonVisibleItems(bufferFrom, bufferTo);
489 added |= addVisibleItems(bufferFrom, bufferTo, true);
491 if (added || removed) {
492 m_contentHeightDirty = true;
493 }
496bool ListViewWithPageHeader::addVisibleItems(qreal fillFrom, qreal fillTo, bool asynchronous)
498 if (!delegate())
499 return false;
501 if (m_delegateModel->count() == 0)
502 return false;
504 ListItem *item;
505// qDebug() << "ListViewWithPageHeader::addVisibleItems" << fillFrom << fillTo << asynchronous;
507 int modelIndex = 0;
508 qreal pos = 0;
509 if (!m_visibleItems.isEmpty()) {
510 modelIndex = m_firstVisibleIndex + m_visibleItems.count();
511 item = m_visibleItems.last();
512 pos = item->y() + item->height() + m_clipItem->y();
513 }
514 bool changed = false;
515// qDebug() << (modelIndex < m_delegateModel->count()) << pos << fillTo;
516 while (modelIndex < m_delegateModel->count() && pos <= fillTo) {
517// qDebug() << "refill: append item" << modelIndex << "pos" << pos << "asynchronous" << asynchronous;
518 if (!(item = createItem(modelIndex, asynchronous)))
519 break;
520 pos += item->height();
521 ++modelIndex;
522 changed = true;
523 }
525 modelIndex = 0;
526 pos = 0;
527 if (!m_visibleItems.isEmpty()) {
528 modelIndex = m_firstVisibleIndex - 1;
529 item = m_visibleItems.first();
530 pos = item->y() + m_clipItem->y();
531 }
532 while (modelIndex >= 0 && pos > fillFrom) {
533// qDebug() << "refill: prepend item" << modelIndex << "pos" << pos << "fillFrom" << fillFrom << "asynchronous" << asynchronous;
534 if (!(item = createItem(modelIndex, asynchronous)))
535 break;
536 pos -= item->height();
537 --modelIndex;
538 changed = true;
539 }
541 return changed;
544void ListViewWithPageHeader::reallyReleaseItem(ListItem *listItem)
546 QQuickItem *item = listItem->m_item;
547#if (QT_VERSION < QT_VERSION_CHECK(5, 1, 0))
548 QQuickVisualModel::ReleaseFlags flags = m_delegateModel->release(item);
549 if (flags & QQuickVisualModel::Destroyed) {
550#else
551 QQmlDelegateModel::ReleaseFlags flags = m_delegateModel->release(item);
552 if (flags & QQmlDelegateModel::Destroyed) {
553#endif
554 item->setParentItem(nullptr);
555 }
556 delete listItem->m_sectionItem;
557 delete listItem;
560void ListViewWithPageHeader::releaseItem(ListItem *listItem)
562 QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(listItem->m_item);
563 itemPrivate->removeItemChangeListener(this, QQuickItemPrivate::Geometry);
564 m_itemsToRelease << listItem;
567void ListViewWithPageHeader::updateWatchedRoles()
569 if (m_delegateModel) {
570 QList<QByteArray> roles;
571 if (!m_sectionProperty.isEmpty())
572 roles << m_sectionProperty.toUtf8();
573 m_delegateModel->setWatchedRoles(roles);
574 }
577QQuickItem *ListViewWithPageHeader::getSectionItem(int modelIndex, bool alreadyInserted)
579 if (!m_sectionDelegate)
580 return nullptr;
582 const QString section = m_delegateModel->stringValue(modelIndex, m_sectionProperty);
583 if (modelIndex > 0) {
584 const QString prevSection = m_delegateModel->stringValue(modelIndex - 1, m_sectionProperty);
585 if (section == prevSection)
586 return nullptr;
587 }
588 if (modelIndex + 1 < model()->rowCount() && !alreadyInserted) {
589 // Already inserted items can't steal next section header
590 const QString nextSection = m_delegateModel->stringValue(modelIndex + 1, m_sectionProperty);
591 if (section == nextSection) {
592 // Steal the section header
593 ListItem *nextItem = itemAtIndex(modelIndex); // Not +1 since not yet inserted into m_visibleItems
594 if (nextItem) {
595 QQuickItem *sectionItem = nextItem->m_sectionItem;
596 nextItem->m_sectionItem = nullptr;
597 return sectionItem;
598 }
599 }
600 }
602 return getSectionItem(section);
605QQuickItem *ListViewWithPageHeader::getSectionItem(const QString &sectionText)
607 QQuickItem *sectionItem = nullptr;
609 QQmlContext *creationContext = m_sectionDelegate->creationContext();
610 QQmlContext *context = new QQmlContext(creationContext ? creationContext : qmlContext(this));
611 context->setContextProperty(QLatin1String("section"), sectionText);
612 QObject *nobj = m_sectionDelegate->beginCreate(context);
613 if (nobj) {
614 QQml_setParent_noEvent(context, nobj);
615 sectionItem = qobject_cast<QQuickItem *>(nobj);
616 if (!sectionItem) {
617 delete nobj;
618 } else {
619 sectionItem->setZ(2);
620 QQml_setParent_noEvent(sectionItem, m_clipItem);
621 sectionItem->setParentItem(m_clipItem);
622 }
623 } else {
624 delete context;
625 }
626 m_sectionDelegate->completeCreate();
628 // TODO attach to sectionItem so we can accomodate to it changing its height
630 return sectionItem;
633bool ListViewWithPageHeader::removeNonVisibleItems(qreal bufferFrom, qreal bufferTo)
635// qDebug() << "ListViewWithPageHeader::removeNonVisibleItems" << bufferFrom << bufferTo;
636 // Do not remove items if we are overshooting up or down, since we'll come back
637 // to the "stable" position and delete/create items without any reason
638 if (contentY() < -m_minYExtent) {
639 return false;
640 } else if (contentY() + height() > contentHeight()) {
641 return false;
642 }
643 bool changed = false;
645 bool foundVisible = false;
646 int i = 0;
647 int removedItems = 0;
648 const auto oldFirstVisibleIndex = m_firstVisibleIndex;
649 while (i < m_visibleItems.count()) {
650 ListItem *item = m_visibleItems[i];
651 const qreal pos = item->y() + m_clipItem->y();
652// qDebug() << i << pos << (pos + item->height()) << bufferFrom << bufferTo;
653 if (pos + item->height() < bufferFrom || pos > bufferTo) {
654// qDebug() << "Releasing" << i << (pos + item->height() < bufferFrom) << pos + item->height() << bufferFrom << (pos > bufferTo) << pos << bufferTo;
655 releaseItem(item);
656 m_visibleItems.removeAt(i);
657 changed = true;
658 ++removedItems;
659 } else {
660 if (!foundVisible) {
661 foundVisible = true;
662 const int itemIndex = m_firstVisibleIndex + removedItems + i;
663 m_firstVisibleIndex = itemIndex;
664 }
665 ++i;
666 }
667 }
668 if (m_firstVisibleIndex != oldFirstVisibleIndex) {
669 adjustMinYExtent();
670 }
672 return changed;
675ListViewWithPageHeader::ListItem *ListViewWithPageHeader::createItem(int modelIndex, bool asynchronous)
677// qDebug() << "CREATE ITEM" << modelIndex;
678 if (asynchronous && m_asyncRequestedIndex != -1)
679 return nullptr;
681 m_asyncRequestedIndex = -1;
682#if (QT_VERSION < QT_VERSION_CHECK(5, 1, 0))
683 QQuickItem *item = m_delegateModel->item(modelIndex, asynchronous);
684#else
685 QObject* object = m_delegateModel->object(modelIndex, asynchronous);
686 QQuickItem *item = qmlobject_cast<QQuickItem*>(object);
687#endif
688 if (!item) {
689#if (QT_VERSION < QT_VERSION_CHECK(5, 1, 0))
690 m_asyncRequestedIndex = modelIndex;
691#else
692 if (object) {
693 m_delegateModel->release(object);
694 if (!m_delegateValidated) {
695 m_delegateValidated = true;
696 QObject* delegateObj = delegate();
697 qmlInfo(delegateObj ? delegateObj : this) << "Delegate must be of Item type";
698 }
699 } else {
700 m_asyncRequestedIndex = modelIndex;
701 }
702#endif
703 return 0;
704 } else {
705// qDebug() << "ListViewWithPageHeader::createItem::We have the item" << modelIndex << item;
706 ListItem *listItem = new ListItem;
707 listItem->m_item = item;
708 listItem->m_sectionItem = getSectionItem(modelIndex, false /*Not yet inserted into m_visibleItems*/);
709 QQuickItemPrivate::get(item)->addItemChangeListener(this, QQuickItemPrivate::Geometry);
710 ListItem *prevItem = itemAtIndex(modelIndex - 1);
711 bool lostItem = false; // Is an item that we requested async but because of model changes
712 // it is no longer attached to any of the existing items (has no prev nor next item)
713 // nor is the first item
714 if (prevItem) {
715 listItem->setY(prevItem->y() + prevItem->height());
716 } else {
717 ListItem *currItem = itemAtIndex(modelIndex);
718 if (currItem) {
719 // There's something already in m_visibleItems at out index, meaning this is an insert, so attach to its top
720 listItem->setY(currItem->y() - listItem->height());
721 } else {
722 ListItem *nextItem = itemAtIndex(modelIndex + 1);
723 if (nextItem) {
724 listItem->setY(nextItem->y() - listItem->height());
725 } else if (modelIndex == 0 && m_headerItem) {
726 listItem->setY(m_headerItem->height());
727 } else if (!m_visibleItems.isEmpty()) {
728 lostItem = true;
729 }
730 }
731 }
732 if (lostItem) {
733 releaseItem(listItem);
734 listItem = nullptr;
735 } else {
736 listItem->setCulled(listItem->y() + listItem->height() + m_clipItem->y() < contentY() || listItem->y() + m_clipItem->y() >= contentY() + height());
737 if (m_visibleItems.isEmpty()) {
738 m_visibleItems << listItem;
739 } else {
740 m_visibleItems.insert(modelIndex - m_firstVisibleIndex, listItem);
741 }
742 if (m_firstVisibleIndex < 0 || modelIndex < m_firstVisibleIndex) {
743 m_firstVisibleIndex = modelIndex;
744 polish();
745 }
746 adjustMinYExtent();
747 m_contentHeightDirty = true;
748 }
749 return listItem;
750 }
753#if (QT_VERSION < QT_VERSION_CHECK(5, 1, 0))
754void ListViewWithPageHeader::itemCreated(int modelIndex, QQuickItem *item)
756#else
757void ListViewWithPageHeader::itemCreated(int modelIndex, QObject *object)
759 QQuickItem *item = qmlobject_cast<QQuickItem*>(object);
760 if (!item) {
761 qWarning() << "ListViewWithPageHeader::itemCreated got a non item for index" << modelIndex;
762 return;
763 }
764#endif
765// qDebug() << "ListViewWithPageHeader::itemCreated" << modelIndex << item;
767 item->setParentItem(m_clipItem);
768 QQmlContext *context = QQmlEngine::contextForObject(item)->parentContext();
769 context->setContextProperty(QLatin1String("ListViewWithPageHeader"), this);
770 context->setContextProperty(QLatin1String("heightToClip"), QVariant::fromValue<int>(0));
771 if (modelIndex == m_asyncRequestedIndex) {
772 createItem(modelIndex, false);
773 refill();
774 }
777void ListViewWithPageHeader::updateClipItem()
779 m_clipItem->setHeight(height() - m_headerItemShownHeight);
780 m_clipItem->setY(contentY() + m_headerItemShownHeight);
781 m_clipItem->setClip(!m_forceNoClip && m_headerItemShownHeight > 0);
784void ListViewWithPageHeader::onContentHeightChanged()
786 updateClipItem();
789void ListViewWithPageHeader::onContentWidthChanged()
791 m_clipItem->setWidth(contentItem()->width());
794void ListViewWithPageHeader::onHeightChanged()
796 polish();
800#if (QT_VERSION < QT_VERSION_CHECK(5, 1, 0))
801void ListViewWithPageHeader::onModelUpdated(const QQuickChangeSet &changeSet, bool /*reset*/)
802#else
803void ListViewWithPageHeader::onModelUpdated(const QQmlChangeSet &changeSet, bool /*reset*/)
804#endif
806 // TODO Do something with reset
807// qDebug() << "ListViewWithPageHeader::onModelUpdated" << changeSet << reset;
808 const auto oldFirstVisibleIndex = m_firstVisibleIndex;
810#if (QT_VERSION < QT_VERSION_CHECK(5, 1, 0))
811 Q_FOREACH(const QQuickChangeSet::Remove &remove, changeSet.removes()) {
812#else
813 Q_FOREACH(const QQmlChangeSet::Remove &remove, changeSet.removes()) {
814#endif
815// qDebug() << "ListViewWithPageHeader::onModelUpdated Remove" << remove.index << remove.count;
816 if (remove.index + remove.count > m_firstVisibleIndex && remove.index < m_firstVisibleIndex + m_visibleItems.count()) {
817 const qreal oldFirstValidIndexPos = m_visibleItems.first()->y();
818 // If all the items we are removing are either not created or culled
819 // we have to grow down to avoid viewport changing
820 bool growDown = true;
821 for (int i = 0; growDown && i < remove.count; ++i) {
822 const int modelIndex = remove.index + i;
823 ListItem *item = itemAtIndex(modelIndex);
824 if (item && !item->culled()) {
825 growDown = false;
826 }
827 }
828 for (int i = remove.count - 1; i >= 0; --i) {
829 const int visibleIndex = remove.index + i - m_firstVisibleIndex;
830 if (visibleIndex >= 0 && visibleIndex < m_visibleItems.count()) {
831 ListItem *item = m_visibleItems[visibleIndex];
832 // Pass the section item down if needed
833 if (item->m_sectionItem && visibleIndex + 1 < m_visibleItems.count()) {
834 ListItem *nextItem = m_visibleItems[visibleIndex + 1];
835 if (!nextItem->m_sectionItem) {
836 nextItem->m_sectionItem = item->m_sectionItem;
837 item->m_sectionItem = nullptr;
838 }
839 }
840 releaseItem(item);
841 m_visibleItems.removeAt(visibleIndex);
842 }
843 }
844 if (growDown) {
845 adjustMinYExtent();
846 } else if (remove.index <= m_firstVisibleIndex) {
847 if (!m_visibleItems.isEmpty()) {
848 // We removed the first item that is the one that positions the rest
849 // position the new first item correctly
850 m_visibleItems.first()->setY(oldFirstValidIndexPos);
851 } else {
852 m_firstVisibleIndex = -1;
853 }
854 }
855 } else if (remove.index + remove.count <= m_firstVisibleIndex) {
856 m_firstVisibleIndex -= remove.count;
857 }
858 for (int i = remove.count - 1; i >= 0; --i) {
859 const int modelIndex = remove.index + i;
860 if (modelIndex == m_asyncRequestedIndex) {
861 m_asyncRequestedIndex = -1;
862 } else if (modelIndex < m_asyncRequestedIndex) {
863 m_asyncRequestedIndex--;
864 }
865 }
866 }
868#if (QT_VERSION < QT_VERSION_CHECK(5, 1, 0))
869 Q_FOREACH(const QQuickChangeSet::Insert &insert, changeSet.inserts()) {
870#else
871 Q_FOREACH(const QQmlChangeSet::Insert &insert, changeSet.inserts()) {
872#endif
873// qDebug() << "ListViewWithPageHeader::onModelUpdated Insert" << insert.index << insert.count;
874 const bool insertingInValidIndexes = insert.index > m_firstVisibleIndex && insert.index < m_firstVisibleIndex + m_visibleItems.count();
875 const bool firstItemWithViewOnTop = insert.index == 0 && m_firstVisibleIndex == 0 && m_visibleItems.first()->y() + m_clipItem->y() > contentY();
876 if (insertingInValidIndexes || firstItemWithViewOnTop)
877 {
878 // If the items we are adding won't be really visible
879 // we grow up instead of down to not change the viewport
880 bool growUp = false;
881 if (!firstItemWithViewOnTop) {
882 for (int i = 0; i < m_visibleItems.count(); ++i) {
883 if (!m_visibleItems[i]->culled()) {
884 if (insert.index <= m_firstVisibleIndex + i) {
885 growUp = true;
886 }
887 break;
888 }
889 }
890 }
892 const qreal oldFirstValidIndexPos = m_visibleItems.first()->y();
893 for (int i = insert.count - 1; i >= 0; --i) {
894 const int modelIndex = insert.index + i;
895 ListItem *item = createItem(modelIndex, false);
896 if (growUp) {
897 ListItem *firstItem = m_visibleItems.first();
898 firstItem->setY(firstItem->y() - item->height());
899 adjustMinYExtent();
900 }
901 // Adding an item may break a "same section" chain, so check
902 // if we need adding a new section item
903 if (m_sectionDelegate) {
904 ListItem *nextItem = itemAtIndex(modelIndex + 1);
905 if (nextItem && !nextItem->m_sectionItem) {
906 nextItem->m_sectionItem = getSectionItem(modelIndex + 1, true /* alredy inserted into m_visibleItems*/);
907 if (growUp && nextItem->m_sectionItem) {
908 ListItem *firstItem = m_visibleItems.first();
909 firstItem->setY(firstItem->y() - nextItem->m_sectionItem->height());
910 adjustMinYExtent();
911 }
912 }
913 }
914 }
915 if (firstItemWithViewOnTop) {
916 ListItem *firstItem = m_visibleItems.first();
917 firstItem->setY(oldFirstValidIndexPos);
918 }
919 } else if (insert.index <= m_firstVisibleIndex) {
920 m_firstVisibleIndex += insert.count;
921 }
923 for (int i = insert.count - 1; i >= 0; --i) {
924 const int modelIndex = insert.index + i;
925 if (modelIndex <= m_asyncRequestedIndex) {
926 m_asyncRequestedIndex++;
927 }
928 }
929 }
931 if (m_firstVisibleIndex != oldFirstVisibleIndex) {
932 adjustMinYExtent();
933 }
935 layout();
936 polish();
937 m_contentHeightDirty = true;
940void ListViewWithPageHeader::onShowHeaderAnimationFinished()
942 m_contentHeightDirty = true;
943 polish();
946void ListViewWithPageHeader::itemGeometryChanged(QQuickItem * /*item*/, const QRectF &newGeometry, const QRectF &oldGeometry)
948 const qreal heightDiff = newGeometry.height() - oldGeometry.height();
949 if (heightDiff != 0) {
950 if (oldGeometry.y() + oldGeometry.height() + m_clipItem->y() < contentY() && !m_visibleItems.isEmpty()) {
951 ListItem *firstItem = m_visibleItems.first();
952 firstItem->setY(firstItem->y() - heightDiff);
953 adjustMinYExtent();
954 layout();
955 }
956 refill();
957 adjustMinYExtent();
958 polish();
959 m_contentHeightDirty = true;
960 }
963void ListViewWithPageHeader::headerHeightChanged(qreal newHeaderHeight, qreal oldHeaderHeight, qreal oldHeaderY)
965 const qreal heightDiff = newHeaderHeight - oldHeaderHeight;
966 if (m_headerItemShownHeight > 0) {
967 // If the header is shown because of the clip
968 // Change its size
969 m_headerItemShownHeight += heightDiff;
970 m_headerItemShownHeight = qBound(static_cast<qreal>(0.), m_headerItemShownHeight, newHeaderHeight);
971 updateClipItem();
972 adjustMinYExtent();
973 } else {
974 if (oldHeaderY + oldHeaderHeight > contentY()) {
975 // If the header is shown because its position
976 // Change its size
977 ListItem *firstItem = m_visibleItems.first();
978 firstItem->setY(firstItem->y() + heightDiff);
979 layout();
980 } else {
981 // If the header is not on screen, just change the start of the list
982 // so the viewport is not changed
983 adjustMinYExtent();
984 }
985 }
989void ListViewWithPageHeader::adjustMinYExtent()
991 if (m_visibleItems.isEmpty()) {
992 m_minYExtent = 0;
993 } else {
994 qreal nonCreatedHeight = 0;
995 if (m_firstVisibleIndex != 0) {
996 // Calculate the average height of items to estimate the position of the list start
997 const int visibleItems = m_visibleItems.count();
998 qreal visibleItemsHeight = 0;
999 Q_FOREACH(ListItem *item, m_visibleItems) {
1000 visibleItemsHeight += item->height();
1002 nonCreatedHeight = m_firstVisibleIndex * visibleItemsHeight / visibleItems;
1003// qDebug() << m_firstVisibleIndex << visibleItemsHeight << visibleItems << nonCreatedHeight;
1005 m_minYExtent = nonCreatedHeight - m_visibleItems.first()->y() - m_clipItem->y() + (m_headerItem ? m_headerItem->implicitHeight() : 0);
1009ListViewWithPageHeader::ListItem *ListViewWithPageHeader::itemAtIndex(int modelIndex) const
1011 const int visibleIndexedModelIndex = modelIndex - m_firstVisibleIndex;
1012 if (visibleIndexedModelIndex >= 0 && visibleIndexedModelIndex < m_visibleItems.count())
1013 return m_visibleItems[visibleIndexedModelIndex];
1015 return nullptr;
1018void ListViewWithPageHeader::layout()
1020 if (m_inLayout)
1021 return;
1023 m_inLayout = true;
1024 if (!m_visibleItems.isEmpty()) {
1025 const qreal visibleFrom = contentY() - m_clipItem->y() + m_headerItemShownHeight;
1026 const qreal visibleTo = contentY() + height() - m_clipItem->y();
1028 qreal pos = m_visibleItems.first()->y();
1030// qDebug() << "ListViewWithPageHeader::layout Updating positions and heights. contentY" << contentY() << "minYExtent" << minYExtent();
1031 int firstReallyVisibleItem = -1;
1032 int modelIndex = m_firstVisibleIndex;
1033 Q_FOREACH(ListItem *item, m_visibleItems) {
1034 const bool cull = pos + item->height() < visibleFrom || pos >= visibleTo;
1035 item->setCulled(cull);
1036 item->setY(pos);
1037 if (!cull && firstReallyVisibleItem == -1) {
1038 firstReallyVisibleItem = modelIndex;
1039 if (m_topSectionItem) {
1040 // Update the top sticky section header
1041 const QString section = m_delegateModel->stringValue(modelIndex, m_sectionProperty);
1042 QQmlContext *context = QQmlEngine::contextForObject(m_topSectionItem)->parentContext();
1043 context->setContextProperty(QLatin1String("section"), section);
1045 // Positing the top section sticky item is a two step process
1046 // First we set it either we cull it (because it doesn't need to be sticked to the top)
1047 // or stick it to the top
1048 // Then after the loop we'll make sure that if there's another section just below it
1049 // pushed the sticky section up to make it disappear
1050 const qreal topSectionStickPos = m_headerItemShownHeight + contentY() - m_clipItem->y();
1051 if (topSectionStickPos <= pos) {
1052 QQuickItemPrivate::get(m_topSectionItem)->setCulled(true);
1053 if (item->m_sectionItem) {
1054 // This seems it should happen since why would we cull the top section
1055 // if the first visible item has no section header? This only happens briefly
1056 // when increasing the height of a list that is at the bottom, the m_topSectionItem
1057 // gets shown shortly in the next polish call
1058 QQuickItemPrivate::get(item->m_sectionItem)->setCulled(false);
1060 } else {
1061 QQuickItemPrivate::get(m_topSectionItem)->setCulled(false);
1062 m_topSectionItem->setY(topSectionStickPos);
1063 if (item->m_sectionItem) {
1064 QQuickItemPrivate::get(item->m_sectionItem)->setCulled(true);
1069 QQmlContext *context = QQmlEngine::contextForObject(item->m_item)->parentContext();
1070 const qreal clipFrom = visibleFrom + (!item->m_sectionItem && m_topSectionItem && !QQuickItemPrivate::get(m_topSectionItem)->culled ? m_topSectionItem->height() : 0);
1071 if (!cull && pos < clipFrom) {
1072 context->setContextProperty(QLatin1String("heightToClip"), clipFrom - pos);
1073 } else {
1074 context->setContextProperty(QLatin1String("heightToClip"), QVariant::fromValue<int>(0));
1076// qDebug() << "ListViewWithPageHeader::layout" << item->m_item;
1077 pos += item->height();
1078 ++modelIndex;
1081 // Second step of section sticky item positioning
1082 // Look at the next section header, check if it's pushing up the sticky one
1083 if (m_topSectionItem) {
1084 if (firstReallyVisibleItem >= 0) {
1085 for (int i = firstReallyVisibleItem - m_firstVisibleIndex + 1; i < m_visibleItems.count(); ++i) {
1086 ListItem *item = m_visibleItems[i];
1087 if (item->m_sectionItem) {
1088 if (m_topSectionItem->y() + m_topSectionItem->height() > item->y()) {
1089 m_topSectionItem->setY(item->y() - m_topSectionItem->height());
1091 break;
1097 m_inLayout = false;
1100void ListViewWithPageHeader::updatePolish()
1102 Q_FOREACH(ListItem *item, m_itemsToRelease)
1103 reallyReleaseItem(item);
1104 m_itemsToRelease.clear();
1106 if (!model())
1107 return;
1109 layout();
1111 refill();
1113 if (m_contentHeightDirty) {
1114 qreal contentHeight;
1115 if (m_visibleItems.isEmpty()) {
1116 contentHeight = m_headerItem ? m_headerItem->height() : 0;
1117 } else {
1118 const int modelCount = model()->rowCount();
1119 const int visibleItems = m_visibleItems.count();
1120 const int lastValidIndex = m_firstVisibleIndex + visibleItems - 1;
1121 qreal nonCreatedHeight = 0;
1122 if (lastValidIndex != modelCount - 1) {
1123 const int visibleItems = m_visibleItems.count();
1124 qreal visibleItemsHeight = 0;
1125 Q_FOREACH(ListItem *item, m_visibleItems) {
1126 visibleItemsHeight += item->height();
1128 const int unknownSizes = modelCount - (m_firstVisibleIndex + visibleItems);
1129 nonCreatedHeight = unknownSizes * visibleItemsHeight / visibleItems;
1131 ListItem *item = m_visibleItems.last();
1132 contentHeight = nonCreatedHeight + item->y() + item->height() + m_clipItem->y();
1133 if (m_firstVisibleIndex != 0) {
1134 // Make sure that if we are shrinking we tell the view we still fit
1135 m_minYExtent = qMax(m_minYExtent, -(contentHeight - height()));
1139 m_contentHeightDirty = false;
1140 setContentHeight(contentHeight);
1144#include "moc_listviewwithpageheader.cpp"