on 888e546 help sign in
unity8/plugins/ListViewWithPageHeader/listviewwithpageheader.cpp
1075 lines 42 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 if (!m_headerItem)
346 return;
348 auto to = qMax(-minYExtent(), contentY() - m_headerItem->height() + m_headerItemShownHeight);
349 if (to != contentY()) {
350 const bool headerShownByItsOwn = contentY() < m_headerItem->y() + m_headerItem->height();
351 if (headerShownByItsOwn && m_headerItemShownHeight == 0) {
352 // We are not clipping since we are just at the top of the viewport
353 // but because of the showHeader animation we will need to, so
354 // enable the clipping without logically moving the items
355 m_headerItemShownHeight = m_headerItem->y() + m_headerItem->height() - contentY();
356 if (!m_visibleItems.isEmpty()) {
357 updateClipItem();
358 ListItem *firstItem = m_visibleItems.first();
359 firstItem->setY(firstItem->y() - m_headerItemShownHeight);
360 layout();
361 }
362 }
363 m_headerShowAnimation->setTo(to);
364 m_headerShowAnimation->start();
365 }
368qreal ListViewWithPageHeader::minYExtent() const
370// qDebug() << "ListViewWithPageHeader::minYExtent" << m_minYExtent;
371 return m_minYExtent;
374void ListViewWithPageHeader::componentComplete()
376 if (m_delegateModel)
377 m_delegateModel->componentComplete();
379 QQuickFlickable::componentComplete();
381 polish();
384void ListViewWithPageHeader::viewportMoved(Qt::Orientations orient)
386 QQuickFlickable::viewportMoved(orient);
387// qDebug() << "ListViewWithPageHeader::viewportMoved" << contentY();
388 qreal diff = m_previousContentY - contentY();
389 if (m_headerItem) {
390 auto oldHeaderItemShownHeight = m_headerItemShownHeight;
391 if (contentY() < -m_minYExtent) {
392 // Stick the header item to the top when dragging down
393 m_headerItem->setY(contentY());
394 m_headerItem->setHeight(m_headerItem->implicitHeight() + (-m_minYExtent - contentY()));
395 } else {
396 m_headerItem->setHeight(m_headerItem->implicitHeight());
397 // We are going down (but it's not because of the rebound at the end)
398 // (but the header was not shown by it's own position)
399 // or the header is partially shown
400 const bool scrolledUp = m_previousContentY > contentY();
401 const bool notRebounding = contentY() + height() < contentHeight();
402 const bool notShownByItsOwn = contentY() + diff > m_headerItem->y() + m_headerItem->height();
404 if (!scrolledUp && contentY() == -m_minYExtent) {
405 m_headerItemShownHeight = 0;
406 m_headerItem->setY(contentY());
407 } else if ((scrolledUp && notRebounding && notShownByItsOwn) || (m_headerItemShownHeight > 0)) {
408 m_headerItemShownHeight += diff;
409 if (contentY() == -m_minYExtent) {
410 m_headerItemShownHeight = 0;
411 } else {
412 m_headerItemShownHeight = qBound(static_cast<qreal>(0.), m_headerItemShownHeight, m_headerItem->height());
413 }
414 if (m_headerItemShownHeight > 0) {
415 m_headerItem->setY(contentY() - m_headerItem->height() + m_headerItemShownHeight);
416 } else {
417 m_headerItem->setY(-m_minYExtent);
418 }
419 }
420 }
421 // We will be changing the clip item, need to accomadate for it
422 // otherwise we move the firstItem down/up twice (unless the
423 // show header animation is running, where we want to keep the viewport stable)
424 if (!m_headerShowAnimation->isRunning()) {
425 diff += oldHeaderItemShownHeight - m_headerItemShownHeight;
426 } else {
427 diff = -diff;
428 }
429 }
430 if (!m_visibleItems.isEmpty()) {
431 updateClipItem();
432 ListItem *firstItem = m_visibleItems.first();
433 firstItem->setY(firstItem->y() + diff);
434 if (m_headerShowAnimation->isRunning()) {
435 adjustMinYExtent();
436 }
437 }
439 m_previousContentY = contentY();
440 layout();
441 polish();
444void ListViewWithPageHeader::createDelegateModel()
446 m_delegateModel = new QQuickVisualDataModel(qmlContext(this), this);
447 connect(m_delegateModel, SIGNAL(createdItem(int,QQuickItem*)), this, SLOT(itemCreated(int,QQuickItem*)));
448 if (isComponentComplete())
449 m_delegateModel->componentComplete();
450 updateWatchedRoles();
453void ListViewWithPageHeader::refill()
455 if (m_inLayout) {
456 return;
457 }
458 if (!isComponentComplete()) {
459 return;
460 }
462 const qreal buffer = height() * bufferRatio;
463 const qreal from = contentY();
464 const qreal to = from + height();
465 const qreal bufferFrom = from - buffer;
466 const qreal bufferTo = to + buffer;
468 bool added = addVisibleItems(from, to, false);
469 bool removed = removeNonVisibleItems(bufferFrom, bufferTo);
470 added |= addVisibleItems(bufferFrom, bufferTo, true);
472 if (added || removed) {
473 m_contentHeightDirty = true;
474 }
477bool ListViewWithPageHeader::addVisibleItems(qreal fillFrom, qreal fillTo, bool asynchronous)
479 if (!delegate())
480 return false;
482 if (m_delegateModel->count() == 0)
483 return false;
485 ListItem *item;
486// qDebug() << "ListViewWithPageHeader::addVisibleItems" << fillFrom << fillTo << asynchronous;
488 int modelIndex = 0;
489 qreal pos = 0;
490 if (!m_visibleItems.isEmpty()) {
491 modelIndex = m_firstVisibleIndex + m_visibleItems.count();
492 item = m_visibleItems.last();
493 pos = item->y() + item->height() + m_clipItem->y();
494 }
495 bool changed = false;
496// qDebug() << (modelIndex < m_delegateModel->count()) << pos << fillTo;
497 while (modelIndex < m_delegateModel->count() && pos <= fillTo) {
498// qDebug() << "refill: append item" << modelIndex << "pos" << pos << "asynchronous" << asynchronous;
499 if (!(item = createItem(modelIndex, asynchronous)))
500 break;
501 pos += item->height();
502 ++modelIndex;
503 changed = true;
504 }
506 modelIndex = 0;
507 pos = 0;
508 if (!m_visibleItems.isEmpty()) {
509 modelIndex = m_firstVisibleIndex - 1;
510 item = m_visibleItems.first();
511 pos = item->y() + m_clipItem->y();
512 }
513 while (modelIndex >= 0 && pos > fillFrom) {
514// qDebug() << "refill: prepend item" << modelIndex << "pos" << pos << "fillFrom" << fillFrom << "asynchronous" << asynchronous;
515 if (!(item = createItem(modelIndex, asynchronous)))
516 break;
517 pos -= item->height();
518 --modelIndex;
519 changed = true;
520 }
522 return changed;
525void ListViewWithPageHeader::reallyReleaseItem(ListItem *listItem)
527 QQuickItem *item = listItem->m_item;
528 QQuickVisualModel::ReleaseFlags flags = m_delegateModel->release(item);
529 if (flags & QQuickVisualModel::Destroyed) {
530 item->setParentItem(nullptr);
531 }
532 delete listItem->m_sectionItem;
533 delete listItem;
536void ListViewWithPageHeader::releaseItem(ListItem *listItem)
538 QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(listItem->m_item);
539 itemPrivate->removeItemChangeListener(this, QQuickItemPrivate::Geometry);
540 m_itemsToRelease << listItem;
543void ListViewWithPageHeader::updateWatchedRoles()
545 if (m_delegateModel) {
546 QList<QByteArray> roles;
547 if (!m_sectionProperty.isEmpty())
548 roles << m_sectionProperty.toUtf8();
549 m_delegateModel->setWatchedRoles(roles);
550 }
553QQuickItem *ListViewWithPageHeader::getSectionItem(int modelIndex, bool alreadyInserted)
555 if (!m_sectionDelegate)
556 return nullptr;
558 const QString section = m_delegateModel->stringValue(modelIndex, m_sectionProperty);
559 if (modelIndex > 0) {
560 const QString prevSection = m_delegateModel->stringValue(modelIndex - 1, m_sectionProperty);
561 if (section == prevSection)
562 return nullptr;
563 }
564 if (modelIndex + 1 < model()->rowCount() && !alreadyInserted) {
565 // Already inserted items can't steal next section header
566 const QString nextSection = m_delegateModel->stringValue(modelIndex + 1, m_sectionProperty);
567 if (section == nextSection) {
568 // Steal the section header
569 ListItem *nextItem = itemAtIndex(modelIndex); // Not +1 since not yet inserted into m_visibleItems
570 if (nextItem) {
571 QQuickItem *sectionItem = nextItem->m_sectionItem;
572 nextItem->m_sectionItem = nullptr;
573 return sectionItem;
574 }
575 }
576 }
578 return getSectionItem(section);
581QQuickItem *ListViewWithPageHeader::getSectionItem(const QString &sectionText)
583 QQuickItem *sectionItem = nullptr;
585 QQmlContext *creationContext = m_sectionDelegate->creationContext();
586 QQmlContext *context = new QQmlContext(creationContext ? creationContext : qmlContext(this));
587 context->setContextProperty(QLatin1String("section"), sectionText);
588 QObject *nobj = m_sectionDelegate->beginCreate(context);
589 if (nobj) {
590 QQml_setParent_noEvent(context, nobj);
591 sectionItem = qobject_cast<QQuickItem *>(nobj);
592 if (!sectionItem) {
593 delete nobj;
594 } else {
595 sectionItem->setZ(2);
596 QQml_setParent_noEvent(sectionItem, m_clipItem);
597 sectionItem->setParentItem(m_clipItem);
598 }
599 } else {
600 delete context;
601 }
602 m_sectionDelegate->completeCreate();
604 // TODO attach to sectionItem so we can accomodate to it changing its height
606 return sectionItem;
609bool ListViewWithPageHeader::removeNonVisibleItems(qreal bufferFrom, qreal bufferTo)
611// qDebug() << "ListViewWithPageHeader::removeNonVisibleItems" << bufferFrom << bufferTo;
612 // Do not remove items if we are overshooting up or down, since we'll come back
613 // to the "stable" position and delete/create items without any reason
614 if (contentY() < -m_minYExtent) {
615 return false;
616 } else if (contentY() + height() > contentHeight()) {
617 return false;
618 }
619 bool changed = false;
621 bool foundVisible = false;
622 int i = 0;
623 int removedItems = 0;
624 const auto oldFirstVisibleIndex = m_firstVisibleIndex;
625 while (i < m_visibleItems.count()) {
626 ListItem *item = m_visibleItems[i];
627 const qreal pos = item->y() + m_clipItem->y();
628// qDebug() << i << pos << (pos + item->height()) << bufferFrom << bufferTo;
629 if (pos + item->height() < bufferFrom || pos > bufferTo) {
630// qDebug() << "Releasing" << i << (pos + item->height() < bufferFrom) << pos + item->height() << bufferFrom << (pos > bufferTo) << pos << bufferTo;
631 releaseItem(item);
632 m_visibleItems.removeAt(i);
633 changed = true;
634 ++removedItems;
635 } else {
636 if (!foundVisible) {
637 foundVisible = true;
638 const int itemIndex = m_firstVisibleIndex + removedItems + i;
639 m_firstVisibleIndex = itemIndex;
640 }
641 ++i;
642 }
643 }
644 if (m_firstVisibleIndex != oldFirstVisibleIndex) {
645 adjustMinYExtent();
646 }
648 return changed;
651ListViewWithPageHeader::ListItem *ListViewWithPageHeader::createItem(int modelIndex, bool asynchronous)
653// qDebug() << "CREATE ITEM" << modelIndex;
654 if (asynchronous && m_asyncRequestedIndex != -1)
655 return nullptr;
657 m_asyncRequestedIndex = -1;
658 QQuickItem *item = m_delegateModel->item(modelIndex, asynchronous);
659 if (!item) {
660 m_asyncRequestedIndex = modelIndex;
661 return 0;
662 } else {
663// qDebug() << "ListViewWithPageHeader::createItem::We have the item" << modelIndex << item;
664 ListItem *listItem = new ListItem;
665 listItem->m_item = item;
666 listItem->m_sectionItem = getSectionItem(modelIndex, false /*Not yet inserted into m_visibleItems*/);
667 QQuickItemPrivate::get(item)->addItemChangeListener(this, QQuickItemPrivate::Geometry);
668 ListItem *prevItem = itemAtIndex(modelIndex - 1);
669 bool lostItem = false; // Is an item that we requested async but because of model changes
670 // it is no longer attached to any of the existing items (has no prev nor next item)
671 // nor is the first item
672 if (prevItem) {
673 listItem->setY(prevItem->y() + prevItem->height());
674 } else {
675 ListItem *currItem = itemAtIndex(modelIndex);
676 if (currItem) {
677 // There's something already in m_visibleItems at out index, meaning this is an insert, so attach to its top
678 listItem->setY(currItem->y() - listItem->height());
679 } else {
680 ListItem *nextItem = itemAtIndex(modelIndex + 1);
681 if (nextItem) {
682 listItem->setY(nextItem->y() - listItem->height());
683 } else if (modelIndex == 0 && m_headerItem) {
684 listItem->setY(m_headerItem->height());
685 } else if (!m_visibleItems.isEmpty()) {
686 lostItem = true;
687 }
688 }
689 }
690 if (lostItem) {
691 releaseItem(listItem);
692 listItem = nullptr;
693 } else {
694 listItem->setCulled(listItem->y() + listItem->height() + m_clipItem->y() < contentY() || listItem->y() + m_clipItem->y() >= contentY() + height());
695 if (m_visibleItems.isEmpty()) {
696 m_visibleItems << listItem;
697 } else {
698 m_visibleItems.insert(modelIndex - m_firstVisibleIndex, listItem);
699 }
700 if (m_firstVisibleIndex < 0 || modelIndex < m_firstVisibleIndex) {
701 m_firstVisibleIndex = modelIndex;
702 polish();
703 }
704 adjustMinYExtent();
705 m_contentHeightDirty = true;
706 }
707 return listItem;
708 }
711void ListViewWithPageHeader::itemCreated(int modelIndex, QQuickItem *item)
713// qDebug() << "ListViewWithPageHeader::itemCreated" << modelIndex << item;
715 item->setParentItem(m_clipItem);
716 QQmlContext *context = QQmlEngine::contextForObject(item)->parentContext();
717 context->setContextProperty(QLatin1String("ListViewWithPageHeader"), this);
718 context->setContextProperty(QLatin1String("heightToClip"), QVariant::fromValue<int>(0));
719 if (modelIndex == m_asyncRequestedIndex) {
720 createItem(modelIndex, false);
721 refill();
722 }
725void ListViewWithPageHeader::updateClipItem()
727 m_clipItem->setHeight(height() - m_headerItemShownHeight);
728 m_clipItem->setY(contentY() + m_headerItemShownHeight);
729 m_clipItem->setClip(!m_forceNoClip && m_headerItemShownHeight > 0);
732void ListViewWithPageHeader::onContentHeightChanged()
734 updateClipItem();
737void ListViewWithPageHeader::onContentWidthChanged()
739 m_clipItem->setWidth(contentItem()->width());
742void ListViewWithPageHeader::onHeightChanged()
744 polish();
747void ListViewWithPageHeader::onModelUpdated(const QQuickChangeSet &changeSet, bool /*reset*/)
749 // TODO Do something with reset
750// qDebug() << "ListViewWithPageHeader::onModelUpdated" << changeSet << reset;
751 const auto oldFirstVisibleIndex = m_firstVisibleIndex;
753 Q_FOREACH(const QQuickChangeSet::Remove &remove, changeSet.removes()) {
754// qDebug() << "ListViewWithPageHeader::onModelUpdated Remove" << remove.index << remove.count;
755 if (remove.index + remove.count > m_firstVisibleIndex && remove.index < m_firstVisibleIndex + m_visibleItems.count()) {
756 const qreal oldFirstValidIndexPos = m_visibleItems.first()->y();
757 // If all the items we are removing are either not created or culled
758 // we have to grow down to avoid viewport changing
759 bool growDown = true;
760 for (int i = 0; growDown && i < remove.count; ++i) {
761 const int modelIndex = remove.index + i;
762 ListItem *item = itemAtIndex(modelIndex);
763 if (item && !item->culled()) {
764 growDown = false;
765 }
766 }
767 for (int i = remove.count - 1; i >= 0; --i) {
768 const int visibleIndex = remove.index + i - m_firstVisibleIndex;
769 if (visibleIndex >= 0 && visibleIndex < m_visibleItems.count()) {
770 ListItem *item = m_visibleItems[visibleIndex];
771 // Pass the section item down if needed
772 if (item->m_sectionItem && visibleIndex + 1 < m_visibleItems.count()) {
773 ListItem *nextItem = m_visibleItems[visibleIndex + 1];
774 if (!nextItem->m_sectionItem) {
775 nextItem->m_sectionItem = item->m_sectionItem;
776 item->m_sectionItem = nullptr;
777 }
778 }
779 releaseItem(item);
780 m_visibleItems.removeAt(visibleIndex);
781 }
782 }
783 if (growDown) {
784 adjustMinYExtent();
785 } else if (remove.index <= m_firstVisibleIndex && !m_visibleItems.isEmpty()) {
786 // We removed the first item that is the one that positions the rest
787 // position the new first item correctly
788 m_visibleItems.first()->setY(oldFirstValidIndexPos);
789 }
790 } else if (remove.index + remove.count <= m_firstVisibleIndex) {
791 m_firstVisibleIndex -= remove.count;
792 }
793 for (int i = remove.count - 1; i >= 0; --i) {
794 const int modelIndex = remove.index + i;
795 if (modelIndex == m_asyncRequestedIndex) {
796 m_asyncRequestedIndex = -1;
797 } else if (modelIndex < m_asyncRequestedIndex) {
798 m_asyncRequestedIndex--;
799 }
800 }
801 }
803 Q_FOREACH(const QQuickChangeSet::Insert &insert, changeSet.inserts()) {
804// qDebug() << "ListViewWithPageHeader::onModelUpdated Insert" << insert.index << insert.count;
805 const bool insertingInValidIndexes = insert.index > m_firstVisibleIndex && insert.index < m_firstVisibleIndex + m_visibleItems.count();
806 const bool firstItemWithViewOnTop = insert.index == 0 && m_firstVisibleIndex == 0 && m_visibleItems.first()->y() + m_clipItem->y() > contentY();
807 if (insertingInValidIndexes || firstItemWithViewOnTop)
808 {
809 // If the items we are adding won't be really visible
810 // we grow up instead of down to not change the viewport
811 bool growUp = false;
812 if (!firstItemWithViewOnTop) {
813 for (int i = 0; i < m_visibleItems.count(); ++i) {
814 if (!m_visibleItems[i]->culled()) {
815 if (insert.index <= m_firstVisibleIndex + i) {
816 growUp = true;
817 }
818 break;
819 }
820 }
821 }
823 const qreal oldFirstValidIndexPos = m_visibleItems.first()->y();
824 for (int i = insert.count - 1; i >= 0; --i) {
825 const int modelIndex = insert.index + i;
826 ListItem *item = createItem(modelIndex, false);
827 if (growUp) {
828 ListItem *firstItem = m_visibleItems.first();
829 firstItem->setY(firstItem->y() - item->height());
830 adjustMinYExtent();
831 }
832 // Adding an item may break a "same section" chain, so check
833 // if we need adding a new section item
834 if (m_sectionDelegate) {
835 ListItem *nextItem = itemAtIndex(modelIndex + 1);
836 if (nextItem && !nextItem->m_sectionItem) {
837 nextItem->m_sectionItem = getSectionItem(modelIndex + 1, true /* alredy inserted into m_visibleItems*/);
838 if (growUp && nextItem->m_sectionItem) {
839 ListItem *firstItem = m_visibleItems.first();
840 firstItem->setY(firstItem->y() - nextItem->m_sectionItem->height());
841 adjustMinYExtent();
842 }
843 }
844 }
845 }
846 if (firstItemWithViewOnTop) {
847 ListItem *firstItem = m_visibleItems.first();
848 firstItem->setY(oldFirstValidIndexPos);
849 }
850 } else if (insert.index <= m_firstVisibleIndex) {
851 m_firstVisibleIndex += insert.count;
852 }
854 for (int i = insert.count - 1; i >= 0; --i) {
855 const int modelIndex = insert.index + i;
856 if (modelIndex <= m_asyncRequestedIndex) {
857 m_asyncRequestedIndex++;
858 }
859 }
860 }
862 if (m_firstVisibleIndex != oldFirstVisibleIndex) {
863 adjustMinYExtent();
864 }
866 layout();
867 polish();
868 m_contentHeightDirty = true;
871void ListViewWithPageHeader::onShowHeaderAnimationFinished()
873 m_contentHeightDirty = true;
874 polish();
877void ListViewWithPageHeader::itemGeometryChanged(QQuickItem * /*item*/, const QRectF &newGeometry, const QRectF &oldGeometry)
879 const qreal heightDiff = newGeometry.height() - oldGeometry.height();
880 if (heightDiff != 0) {
881 if (oldGeometry.y() + oldGeometry.height() + m_clipItem->y() < contentY() && !m_visibleItems.isEmpty()) {
882 ListItem *firstItem = m_visibleItems.first();
883 firstItem->setY(firstItem->y() - heightDiff);
884 adjustMinYExtent();
885 layout();
886 }
887 refill();
888 adjustMinYExtent();
889 polish();
890 m_contentHeightDirty = true;
891 }
894void ListViewWithPageHeader::headerHeightChanged(qreal newHeaderHeight, qreal oldHeaderHeight, qreal oldHeaderY)
896 const qreal heightDiff = newHeaderHeight - oldHeaderHeight;
897 if (m_headerItemShownHeight > 0) {
898 // If the header is shown because of the clip
899 // Change its size
900 m_headerItemShownHeight += heightDiff;
901 m_headerItemShownHeight = qBound(static_cast<qreal>(0.), m_headerItemShownHeight, newHeaderHeight);
902 updateClipItem();
903 adjustMinYExtent();
904 } else {
905 if (oldHeaderY + oldHeaderHeight > contentY()) {
906 // If the header is shown because its position
907 // Change its size
908 ListItem *firstItem = m_visibleItems.first();
909 firstItem->setY(firstItem->y() + heightDiff);
910 layout();
911 } else {
912 // If the header is not on screen, just change the start of the list
913 // so the viewport is not changed
914 adjustMinYExtent();
915 }
916 }
920void ListViewWithPageHeader::adjustMinYExtent()
922 if (m_visibleItems.isEmpty()) {
923 m_minYExtent = 0;
924 } else {
925 qreal nonCreatedHeight = 0;
926 if (m_firstVisibleIndex != 0) {
927 // Calculate the average height of items to estimate the position of the list start
928 const int visibleItems = m_visibleItems.count();
929 qreal visibleItemsHeight = 0;
930 Q_FOREACH(ListItem *item, m_visibleItems) {
931 visibleItemsHeight += item->height();
932 }
933 nonCreatedHeight = m_firstVisibleIndex * visibleItemsHeight / visibleItems;
934// qDebug() << m_firstVisibleIndex << visibleItemsHeight << visibleItems << nonCreatedHeight;
935 }
936 m_minYExtent = nonCreatedHeight - m_visibleItems.first()->y() - m_clipItem->y() + (m_headerItem ? m_headerItem->implicitHeight() : 0);
937 }
940ListViewWithPageHeader::ListItem *ListViewWithPageHeader::itemAtIndex(int modelIndex) const
942 const int visibleIndexedModelIndex = modelIndex - m_firstVisibleIndex;
943 if (visibleIndexedModelIndex >= 0 && visibleIndexedModelIndex < m_visibleItems.count())
944 return m_visibleItems[visibleIndexedModelIndex];
946 return nullptr;
949void ListViewWithPageHeader::layout()
951 if (m_inLayout)
952 return;
954 m_inLayout = true;
955 if (!m_visibleItems.isEmpty()) {
956 const qreal visibleFrom = contentY() - m_clipItem->y() + m_headerItemShownHeight;
957 const qreal visibleTo = contentY() + height() - m_clipItem->y();
959 qreal pos = m_visibleItems.first()->y();
961// qDebug() << "ListViewWithPageHeader::layout Updating positions and heights. contentY" << contentY() << "minYExtent" << minYExtent();
962 int firstReallyVisibleItem = -1;
963 int modelIndex = m_firstVisibleIndex;
964 Q_FOREACH(ListItem *item, m_visibleItems) {
965 const bool cull = pos + item->height() < visibleFrom || pos >= visibleTo;
966 item->setCulled(cull);
967 item->setY(pos);
968 if (!cull && firstReallyVisibleItem == -1) {
969 firstReallyVisibleItem = modelIndex;
970 if (m_topSectionItem) {
971 // Update the top sticky section header
972 const QString section = m_delegateModel->stringValue(modelIndex, m_sectionProperty);
973 QQmlContext *context = QQmlEngine::contextForObject(m_topSectionItem)->parentContext();
974 context->setContextProperty(QLatin1String("section"), section);
976 // Positing the top section sticky item is a two step process
977 // First we set it either we cull it (because it doesn't need to be sticked to the top)
978 // or stick it to the top
979 // Then after the loop we'll make sure that if there's another section just below it
980 // pushed the sticky section up to make it disappear
981 const qreal topSectionStickPos = m_headerItemShownHeight + contentY() - m_clipItem->y();
982 if (topSectionStickPos <= pos) {
983 QQuickItemPrivate::get(m_topSectionItem)->setCulled(true);
984 if (item->m_sectionItem) {
985 // This seems it should happen since why would we cull the top section
986 // if the first visible item has no section header? This only happens briefly
987 // when increasing the height of a list that is at the bottom, the m_topSectionItem
988 // gets shown shortly in the next polish call
989 QQuickItemPrivate::get(item->m_sectionItem)->setCulled(false);
990 }
991 } else {
992 QQuickItemPrivate::get(m_topSectionItem)->setCulled(false);
993 m_topSectionItem->setY(topSectionStickPos);
994 if (item->m_sectionItem) {
995 QQuickItemPrivate::get(item->m_sectionItem)->setCulled(true);
996 }
997 }
998 }
999 }
1000 QQmlContext *context = QQmlEngine::contextForObject(item->m_item)->parentContext();
1001 const qreal clipFrom = visibleFrom + (!item->m_sectionItem && m_topSectionItem && !QQuickItemPrivate::get(m_topSectionItem)->culled ? m_topSectionItem->height() : 0);
1002 if (!cull && pos < clipFrom) {
1003 context->setContextProperty(QLatin1String("heightToClip"), clipFrom - pos);
1004 } else {
1005 context->setContextProperty(QLatin1String("heightToClip"), QVariant::fromValue<int>(0));
1007// qDebug() << "ListViewWithPageHeader::layout" << item->m_item;
1008 pos += item->height();
1009 ++modelIndex;
1012 // Second step of section sticky item positioning
1013 // Look at the next section header, check if it's pushing up the sticky one
1014 if (m_topSectionItem) {
1015 if (firstReallyVisibleItem >= 0) {
1016 for (int i = firstReallyVisibleItem - m_firstVisibleIndex + 1; i < m_visibleItems.count(); ++i) {
1017 ListItem *item = m_visibleItems[i];
1018 if (item->m_sectionItem) {
1019 if (m_topSectionItem->y() + m_topSectionItem->height() > item->y()) {
1020 m_topSectionItem->setY(item->y() - m_topSectionItem->height());
1022 break;
1028 m_inLayout = false;
1031void ListViewWithPageHeader::updatePolish()
1033 Q_FOREACH(ListItem *item, m_itemsToRelease)
1034 reallyReleaseItem(item);
1035 m_itemsToRelease.clear();
1037 if (!model())
1038 return;
1040 layout();
1042 refill();
1044 if (m_contentHeightDirty) {
1045 qreal contentHeight;
1046 if (m_visibleItems.isEmpty()) {
1047 contentHeight = m_headerItem ? m_headerItem->height() : 0;
1048 } else {
1049 const int modelCount = model()->rowCount();
1050 const int visibleItems = m_visibleItems.count();
1051 const int lastValidIndex = m_firstVisibleIndex + visibleItems - 1;
1052 qreal nonCreatedHeight = 0;
1053 if (lastValidIndex != modelCount - 1) {
1054 const int visibleItems = m_visibleItems.count();
1055 qreal visibleItemsHeight = 0;
1056 Q_FOREACH(ListItem *item, m_visibleItems) {
1057 visibleItemsHeight += item->height();
1059 const int unknownSizes = modelCount - (m_firstVisibleIndex + visibleItems);
1060 nonCreatedHeight = unknownSizes * visibleItemsHeight / visibleItems;
1062 ListItem *item = m_visibleItems.last();
1063 contentHeight = nonCreatedHeight + item->y() + item->height() + m_clipItem->y();
1064 if (m_firstVisibleIndex != 0) {
1065 // Make sure that if we are shrinking we tell the view we still fit
1066 m_minYExtent = qMax(m_minYExtent, -(contentHeight - height()));
1070 m_contentHeightDirty = false;
1071 setContentHeight(contentHeight);
1075#include "moc_listviewwithpageheader.cpp"