on 39fd092 help sign in
unity8/plugins/ListViewWithPageHeader/listviewwithpageheader.cpp
1059 lines 41 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#include <private/qquickvisualdatamodel_p.h>
98#include <private/qqmlglobal_p.h>
99#include <private/qquickitem_p.h>
100#include <private/qquickanimation_p.h>
101// #include <private/qquickrectangle_p.h>
103static const qreal bufferRatio = 0.5;
105qreal ListViewWithPageHeader::ListItem::height() const
107 return m_item->height() + (m_sectionItem ? m_sectionItem->height() : 0);
110qreal ListViewWithPageHeader::ListItem::y() const
112 return m_item->y() - (m_sectionItem ? m_sectionItem->height() : 0);
115void ListViewWithPageHeader::ListItem::setY(qreal newY)
117 if (m_sectionItem) {
118 m_sectionItem->setY(newY);
119 m_item->setY(newY + m_sectionItem->height());
120 } else {
121 m_item->setY(newY);
122 }
125bool ListViewWithPageHeader::ListItem::culled() const
127 return QQuickItemPrivate::get(m_item)->culled;
130void ListViewWithPageHeader::ListItem::setCulled(bool culled)
132 QQuickItemPrivate::get(m_item)->setCulled(culled);
133 if (m_sectionItem)
134 QQuickItemPrivate::get(m_sectionItem)->setCulled(culled);
137ListViewWithPageHeader::ListViewWithPageHeader()
138 : m_delegateModel(nullptr)
139 , m_asyncRequestedIndex(-1)
140 , m_delegateValidated(false)
141 , m_firstVisibleIndex(-1)
142 , m_minYExtent(0)
143 , m_contentHeightDirty(false)
144 , m_headerItem(nullptr)
145 , m_previousContentY(0)
146 , m_headerItemShownHeight(0)
147 , m_sectionDelegate(nullptr)
148 , m_topSectionItem(nullptr)
149 , m_forceNoClip(false)
150 , m_inLayout(false)
152 m_clipItem = new QQuickItem(contentItem());
153// m_clipItem = new QQuickRectangle(contentItem());
154// ((QQuickRectangle*)m_clipItem)->setColor(Qt::gray);
156 m_headerShowAnimation = new QQuickNumberAnimation(this);
157 m_headerShowAnimation->setEasing(QEasingCurve::OutQuad);
158 m_headerShowAnimation->setProperty("contentY");
159 m_headerShowAnimation->setDuration(200);
160 m_headerShowAnimation->setTargetObject(this);
162 connect(this, SIGNAL(contentWidthChanged()), this, SLOT(onContentWidthChanged()));
163 connect(this, SIGNAL(contentHeightChanged()), this, SLOT(onContentHeightChanged()));
164 connect(this, SIGNAL(heightChanged()), this, SLOT(onHeightChanged()));
165 connect(m_headerShowAnimation, SIGNAL(stopped()), this, SLOT(onShowHeaderAnimationFinished()));
168ListViewWithPageHeader::~ListViewWithPageHeader()
172QAbstractItemModel *ListViewWithPageHeader::model() const
174 return m_delegateModel ? m_delegateModel->model().value<QAbstractItemModel *>() : nullptr;
177void ListViewWithPageHeader::setModel(QAbstractItemModel *model)
179 if (model != this->model()) {
180 if (!m_delegateModel) {
181 createDelegateModel();
182 } else {
183 disconnect(m_delegateModel, SIGNAL(modelUpdated(QQuickChangeSet,bool)), this, SLOT(onModelUpdated(QQuickChangeSet,bool)));
184 }
185 m_delegateModel->setModel(QVariant::fromValue<QAbstractItemModel *>(model));
186 connect(m_delegateModel, SIGNAL(modelUpdated(QQuickChangeSet,bool)), this, SLOT(onModelUpdated(QQuickChangeSet,bool)));
187 Q_EMIT modelChanged();
188 // TODO?
189// Q_EMIT contentHeightChanged();
190// Q_EMIT contentYChanged();
191 }
194QQmlComponent *ListViewWithPageHeader::delegate() const
196 return m_delegateModel ? m_delegateModel->delegate() : nullptr;
199void ListViewWithPageHeader::setDelegate(QQmlComponent *delegate)
201 if (delegate != this->delegate()) {
202 if (!m_delegateModel) {
203 createDelegateModel();
204 }
206 // Cleanup the existing items
207 Q_FOREACH(ListItem *item, m_visibleItems)
208 releaseItem(item);
209 m_visibleItems.clear();
210 m_firstVisibleIndex = -1;
211 adjustMinYExtent();
212 setContentY(0);
213 m_clipItem->setY(0);
214 if (m_topSectionItem) {
215 QQuickItemPrivate::get(m_topSectionItem)->setCulled(true);
216 }
218 m_delegateModel->setDelegate(delegate);
220 Q_EMIT delegateChanged();
221 m_delegateValidated = false;
222 m_contentHeightDirty = true;
223 polish();
224 }
227QQuickItem *ListViewWithPageHeader::header() const
229 return m_headerItem;
232void ListViewWithPageHeader::setHeader(QQuickItem *headerItem)
234 if (m_headerItem != headerItem) {
235 qreal oldHeaderHeight = 0;
236 qreal oldHeaderY = 0;
237 if (m_headerItem) {
238 oldHeaderHeight = m_headerItem->height();
239 oldHeaderY = m_headerItem->y();
240 m_headerItem->setParentItem(nullptr);
241 }
242 m_headerItem = headerItem;
243 if (m_headerItem) {
244 m_headerItem->setParentItem(contentItem());
245 m_headerItem->setZ(1);
246 }
247 qreal newHeaderHeight = m_headerItem ? m_headerItem->height() : 0;
248 if (!m_visibleItems.isEmpty() && newHeaderHeight != oldHeaderHeight) {
249 headerHeightChanged(newHeaderHeight, oldHeaderHeight, oldHeaderY);
250 polish();
251 m_contentHeightDirty = true;
252 }
253 Q_EMIT headerChanged();
254 }
257QQmlComponent *ListViewWithPageHeader::sectionDelegate() const
259 return m_sectionDelegate;
262void ListViewWithPageHeader::setSectionDelegate(QQmlComponent *delegate)
264 if (delegate != m_sectionDelegate) {
265 // TODO clean existing sections
267 m_sectionDelegate = delegate;
269 m_topSectionItem = getSectionItem(QString());
270 m_topSectionItem->setZ(3);
271 QQuickItemPrivate::get(m_topSectionItem)->setCulled(true);
273 // TODO create sections for existing items
275 Q_EMIT sectionDelegateChanged();
276 }
279QString ListViewWithPageHeader::sectionProperty() const
281 return m_sectionProperty;
284void ListViewWithPageHeader::setSectionProperty(const QString &property)
286 if (property != m_sectionProperty) {
287 m_sectionProperty = property;
289 updateWatchedRoles();
291 // TODO recreate sections
293 Q_EMIT sectionPropertyChanged();
294 }
297bool ListViewWithPageHeader::forceNoClip() const
299 return m_forceNoClip;
302void ListViewWithPageHeader::setForceNoClip(bool noClip)
304 if (noClip != m_forceNoClip) {
305 m_forceNoClip = noClip;
306 updateClipItem();
307 Q_EMIT forceNoClipChanged();
308 }
311void ListViewWithPageHeader::positionAtBeginning()
313 qreal headerHeight = (m_headerItem ? m_headerItem->height() : 0);
314 if (m_firstVisibleIndex != 0) {
315 // TODO This could be optimized by trying to reuse the interesection
316 // of items that may end up intersecting between the existing
317 // m_visibleItems and the items we are creating in the next loop
318 Q_FOREACH(ListItem *item, m_visibleItems)
319 releaseItem(item);
320 m_visibleItems.clear();
321 m_firstVisibleIndex = -1;
323 // Create the item 0, it will be already correctly positioned at createItem()
324 m_clipItem->setY(0);
325 ListItem *item = createItem(0, false);
326 // Create the subsequent items
327 int modelIndex = 1;
328 qreal pos = item->y() + item->height();
329 const qreal buffer = height() * bufferRatio;
330 const qreal bufferTo = height() + buffer;
331 while (modelIndex < m_delegateModel->count() && pos <= bufferTo) {
332 if (!(item = createItem(modelIndex, false)))
333 break;
334 pos += item->height();
335 ++modelIndex;
336 }
338 m_previousContentY = m_visibleItems.first()->y() - headerHeight;
339 }
340 setContentY(m_visibleItems.first()->y() + m_clipItem->y() - headerHeight);
343void ListViewWithPageHeader::showHeader()
345 auto to = qMax(-minYExtent(), contentY() - m_headerItem->height() + m_headerItemShownHeight);
346 if (to != contentY()) {
347 m_headerShowAnimation->setTo(to);
348 m_headerShowAnimation->start();
349 }
352qreal ListViewWithPageHeader::minYExtent() const
354// qDebug() << "ListViewWithPageHeader::minYExtent" << m_minYExtent;
355 return m_minYExtent;
358void ListViewWithPageHeader::componentComplete()
360 if (m_delegateModel)
361 m_delegateModel->componentComplete();
363 QQuickFlickable::componentComplete();
365 polish();
368void ListViewWithPageHeader::viewportMoved(Qt::Orientations orient)
370 QQuickFlickable::viewportMoved(orient);
371// qDebug() << "ListViewWithPageHeader::viewportMoved" << contentY();
372 qreal diff = m_previousContentY - contentY();
373 if (m_headerItem) {
374 auto oldHeaderItemShownHeight = m_headerItemShownHeight;
375 if (contentY() < -m_minYExtent) {
376 // Stick the header item to the top when dragging down
377 m_headerItem->setY(contentY());
378 m_headerItem->setHeight(m_headerItem->implicitHeight() + (-m_minYExtent - contentY()));
379 } else {
380 m_headerItem->setHeight(m_headerItem->implicitHeight());
381 // We are going down (but it's not because of the rebound at the end)
382 // (but the header was not shown by it's own position)
383 // or the header is partially shown
384 const bool scrolledUp = m_previousContentY > contentY();
385 const bool notRebounding = contentY() + height() < contentHeight();
386 const bool notShownByItsOwn = contentY() + diff > m_headerItem->y() + m_headerItem->height();
388 if (!scrolledUp && contentY() == -m_minYExtent) {
389 m_headerItemShownHeight = 0;
390 m_headerItem->setY(contentY());
391 } else if ((scrolledUp && notRebounding && notShownByItsOwn) || (m_headerItemShownHeight > 0)) {
392 m_headerItemShownHeight += diff;
393 if (contentY() == -m_minYExtent) {
394 m_headerItemShownHeight = 0;
395 } else {
396 m_headerItemShownHeight = qBound(static_cast<qreal>(0.), m_headerItemShownHeight, m_headerItem->height());
397 }
398 if (m_headerItemShownHeight > 0) {
399 m_headerItem->setY(contentY() - m_headerItem->height() + m_headerItemShownHeight);
400 } else {
401 m_headerItem->setY(-m_minYExtent);
402 }
403 }
404 }
405 // We will be changing the clip item, need to accomadate for it
406 // otherwise we move the firstItem down/up twice (unless the
407 // show header animation is running, where we want to keep the viewport stable)
408 if (!m_headerShowAnimation->isRunning()) {
409 diff += oldHeaderItemShownHeight - m_headerItemShownHeight;
410 } else {
411 diff = -diff;
412 }
413 }
414 if (!m_visibleItems.isEmpty()) {
415 updateClipItem();
416 ListItem *firstItem = m_visibleItems.first();
417 firstItem->setY(firstItem->y() + diff);
418 if (m_headerShowAnimation->isRunning()) {
419 adjustMinYExtent();
420 }
421 }
423 m_previousContentY = contentY();
424 layout();
425 polish();
428void ListViewWithPageHeader::createDelegateModel()
430 m_delegateModel = new QQuickVisualDataModel(qmlContext(this), this);
431 connect(m_delegateModel, SIGNAL(createdItem(int,QQuickItem*)), this, SLOT(itemCreated(int,QQuickItem*)));
432 if (isComponentComplete())
433 m_delegateModel->componentComplete();
434 updateWatchedRoles();
437void ListViewWithPageHeader::refill()
439 if (m_inLayout) {
440 return;
441 }
442 if (!isComponentComplete()) {
443 return;
444 }
446 const qreal buffer = height() * bufferRatio;
447 const qreal from = contentY();
448 const qreal to = from + height();
449 const qreal bufferFrom = from - buffer;
450 const qreal bufferTo = to + buffer;
452 bool added = addVisibleItems(from, to, false);
453 bool removed = removeNonVisibleItems(bufferFrom, bufferTo);
454 added |= addVisibleItems(bufferFrom, bufferTo, true);
456 if (added || removed) {
457 m_contentHeightDirty = true;
458 }
461bool ListViewWithPageHeader::addVisibleItems(qreal fillFrom, qreal fillTo, bool asynchronous)
463 if (!delegate())
464 return false;
466 if (m_delegateModel->count() == 0)
467 return false;
469 ListItem *item;
470// qDebug() << "ListViewWithPageHeader::addVisibleItems" << fillFrom << fillTo << asynchronous;
472 int modelIndex = 0;
473 qreal pos = 0;
474 if (!m_visibleItems.isEmpty()) {
475 modelIndex = m_firstVisibleIndex + m_visibleItems.count();
476 item = m_visibleItems.last();
477 pos = item->y() + item->height() + m_clipItem->y();
478 }
479 bool changed = false;
480// qDebug() << (modelIndex < m_delegateModel->count()) << pos << fillTo;
481 while (modelIndex < m_delegateModel->count() && pos <= fillTo) {
482// qDebug() << "refill: append item" << modelIndex << "pos" << pos << "asynchronous" << asynchronous;
483 if (!(item = createItem(modelIndex, asynchronous)))
484 break;
485 pos += item->height();
486 ++modelIndex;
487 changed = true;
488 }
490 modelIndex = 0;
491 pos = 0;
492 if (!m_visibleItems.isEmpty()) {
493 modelIndex = m_firstVisibleIndex - 1;
494 item = m_visibleItems.first();
495 pos = item->y() + m_clipItem->y();
496 }
497 while (modelIndex >= 0 && pos > fillFrom) {
498// qDebug() << "refill: prepend item" << modelIndex << "pos" << pos << "fillFrom" << fillFrom << "asynchronous" << asynchronous;
499 if (!(item = createItem(modelIndex, asynchronous)))
500 break;
501 pos -= item->height();
502 --modelIndex;
503 changed = true;
504 }
506 return changed;
509void ListViewWithPageHeader::reallyReleaseItem(ListItem *listItem)
511 QQuickItem *item = listItem->m_item;
512 QQuickVisualModel::ReleaseFlags flags = m_delegateModel->release(item);
513 if (flags & QQuickVisualModel::Destroyed) {
514 item->setParentItem(nullptr);
515 }
516 delete listItem->m_sectionItem;
517 delete listItem;
520void ListViewWithPageHeader::releaseItem(ListItem *listItem)
522 QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(listItem->m_item);
523 itemPrivate->removeItemChangeListener(this, QQuickItemPrivate::Geometry);
524 m_itemsToRelease << listItem;
527void ListViewWithPageHeader::updateWatchedRoles()
529 if (m_delegateModel) {
530 QList<QByteArray> roles;
531 if (!m_sectionProperty.isEmpty())
532 roles << m_sectionProperty.toUtf8();
533 m_delegateModel->setWatchedRoles(roles);
534 }
537QQuickItem *ListViewWithPageHeader::getSectionItem(int modelIndex, bool alreadyInserted)
539 if (!m_sectionDelegate)
540 return nullptr;
542 const QString section = m_delegateModel->stringValue(modelIndex, m_sectionProperty);
543 if (modelIndex > 0) {
544 const QString prevSection = m_delegateModel->stringValue(modelIndex - 1, m_sectionProperty);
545 if (section == prevSection)
546 return nullptr;
547 }
548 if (modelIndex + 1 < model()->rowCount() && !alreadyInserted) {
549 // Already inserted items can't steal next section header
550 const QString nextSection = m_delegateModel->stringValue(modelIndex + 1, m_sectionProperty);
551 if (section == nextSection) {
552 // Steal the section header
553 ListItem *nextItem = itemAtIndex(modelIndex); // Not +1 since not yet inserted into m_visibleItems
554 if (nextItem) {
555 QQuickItem *sectionItem = nextItem->m_sectionItem;
556 nextItem->m_sectionItem = nullptr;
557 return sectionItem;
558 }
559 }
560 }
562 return getSectionItem(section);
565QQuickItem *ListViewWithPageHeader::getSectionItem(const QString &sectionText)
567 QQuickItem *sectionItem = nullptr;
569 QQmlContext *creationContext = m_sectionDelegate->creationContext();
570 QQmlContext *context = new QQmlContext(creationContext ? creationContext : qmlContext(this));
571 context->setContextProperty(QLatin1String("section"), sectionText);
572 QObject *nobj = m_sectionDelegate->beginCreate(context);
573 if (nobj) {
574 QQml_setParent_noEvent(context, nobj);
575 sectionItem = qobject_cast<QQuickItem *>(nobj);
576 if (!sectionItem) {
577 delete nobj;
578 } else {
579 sectionItem->setZ(2);
580 QQml_setParent_noEvent(sectionItem, m_clipItem);
581 sectionItem->setParentItem(m_clipItem);
582 }
583 } else {
584 delete context;
585 }
586 m_sectionDelegate->completeCreate();
588 // TODO attach to sectionItem so we can accomodate to it changing its height
590 return sectionItem;
593bool ListViewWithPageHeader::removeNonVisibleItems(qreal bufferFrom, qreal bufferTo)
595// qDebug() << "ListViewWithPageHeader::removeNonVisibleItems" << bufferFrom << bufferTo;
596 // Do not remove items if we are overshooting up or down, since we'll come back
597 // to the "stable" position and delete/create items without any reason
598 if (contentY() < -m_minYExtent) {
599 return false;
600 } else if (contentY() + height() > contentHeight()) {
601 return false;
602 }
603 bool changed = false;
605 bool foundVisible = false;
606 int i = 0;
607 int removedItems = 0;
608 const auto oldFirstVisibleIndex = m_firstVisibleIndex;
609 while (i < m_visibleItems.count()) {
610 ListItem *item = m_visibleItems[i];
611 const qreal pos = item->y() + m_clipItem->y();
612// qDebug() << i << pos << (pos + item->height()) << bufferFrom << bufferTo;
613 if (pos + item->height() < bufferFrom || pos > bufferTo) {
614// qDebug() << "Releasing" << i << (pos + item->height() < bufferFrom) << pos + item->height() << bufferFrom << (pos > bufferTo) << pos << bufferTo;
615 releaseItem(item);
616 m_visibleItems.removeAt(i);
617 changed = true;
618 ++removedItems;
619 } else {
620 if (!foundVisible) {
621 foundVisible = true;
622 const int itemIndex = m_firstVisibleIndex + removedItems + i;
623 m_firstVisibleIndex = itemIndex;
624 }
625 ++i;
626 }
627 }
628 if (m_firstVisibleIndex != oldFirstVisibleIndex) {
629 adjustMinYExtent();
630 }
632 return changed;
635ListViewWithPageHeader::ListItem *ListViewWithPageHeader::createItem(int modelIndex, bool asynchronous)
637// qDebug() << "CREATE ITEM" << modelIndex;
638 if (asynchronous && m_asyncRequestedIndex != -1)
639 return nullptr;
641 m_asyncRequestedIndex = -1;
642 QQuickItem *item = m_delegateModel->item(modelIndex, asynchronous);
643 if (!item) {
644 m_asyncRequestedIndex = modelIndex;
645 return 0;
646 } else {
647// qDebug() << "ListViewWithPageHeader::createItem::We have the item" << modelIndex << item;
648 ListItem *listItem = new ListItem;
649 listItem->m_item = item;
650 listItem->m_sectionItem = getSectionItem(modelIndex, false /*Not yet inserted into m_visibleItems*/);
651 QQuickItemPrivate::get(item)->addItemChangeListener(this, QQuickItemPrivate::Geometry);
652 ListItem *prevItem = itemAtIndex(modelIndex - 1);
653 bool lostItem = false; // Is an item that we requested async but because of model changes
654 // it is no longer attached to any of the existing items (has no prev nor next item)
655 // nor is the first item
656 if (prevItem) {
657 listItem->setY(prevItem->y() + prevItem->height());
658 } else {
659 ListItem *currItem = itemAtIndex(modelIndex);
660 if (currItem) {
661 // There's something already in m_visibleItems at out index, meaning this is an insert, so attach to its top
662 listItem->setY(currItem->y() - listItem->height());
663 } else {
664 ListItem *nextItem = itemAtIndex(modelIndex + 1);
665 if (nextItem) {
666 listItem->setY(nextItem->y() - listItem->height());
667 } else if (modelIndex == 0 && m_headerItem) {
668 listItem->setY(m_headerItem->height());
669 } else if (!m_visibleItems.isEmpty()) {
670 lostItem = true;
671 }
672 }
673 }
674 if (lostItem) {
675 releaseItem(listItem);
676 listItem = nullptr;
677 } else {
678 listItem->setCulled(listItem->y() + listItem->height() + m_clipItem->y() < contentY() || listItem->y() + m_clipItem->y() >= contentY() + height());
679 if (m_visibleItems.isEmpty()) {
680 m_visibleItems << listItem;
681 } else {
682 m_visibleItems.insert(modelIndex - m_firstVisibleIndex, listItem);
683 }
684 if (m_firstVisibleIndex < 0 || modelIndex < m_firstVisibleIndex) {
685 m_firstVisibleIndex = modelIndex;
686 polish();
687 }
688 adjustMinYExtent();
689 m_contentHeightDirty = true;
690 }
691 return listItem;
692 }
695void ListViewWithPageHeader::itemCreated(int modelIndex, QQuickItem *item)
697// qDebug() << "ListViewWithPageHeader::itemCreated" << modelIndex << item;
699 item->setParentItem(m_clipItem);
700 QQmlContext *context = QQmlEngine::contextForObject(item)->parentContext();
701 context->setContextProperty(QLatin1String("ListViewWithPageHeader"), this);
702 context->setContextProperty(QLatin1String("heightToClip"), QVariant::fromValue<int>(0));
703 if (modelIndex == m_asyncRequestedIndex) {
704 createItem(modelIndex, false);
705 refill();
706 }
709void ListViewWithPageHeader::updateClipItem()
711 m_clipItem->setHeight(height() - m_headerItemShownHeight);
712 m_clipItem->setY(contentY() + m_headerItemShownHeight);
713 m_clipItem->setClip(!m_forceNoClip && m_headerItemShownHeight > 0);
716void ListViewWithPageHeader::onContentHeightChanged()
718 updateClipItem();
721void ListViewWithPageHeader::onContentWidthChanged()
723 m_clipItem->setWidth(contentItem()->width());
726void ListViewWithPageHeader::onHeightChanged()
728 polish();
731void ListViewWithPageHeader::onModelUpdated(const QQuickChangeSet &changeSet, bool /*reset*/)
733 // TODO Do something with reset
734// qDebug() << "ListViewWithPageHeader::onModelUpdated" << changeSet << reset;
735 const auto oldFirstVisibleIndex = m_firstVisibleIndex;
737 Q_FOREACH(const QQuickChangeSet::Remove &remove, changeSet.removes()) {
738// qDebug() << "ListViewWithPageHeader::onModelUpdated Remove" << remove.index << remove.count;
739 if (remove.index + remove.count > m_firstVisibleIndex && remove.index < m_firstVisibleIndex + m_visibleItems.count()) {
740 const qreal oldFirstValidIndexPos = m_visibleItems.first()->y();
741 // If all the items we are removing are either not created or culled
742 // we have to grow down to avoid viewport changing
743 bool growDown = true;
744 for (int i = 0; growDown && i < remove.count; ++i) {
745 const int modelIndex = remove.index + i;
746 ListItem *item = itemAtIndex(modelIndex);
747 if (item && !item->culled()) {
748 growDown = false;
749 }
750 }
751 for (int i = remove.count - 1; i >= 0; --i) {
752 const int visibleIndex = remove.index + i - m_firstVisibleIndex;
753 if (visibleIndex >= 0 && visibleIndex < m_visibleItems.count()) {
754 ListItem *item = m_visibleItems[visibleIndex];
755 // Pass the section item down if needed
756 if (item->m_sectionItem && visibleIndex + 1 < m_visibleItems.count()) {
757 ListItem *nextItem = m_visibleItems[visibleIndex + 1];
758 if (!nextItem->m_sectionItem) {
759 nextItem->m_sectionItem = item->m_sectionItem;
760 item->m_sectionItem = nullptr;
761 }
762 }
763 releaseItem(item);
764 m_visibleItems.removeAt(visibleIndex);
765 }
766 }
767 if (growDown) {
768 adjustMinYExtent();
769 } else if (remove.index <= m_firstVisibleIndex && !m_visibleItems.isEmpty()) {
770 // We removed the first item that is the one that positions the rest
771 // position the new first item correctly
772 m_visibleItems.first()->setY(oldFirstValidIndexPos);
773 }
774 } else if (remove.index + remove.count <= m_firstVisibleIndex) {
775 m_firstVisibleIndex -= remove.count;
776 }
777 for (int i = remove.count - 1; i >= 0; --i) {
778 const int modelIndex = remove.index + i;
779 if (modelIndex == m_asyncRequestedIndex) {
780 m_asyncRequestedIndex = -1;
781 } else if (modelIndex < m_asyncRequestedIndex) {
782 m_asyncRequestedIndex--;
783 }
784 }
785 }
787 Q_FOREACH(const QQuickChangeSet::Insert &insert, changeSet.inserts()) {
788// qDebug() << "ListViewWithPageHeader::onModelUpdated Insert" << insert.index << insert.count;
789 const bool insertingInValidIndexes = insert.index > m_firstVisibleIndex && insert.index < m_firstVisibleIndex + m_visibleItems.count();
790 const bool firstItemWithViewOnTop = insert.index == 0 && m_firstVisibleIndex == 0 && m_visibleItems.first()->y() + m_clipItem->y() > contentY();
791 if (insertingInValidIndexes || firstItemWithViewOnTop)
792 {
793 // If the items we are adding won't be really visible
794 // we grow up instead of down to not change the viewport
795 bool growUp = false;
796 if (!firstItemWithViewOnTop) {
797 for (int i = 0; i < m_visibleItems.count(); ++i) {
798 if (!m_visibleItems[i]->culled()) {
799 if (insert.index <= m_firstVisibleIndex + i) {
800 growUp = true;
801 }
802 break;
803 }
804 }
805 }
807 const qreal oldFirstValidIndexPos = m_visibleItems.first()->y();
808 for (int i = insert.count - 1; i >= 0; --i) {
809 const int modelIndex = insert.index + i;
810 ListItem *item = createItem(modelIndex, false);
811 if (growUp) {
812 ListItem *firstItem = m_visibleItems.first();
813 firstItem->setY(firstItem->y() - item->height());
814 adjustMinYExtent();
815 }
816 // Adding an item may break a "same section" chain, so check
817 // if we need adding a new section item
818 if (m_sectionDelegate) {
819 ListItem *nextItem = itemAtIndex(modelIndex + 1);
820 if (nextItem && !nextItem->m_sectionItem) {
821 nextItem->m_sectionItem = getSectionItem(modelIndex + 1, true /* alredy inserted into m_visibleItems*/);
822 if (growUp && nextItem->m_sectionItem) {
823 ListItem *firstItem = m_visibleItems.first();
824 firstItem->setY(firstItem->y() - nextItem->m_sectionItem->height());
825 adjustMinYExtent();
826 }
827 }
828 }
829 }
830 if (firstItemWithViewOnTop) {
831 ListItem *firstItem = m_visibleItems.first();
832 firstItem->setY(oldFirstValidIndexPos);
833 }
834 } else if (insert.index <= m_firstVisibleIndex) {
835 m_firstVisibleIndex += insert.count;
836 }
838 for (int i = insert.count - 1; i >= 0; --i) {
839 const int modelIndex = insert.index + i;
840 if (modelIndex <= m_asyncRequestedIndex) {
841 m_asyncRequestedIndex++;
842 }
843 }
844 }
846 if (m_firstVisibleIndex != oldFirstVisibleIndex) {
847 adjustMinYExtent();
848 }
850 layout();
851 polish();
852 m_contentHeightDirty = true;
855void ListViewWithPageHeader::onShowHeaderAnimationFinished()
857 m_contentHeightDirty = true;
858 polish();
861void ListViewWithPageHeader::itemGeometryChanged(QQuickItem * /*item*/, const QRectF &newGeometry, const QRectF &oldGeometry)
863 const qreal heightDiff = newGeometry.height() - oldGeometry.height();
864 if (heightDiff != 0) {
865 if (oldGeometry.y() + oldGeometry.height() + m_clipItem->y() < contentY() && !m_visibleItems.isEmpty()) {
866 ListItem *firstItem = m_visibleItems.first();
867 firstItem->setY(firstItem->y() - heightDiff);
868 adjustMinYExtent();
869 layout();
870 }
871 refill();
872 adjustMinYExtent();
873 polish();
874 m_contentHeightDirty = true;
875 }
878void ListViewWithPageHeader::headerHeightChanged(qreal newHeaderHeight, qreal oldHeaderHeight, qreal oldHeaderY)
880 const qreal heightDiff = newHeaderHeight - oldHeaderHeight;
881 if (m_headerItemShownHeight > 0) {
882 // If the header is shown because of the clip
883 // Change its size
884 m_headerItemShownHeight += heightDiff;
885 m_headerItemShownHeight = qBound(static_cast<qreal>(0.), m_headerItemShownHeight, newHeaderHeight);
886 updateClipItem();
887 adjustMinYExtent();
888 } else {
889 if (oldHeaderY + oldHeaderHeight > contentY()) {
890 // If the header is shown because its position
891 // Change its size
892 ListItem *firstItem = m_visibleItems.first();
893 firstItem->setY(firstItem->y() + heightDiff);
894 layout();
895 } else {
896 // If the header is not on screen, just change the start of the list
897 // so the viewport is not changed
898 adjustMinYExtent();
899 }
900 }
904void ListViewWithPageHeader::adjustMinYExtent()
906 if (m_visibleItems.isEmpty()) {
907 m_minYExtent = 0;
908 } else {
909 qreal nonCreatedHeight = 0;
910 if (m_firstVisibleIndex != 0) {
911 // Calculate the average height of items to estimate the position of the list start
912 const int visibleItems = m_visibleItems.count();
913 qreal visibleItemsHeight = 0;
914 Q_FOREACH(ListItem *item, m_visibleItems) {
915 visibleItemsHeight += item->height();
916 }
917 nonCreatedHeight = m_firstVisibleIndex * visibleItemsHeight / visibleItems;
918// qDebug() << m_firstVisibleIndex << visibleItemsHeight << visibleItems << nonCreatedHeight;
919 }
920 m_minYExtent = nonCreatedHeight - m_visibleItems.first()->y() - m_clipItem->y() + (m_headerItem ? m_headerItem->implicitHeight() : 0);
921 }
924ListViewWithPageHeader::ListItem *ListViewWithPageHeader::itemAtIndex(int modelIndex) const
926 const int visibleIndexedModelIndex = modelIndex - m_firstVisibleIndex;
927 if (visibleIndexedModelIndex >= 0 && visibleIndexedModelIndex < m_visibleItems.count())
928 return m_visibleItems[visibleIndexedModelIndex];
930 return nullptr;
933void ListViewWithPageHeader::layout()
935 if (m_inLayout)
936 return;
938 m_inLayout = true;
939 if (!m_visibleItems.isEmpty()) {
940 const qreal visibleFrom = contentY() - m_clipItem->y() + m_headerItemShownHeight;
941 const qreal visibleTo = contentY() + height() - m_clipItem->y();
943 qreal pos = m_visibleItems.first()->y();
945// qDebug() << "ListViewWithPageHeader::layout Updating positions and heights. contentY" << contentY() << "minYExtent" << minYExtent();
946 int firstReallyVisibleItem = -1;
947 int modelIndex = m_firstVisibleIndex;
948 Q_FOREACH(ListItem *item, m_visibleItems) {
949 const bool cull = pos + item->height() < visibleFrom || pos >= visibleTo;
950 item->setCulled(cull);
951 item->setY(pos);
952 if (!cull && firstReallyVisibleItem == -1) {
953 firstReallyVisibleItem = modelIndex;
954 if (m_topSectionItem) {
955 // Update the top sticky section header
956 const QString section = m_delegateModel->stringValue(modelIndex, m_sectionProperty);
957 QQmlContext *context = QQmlEngine::contextForObject(m_topSectionItem)->parentContext();
958 context->setContextProperty(QLatin1String("section"), section);
960 // Positing the top section sticky item is a two step process
961 // First we set it either we cull it (because it doesn't need to be sticked to the top)
962 // or stick it to the top
963 // Then after the loop we'll make sure that if there's another section just below it
964 // pushed the sticky section up to make it disappear
965 const qreal topSectionStickPos = m_headerItemShownHeight + contentY() - m_clipItem->y();
966 if (topSectionStickPos <= pos) {
967 QQuickItemPrivate::get(m_topSectionItem)->setCulled(true);
968 if (item->m_sectionItem) {
969 // This seems it should happen since why would we cull the top section
970 // if the first visible item has no section header? This only happens briefly
971 // when increasing the height of a list that is at the bottom, the m_topSectionItem
972 // gets shown shortly in the next polish call
973 QQuickItemPrivate::get(item->m_sectionItem)->setCulled(false);
974 }
975 } else {
976 QQuickItemPrivate::get(m_topSectionItem)->setCulled(false);
977 m_topSectionItem->setY(topSectionStickPos);
978 if (item->m_sectionItem) {
979 QQuickItemPrivate::get(item->m_sectionItem)->setCulled(true);
980 }
981 }
982 }
983 }
984 QQmlContext *context = QQmlEngine::contextForObject(item->m_item)->parentContext();
985 const qreal clipFrom = visibleFrom + (!item->m_sectionItem && m_topSectionItem && !QQuickItemPrivate::get(m_topSectionItem)->culled ? m_topSectionItem->height() : 0);
986 if (!cull && pos < clipFrom) {
987 context->setContextProperty(QLatin1String("heightToClip"), clipFrom - pos);
988 } else {
989 context->setContextProperty(QLatin1String("heightToClip"), QVariant::fromValue<int>(0));
990 }
991// qDebug() << "ListViewWithPageHeader::layout" << item->m_item;
992 pos += item->height();
993 ++modelIndex;
994 }
996 // Second step of section sticky item positioning
997 // Look at the next section header, check if it's pushing up the sticky one
998 if (m_topSectionItem) {
999 if (firstReallyVisibleItem >= 0) {
1000 for (int i = firstReallyVisibleItem - m_firstVisibleIndex + 1; i < m_visibleItems.count(); ++i) {
1001 ListItem *item = m_visibleItems[i];
1002 if (item->m_sectionItem) {
1003 if (m_topSectionItem->y() + m_topSectionItem->height() > item->y()) {
1004 m_topSectionItem->setY(item->y() - m_topSectionItem->height());
1006 break;
1012 m_inLayout = false;
1015void ListViewWithPageHeader::updatePolish()
1017 Q_FOREACH(ListItem *item, m_itemsToRelease)
1018 reallyReleaseItem(item);
1019 m_itemsToRelease.clear();
1021 if (!model())
1022 return;
1024 layout();
1026 refill();
1028 if (m_contentHeightDirty) {
1029 qreal contentHeight;
1030 if (m_visibleItems.isEmpty()) {
1031 contentHeight = m_headerItem ? m_headerItem->height() : 0;
1032 } else {
1033 const int modelCount = model()->rowCount();
1034 const int visibleItems = m_visibleItems.count();
1035 const int lastValidIndex = m_firstVisibleIndex + visibleItems - 1;
1036 qreal nonCreatedHeight = 0;
1037 if (lastValidIndex != modelCount - 1) {
1038 const int visibleItems = m_visibleItems.count();
1039 qreal visibleItemsHeight = 0;
1040 Q_FOREACH(ListItem *item, m_visibleItems) {
1041 visibleItemsHeight += item->height();
1043 const int unknownSizes = modelCount - (m_firstVisibleIndex + visibleItems);
1044 nonCreatedHeight = unknownSizes * visibleItemsHeight / visibleItems;
1046 ListItem *item = m_visibleItems.last();
1047 contentHeight = nonCreatedHeight + item->y() + item->height() + m_clipItem->y();
1048 if (m_firstVisibleIndex != 0) {
1049 // Make sure that if we are shrinking we tell the view we still fit
1050 m_minYExtent = qMax(m_minYExtent, -(contentHeight - height()));
1054 m_contentHeightDirty = false;
1055 setContentHeight(contentHeight);
1059#include "moc_listviewwithpageheader.cpp"