on 44444ad help sign in
unity8/plugins/ListViewWithPageHeader/listviewwithpageheader.cpp
1078 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#pragma GCC diagnostic push
98#pragma GCC diagnostic ignored "-pedantic"
99#include <private/qquickvisualdatamodel_p.h>
100#include <private/qqmlglobal_p.h>
101#include <private/qquickitem_p.h>
102#include <private/qquickanimation_p.h>
103#pragma GCC diagnostic pop
104// #include <private/qquickrectangle_p.h>
106static const qreal bufferRatio = 0.5;
108qreal ListViewWithPageHeader::ListItem::height() const
110 return m_item->height() + (m_sectionItem ? m_sectionItem->height() : 0);
113qreal ListViewWithPageHeader::ListItem::y() const
115 return m_item->y() - (m_sectionItem ? m_sectionItem->height() : 0);
118void ListViewWithPageHeader::ListItem::setY(qreal newY)
120 if (m_sectionItem) {
121 m_sectionItem->setY(newY);
122 m_item->setY(newY + m_sectionItem->height());
123 } else {
124 m_item->setY(newY);
125 }
128bool ListViewWithPageHeader::ListItem::culled() const
130 return QQuickItemPrivate::get(m_item)->culled;
133void ListViewWithPageHeader::ListItem::setCulled(bool culled)
135 QQuickItemPrivate::get(m_item)->setCulled(culled);
136 if (m_sectionItem)
137 QQuickItemPrivate::get(m_sectionItem)->setCulled(culled);
140ListViewWithPageHeader::ListViewWithPageHeader()
141 : m_delegateModel(nullptr)
142 , m_asyncRequestedIndex(-1)
143 , m_delegateValidated(false)
144 , m_firstVisibleIndex(-1)
145 , m_minYExtent(0)
146 , m_contentHeightDirty(false)
147 , m_headerItem(nullptr)
148 , m_previousContentY(0)
149 , m_headerItemShownHeight(0)
150 , m_sectionDelegate(nullptr)
151 , m_topSectionItem(nullptr)
152 , m_forceNoClip(false)
153 , m_inLayout(false)
155 m_clipItem = new QQuickItem(contentItem());
156// m_clipItem = new QQuickRectangle(contentItem());
157// ((QQuickRectangle*)m_clipItem)->setColor(Qt::gray);
159 m_headerShowAnimation = new QQuickNumberAnimation(this);
160 m_headerShowAnimation->setEasing(QEasingCurve::OutQuad);
161 m_headerShowAnimation->setProperty("contentY");
162 m_headerShowAnimation->setDuration(200);
163 m_headerShowAnimation->setTargetObject(this);
165 connect(this, SIGNAL(contentWidthChanged()), this, SLOT(onContentWidthChanged()));
166 connect(this, SIGNAL(contentHeightChanged()), this, SLOT(onContentHeightChanged()));
167 connect(this, SIGNAL(heightChanged()), this, SLOT(onHeightChanged()));
168 connect(m_headerShowAnimation, SIGNAL(stopped()), this, SLOT(onShowHeaderAnimationFinished()));
171ListViewWithPageHeader::~ListViewWithPageHeader()
175QAbstractItemModel *ListViewWithPageHeader::model() const
177 return m_delegateModel ? m_delegateModel->model().value<QAbstractItemModel *>() : nullptr;
180void ListViewWithPageHeader::setModel(QAbstractItemModel *model)
182 if (model != this->model()) {
183 if (!m_delegateModel) {
184 createDelegateModel();
185 } else {
186 disconnect(m_delegateModel, SIGNAL(modelUpdated(QQuickChangeSet,bool)), this, SLOT(onModelUpdated(QQuickChangeSet,bool)));
187 }
188 m_delegateModel->setModel(QVariant::fromValue<QAbstractItemModel *>(model));
189 connect(m_delegateModel, SIGNAL(modelUpdated(QQuickChangeSet,bool)), this, SLOT(onModelUpdated(QQuickChangeSet,bool)));
190 Q_EMIT modelChanged();
191 // TODO?
192// Q_EMIT contentHeightChanged();
193// Q_EMIT contentYChanged();
194 }
197QQmlComponent *ListViewWithPageHeader::delegate() const
199 return m_delegateModel ? m_delegateModel->delegate() : nullptr;
202void ListViewWithPageHeader::setDelegate(QQmlComponent *delegate)
204 if (delegate != this->delegate()) {
205 if (!m_delegateModel) {
206 createDelegateModel();
207 }
209 // Cleanup the existing items
210 Q_FOREACH(ListItem *item, m_visibleItems)
211 releaseItem(item);
212 m_visibleItems.clear();
213 m_firstVisibleIndex = -1;
214 adjustMinYExtent();
215 setContentY(0);
216 m_clipItem->setY(0);
217 if (m_topSectionItem) {
218 QQuickItemPrivate::get(m_topSectionItem)->setCulled(true);
219 }
221 m_delegateModel->setDelegate(delegate);
223 Q_EMIT delegateChanged();
224 m_delegateValidated = false;
225 m_contentHeightDirty = true;
226 polish();
227 }
230QQuickItem *ListViewWithPageHeader::header() const
232 return m_headerItem;
235void ListViewWithPageHeader::setHeader(QQuickItem *headerItem)
237 if (m_headerItem != headerItem) {
238 qreal oldHeaderHeight = 0;
239 qreal oldHeaderY = 0;
240 if (m_headerItem) {
241 oldHeaderHeight = m_headerItem->height();
242 oldHeaderY = m_headerItem->y();
243 m_headerItem->setParentItem(nullptr);
244 }
245 m_headerItem = headerItem;
246 if (m_headerItem) {
247 m_headerItem->setParentItem(contentItem());
248 m_headerItem->setZ(1);
249 }
250 qreal newHeaderHeight = m_headerItem ? m_headerItem->height() : 0;
251 if (!m_visibleItems.isEmpty() && newHeaderHeight != oldHeaderHeight) {
252 headerHeightChanged(newHeaderHeight, oldHeaderHeight, oldHeaderY);
253 polish();
254 m_contentHeightDirty = true;
255 }
256 Q_EMIT headerChanged();
257 }
260QQmlComponent *ListViewWithPageHeader::sectionDelegate() const
262 return m_sectionDelegate;
265void ListViewWithPageHeader::setSectionDelegate(QQmlComponent *delegate)
267 if (delegate != m_sectionDelegate) {
268 // TODO clean existing sections
270 m_sectionDelegate = delegate;
272 m_topSectionItem = getSectionItem(QString());
273 m_topSectionItem->setZ(3);
274 QQuickItemPrivate::get(m_topSectionItem)->setCulled(true);
276 // TODO create sections for existing items
278 Q_EMIT sectionDelegateChanged();
279 }
282QString ListViewWithPageHeader::sectionProperty() const
284 return m_sectionProperty;
287void ListViewWithPageHeader::setSectionProperty(const QString &property)
289 if (property != m_sectionProperty) {
290 m_sectionProperty = property;
292 updateWatchedRoles();
294 // TODO recreate sections
296 Q_EMIT sectionPropertyChanged();
297 }
300bool ListViewWithPageHeader::forceNoClip() const
302 return m_forceNoClip;
305void ListViewWithPageHeader::setForceNoClip(bool noClip)
307 if (noClip != m_forceNoClip) {
308 m_forceNoClip = noClip;
309 updateClipItem();
310 Q_EMIT forceNoClipChanged();
311 }
314void ListViewWithPageHeader::positionAtBeginning()
316 qreal headerHeight = (m_headerItem ? m_headerItem->height() : 0);
317 if (m_firstVisibleIndex != 0) {
318 // TODO This could be optimized by trying to reuse the interesection
319 // of items that may end up intersecting between the existing
320 // m_visibleItems and the items we are creating in the next loop
321 Q_FOREACH(ListItem *item, m_visibleItems)
322 releaseItem(item);
323 m_visibleItems.clear();
324 m_firstVisibleIndex = -1;
326 // Create the item 0, it will be already correctly positioned at createItem()
327 m_clipItem->setY(0);
328 ListItem *item = createItem(0, false);
329 // Create the subsequent items
330 int modelIndex = 1;
331 qreal pos = item->y() + item->height();
332 const qreal buffer = height() * bufferRatio;
333 const qreal bufferTo = height() + buffer;
334 while (modelIndex < m_delegateModel->count() && pos <= bufferTo) {
335 if (!(item = createItem(modelIndex, false)))
336 break;
337 pos += item->height();
338 ++modelIndex;
339 }
341 m_previousContentY = m_visibleItems.first()->y() - headerHeight;
342 }
343 setContentY(m_visibleItems.first()->y() + m_clipItem->y() - headerHeight);
346void ListViewWithPageHeader::showHeader()
348 if (!m_headerItem)
349 return;
351 auto to = qMax(-minYExtent(), contentY() - m_headerItem->height() + m_headerItemShownHeight);
352 if (to != contentY()) {
353 const bool headerShownByItsOwn = contentY() < m_headerItem->y() + m_headerItem->height();
354 if (headerShownByItsOwn && m_headerItemShownHeight == 0) {
355 // We are not clipping since we are just at the top of the viewport
356 // but because of the showHeader animation we will need to, so
357 // enable the clipping without logically moving the items
358 m_headerItemShownHeight = m_headerItem->y() + m_headerItem->height() - contentY();
359 if (!m_visibleItems.isEmpty()) {
360 updateClipItem();
361 ListItem *firstItem = m_visibleItems.first();
362 firstItem->setY(firstItem->y() - m_headerItemShownHeight);
363 layout();
364 }
365 }
366 m_headerShowAnimation->setTo(to);
367 m_headerShowAnimation->start();
368 }
371qreal ListViewWithPageHeader::minYExtent() const
373// qDebug() << "ListViewWithPageHeader::minYExtent" << m_minYExtent;
374 return m_minYExtent;
377void ListViewWithPageHeader::componentComplete()
379 if (m_delegateModel)
380 m_delegateModel->componentComplete();
382 QQuickFlickable::componentComplete();
384 polish();
387void ListViewWithPageHeader::viewportMoved(Qt::Orientations orient)
389 QQuickFlickable::viewportMoved(orient);
390// qDebug() << "ListViewWithPageHeader::viewportMoved" << contentY();
391 qreal diff = m_previousContentY - contentY();
392 if (m_headerItem) {
393 auto oldHeaderItemShownHeight = m_headerItemShownHeight;
394 if (contentY() < -m_minYExtent) {
395 // Stick the header item to the top when dragging down
396 m_headerItem->setY(contentY());
397 m_headerItem->setHeight(m_headerItem->implicitHeight() + (-m_minYExtent - contentY()));
398 } else {
399 m_headerItem->setHeight(m_headerItem->implicitHeight());
400 // We are going down (but it's not because of the rebound at the end)
401 // (but the header was not shown by it's own position)
402 // or the header is partially shown
403 const bool scrolledUp = m_previousContentY > contentY();
404 const bool notRebounding = contentY() + height() < contentHeight();
405 const bool notShownByItsOwn = contentY() + diff > m_headerItem->y() + m_headerItem->height();
407 if (!scrolledUp && contentY() == -m_minYExtent) {
408 m_headerItemShownHeight = 0;
409 m_headerItem->setY(contentY());
410 } else if ((scrolledUp && notRebounding && notShownByItsOwn) || (m_headerItemShownHeight > 0)) {
411 m_headerItemShownHeight += diff;
412 if (contentY() == -m_minYExtent) {
413 m_headerItemShownHeight = 0;
414 } else {
415 m_headerItemShownHeight = qBound(static_cast<qreal>(0.), m_headerItemShownHeight, m_headerItem->height());
416 }
417 if (m_headerItemShownHeight > 0) {
418 m_headerItem->setY(contentY() - m_headerItem->height() + m_headerItemShownHeight);
419 } else {
420 m_headerItem->setY(-m_minYExtent);
421 }
422 }
423 }
424 // We will be changing the clip item, need to accomadate for it
425 // otherwise we move the firstItem down/up twice (unless the
426 // show header animation is running, where we want to keep the viewport stable)
427 if (!m_headerShowAnimation->isRunning()) {
428 diff += oldHeaderItemShownHeight - m_headerItemShownHeight;
429 } else {
430 diff = -diff;
431 }
432 }
433 if (!m_visibleItems.isEmpty()) {
434 updateClipItem();
435 ListItem *firstItem = m_visibleItems.first();
436 firstItem->setY(firstItem->y() + diff);
437 if (m_headerShowAnimation->isRunning()) {
438 adjustMinYExtent();
439 }
440 }
442 m_previousContentY = contentY();
443 layout();
444 polish();
447void ListViewWithPageHeader::createDelegateModel()
449 m_delegateModel = new QQuickVisualDataModel(qmlContext(this), this);
450 connect(m_delegateModel, SIGNAL(createdItem(int,QQuickItem*)), this, SLOT(itemCreated(int,QQuickItem*)));
451 if (isComponentComplete())
452 m_delegateModel->componentComplete();
453 updateWatchedRoles();
456void ListViewWithPageHeader::refill()
458 if (m_inLayout) {
459 return;
460 }
461 if (!isComponentComplete()) {
462 return;
463 }
465 const qreal buffer = height() * bufferRatio;
466 const qreal from = contentY();
467 const qreal to = from + height();
468 const qreal bufferFrom = from - buffer;
469 const qreal bufferTo = to + buffer;
471 bool added = addVisibleItems(from, to, false);
472 bool removed = removeNonVisibleItems(bufferFrom, bufferTo);
473 added |= addVisibleItems(bufferFrom, bufferTo, true);
475 if (added || removed) {
476 m_contentHeightDirty = true;
477 }
480bool ListViewWithPageHeader::addVisibleItems(qreal fillFrom, qreal fillTo, bool asynchronous)
482 if (!delegate())
483 return false;
485 if (m_delegateModel->count() == 0)
486 return false;
488 ListItem *item;
489// qDebug() << "ListViewWithPageHeader::addVisibleItems" << fillFrom << fillTo << asynchronous;
491 int modelIndex = 0;
492 qreal pos = 0;
493 if (!m_visibleItems.isEmpty()) {
494 modelIndex = m_firstVisibleIndex + m_visibleItems.count();
495 item = m_visibleItems.last();
496 pos = item->y() + item->height() + m_clipItem->y();
497 }
498 bool changed = false;
499// qDebug() << (modelIndex < m_delegateModel->count()) << pos << fillTo;
500 while (modelIndex < m_delegateModel->count() && pos <= fillTo) {
501// qDebug() << "refill: append item" << modelIndex << "pos" << pos << "asynchronous" << asynchronous;
502 if (!(item = createItem(modelIndex, asynchronous)))
503 break;
504 pos += item->height();
505 ++modelIndex;
506 changed = true;
507 }
509 modelIndex = 0;
510 pos = 0;
511 if (!m_visibleItems.isEmpty()) {
512 modelIndex = m_firstVisibleIndex - 1;
513 item = m_visibleItems.first();
514 pos = item->y() + m_clipItem->y();
515 }
516 while (modelIndex >= 0 && pos > fillFrom) {
517// qDebug() << "refill: prepend item" << modelIndex << "pos" << pos << "fillFrom" << fillFrom << "asynchronous" << asynchronous;
518 if (!(item = createItem(modelIndex, asynchronous)))
519 break;
520 pos -= item->height();
521 --modelIndex;
522 changed = true;
523 }
525 return changed;
528void ListViewWithPageHeader::reallyReleaseItem(ListItem *listItem)
530 QQuickItem *item = listItem->m_item;
531 QQuickVisualModel::ReleaseFlags flags = m_delegateModel->release(item);
532 if (flags & QQuickVisualModel::Destroyed) {
533 item->setParentItem(nullptr);
534 }
535 delete listItem->m_sectionItem;
536 delete listItem;
539void ListViewWithPageHeader::releaseItem(ListItem *listItem)
541 QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(listItem->m_item);
542 itemPrivate->removeItemChangeListener(this, QQuickItemPrivate::Geometry);
543 m_itemsToRelease << listItem;
546void ListViewWithPageHeader::updateWatchedRoles()
548 if (m_delegateModel) {
549 QList<QByteArray> roles;
550 if (!m_sectionProperty.isEmpty())
551 roles << m_sectionProperty.toUtf8();
552 m_delegateModel->setWatchedRoles(roles);
553 }
556QQuickItem *ListViewWithPageHeader::getSectionItem(int modelIndex, bool alreadyInserted)
558 if (!m_sectionDelegate)
559 return nullptr;
561 const QString section = m_delegateModel->stringValue(modelIndex, m_sectionProperty);
562 if (modelIndex > 0) {
563 const QString prevSection = m_delegateModel->stringValue(modelIndex - 1, m_sectionProperty);
564 if (section == prevSection)
565 return nullptr;
566 }
567 if (modelIndex + 1 < model()->rowCount() && !alreadyInserted) {
568 // Already inserted items can't steal next section header
569 const QString nextSection = m_delegateModel->stringValue(modelIndex + 1, m_sectionProperty);
570 if (section == nextSection) {
571 // Steal the section header
572 ListItem *nextItem = itemAtIndex(modelIndex); // Not +1 since not yet inserted into m_visibleItems
573 if (nextItem) {
574 QQuickItem *sectionItem = nextItem->m_sectionItem;
575 nextItem->m_sectionItem = nullptr;
576 return sectionItem;
577 }
578 }
579 }
581 return getSectionItem(section);
584QQuickItem *ListViewWithPageHeader::getSectionItem(const QString &sectionText)
586 QQuickItem *sectionItem = nullptr;
588 QQmlContext *creationContext = m_sectionDelegate->creationContext();
589 QQmlContext *context = new QQmlContext(creationContext ? creationContext : qmlContext(this));
590 context->setContextProperty(QLatin1String("section"), sectionText);
591 QObject *nobj = m_sectionDelegate->beginCreate(context);
592 if (nobj) {
593 QQml_setParent_noEvent(context, nobj);
594 sectionItem = qobject_cast<QQuickItem *>(nobj);
595 if (!sectionItem) {
596 delete nobj;
597 } else {
598 sectionItem->setZ(2);
599 QQml_setParent_noEvent(sectionItem, m_clipItem);
600 sectionItem->setParentItem(m_clipItem);
601 }
602 } else {
603 delete context;
604 }
605 m_sectionDelegate->completeCreate();
607 // TODO attach to sectionItem so we can accomodate to it changing its height
609 return sectionItem;
612bool ListViewWithPageHeader::removeNonVisibleItems(qreal bufferFrom, qreal bufferTo)
614// qDebug() << "ListViewWithPageHeader::removeNonVisibleItems" << bufferFrom << bufferTo;
615 // Do not remove items if we are overshooting up or down, since we'll come back
616 // to the "stable" position and delete/create items without any reason
617 if (contentY() < -m_minYExtent) {
618 return false;
619 } else if (contentY() + height() > contentHeight()) {
620 return false;
621 }
622 bool changed = false;
624 bool foundVisible = false;
625 int i = 0;
626 int removedItems = 0;
627 const auto oldFirstVisibleIndex = m_firstVisibleIndex;
628 while (i < m_visibleItems.count()) {
629 ListItem *item = m_visibleItems[i];
630 const qreal pos = item->y() + m_clipItem->y();
631// qDebug() << i << pos << (pos + item->height()) << bufferFrom << bufferTo;
632 if (pos + item->height() < bufferFrom || pos > bufferTo) {
633// qDebug() << "Releasing" << i << (pos + item->height() < bufferFrom) << pos + item->height() << bufferFrom << (pos > bufferTo) << pos << bufferTo;
634 releaseItem(item);
635 m_visibleItems.removeAt(i);
636 changed = true;
637 ++removedItems;
638 } else {
639 if (!foundVisible) {
640 foundVisible = true;
641 const int itemIndex = m_firstVisibleIndex + removedItems + i;
642 m_firstVisibleIndex = itemIndex;
643 }
644 ++i;
645 }
646 }
647 if (m_firstVisibleIndex != oldFirstVisibleIndex) {
648 adjustMinYExtent();
649 }
651 return changed;
654ListViewWithPageHeader::ListItem *ListViewWithPageHeader::createItem(int modelIndex, bool asynchronous)
656// qDebug() << "CREATE ITEM" << modelIndex;
657 if (asynchronous && m_asyncRequestedIndex != -1)
658 return nullptr;
660 m_asyncRequestedIndex = -1;
661 QQuickItem *item = m_delegateModel->item(modelIndex, asynchronous);
662 if (!item) {
663 m_asyncRequestedIndex = modelIndex;
664 return 0;
665 } else {
666// qDebug() << "ListViewWithPageHeader::createItem::We have the item" << modelIndex << item;
667 ListItem *listItem = new ListItem;
668 listItem->m_item = item;
669 listItem->m_sectionItem = getSectionItem(modelIndex, false /*Not yet inserted into m_visibleItems*/);
670 QQuickItemPrivate::get(item)->addItemChangeListener(this, QQuickItemPrivate::Geometry);
671 ListItem *prevItem = itemAtIndex(modelIndex - 1);
672 bool lostItem = false; // Is an item that we requested async but because of model changes
673 // it is no longer attached to any of the existing items (has no prev nor next item)
674 // nor is the first item
675 if (prevItem) {
676 listItem->setY(prevItem->y() + prevItem->height());
677 } else {
678 ListItem *currItem = itemAtIndex(modelIndex);
679 if (currItem) {
680 // There's something already in m_visibleItems at out index, meaning this is an insert, so attach to its top
681 listItem->setY(currItem->y() - listItem->height());
682 } else {
683 ListItem *nextItem = itemAtIndex(modelIndex + 1);
684 if (nextItem) {
685 listItem->setY(nextItem->y() - listItem->height());
686 } else if (modelIndex == 0 && m_headerItem) {
687 listItem->setY(m_headerItem->height());
688 } else if (!m_visibleItems.isEmpty()) {
689 lostItem = true;
690 }
691 }
692 }
693 if (lostItem) {
694 releaseItem(listItem);
695 listItem = nullptr;
696 } else {
697 listItem->setCulled(listItem->y() + listItem->height() + m_clipItem->y() < contentY() || listItem->y() + m_clipItem->y() >= contentY() + height());
698 if (m_visibleItems.isEmpty()) {
699 m_visibleItems << listItem;
700 } else {
701 m_visibleItems.insert(modelIndex - m_firstVisibleIndex, listItem);
702 }
703 if (m_firstVisibleIndex < 0 || modelIndex < m_firstVisibleIndex) {
704 m_firstVisibleIndex = modelIndex;
705 polish();
706 }
707 adjustMinYExtent();
708 m_contentHeightDirty = true;
709 }
710 return listItem;
711 }
714void ListViewWithPageHeader::itemCreated(int modelIndex, QQuickItem *item)
716// qDebug() << "ListViewWithPageHeader::itemCreated" << modelIndex << item;
718 item->setParentItem(m_clipItem);
719 QQmlContext *context = QQmlEngine::contextForObject(item)->parentContext();
720 context->setContextProperty(QLatin1String("ListViewWithPageHeader"), this);
721 context->setContextProperty(QLatin1String("heightToClip"), QVariant::fromValue<int>(0));
722 if (modelIndex == m_asyncRequestedIndex) {
723 createItem(modelIndex, false);
724 refill();
725 }
728void ListViewWithPageHeader::updateClipItem()
730 m_clipItem->setHeight(height() - m_headerItemShownHeight);
731 m_clipItem->setY(contentY() + m_headerItemShownHeight);
732 m_clipItem->setClip(!m_forceNoClip && m_headerItemShownHeight > 0);
735void ListViewWithPageHeader::onContentHeightChanged()
737 updateClipItem();
740void ListViewWithPageHeader::onContentWidthChanged()
742 m_clipItem->setWidth(contentItem()->width());
745void ListViewWithPageHeader::onHeightChanged()
747 polish();
750void ListViewWithPageHeader::onModelUpdated(const QQuickChangeSet &changeSet, bool /*reset*/)
752 // TODO Do something with reset
753// qDebug() << "ListViewWithPageHeader::onModelUpdated" << changeSet << reset;
754 const auto oldFirstVisibleIndex = m_firstVisibleIndex;
756 Q_FOREACH(const QQuickChangeSet::Remove &remove, changeSet.removes()) {
757// qDebug() << "ListViewWithPageHeader::onModelUpdated Remove" << remove.index << remove.count;
758 if (remove.index + remove.count > m_firstVisibleIndex && remove.index < m_firstVisibleIndex + m_visibleItems.count()) {
759 const qreal oldFirstValidIndexPos = m_visibleItems.first()->y();
760 // If all the items we are removing are either not created or culled
761 // we have to grow down to avoid viewport changing
762 bool growDown = true;
763 for (int i = 0; growDown && i < remove.count; ++i) {
764 const int modelIndex = remove.index + i;
765 ListItem *item = itemAtIndex(modelIndex);
766 if (item && !item->culled()) {
767 growDown = false;
768 }
769 }
770 for (int i = remove.count - 1; i >= 0; --i) {
771 const int visibleIndex = remove.index + i - m_firstVisibleIndex;
772 if (visibleIndex >= 0 && visibleIndex < m_visibleItems.count()) {
773 ListItem *item = m_visibleItems[visibleIndex];
774 // Pass the section item down if needed
775 if (item->m_sectionItem && visibleIndex + 1 < m_visibleItems.count()) {
776 ListItem *nextItem = m_visibleItems[visibleIndex + 1];
777 if (!nextItem->m_sectionItem) {
778 nextItem->m_sectionItem = item->m_sectionItem;
779 item->m_sectionItem = nullptr;
780 }
781 }
782 releaseItem(item);
783 m_visibleItems.removeAt(visibleIndex);
784 }
785 }
786 if (growDown) {
787 adjustMinYExtent();
788 } else if (remove.index <= m_firstVisibleIndex && !m_visibleItems.isEmpty()) {
789 // We removed the first item that is the one that positions the rest
790 // position the new first item correctly
791 m_visibleItems.first()->setY(oldFirstValidIndexPos);
792 }
793 } else if (remove.index + remove.count <= m_firstVisibleIndex) {
794 m_firstVisibleIndex -= remove.count;
795 }
796 for (int i = remove.count - 1; i >= 0; --i) {
797 const int modelIndex = remove.index + i;
798 if (modelIndex == m_asyncRequestedIndex) {
799 m_asyncRequestedIndex = -1;
800 } else if (modelIndex < m_asyncRequestedIndex) {
801 m_asyncRequestedIndex--;
802 }
803 }
804 }
806 Q_FOREACH(const QQuickChangeSet::Insert &insert, changeSet.inserts()) {
807// qDebug() << "ListViewWithPageHeader::onModelUpdated Insert" << insert.index << insert.count;
808 const bool insertingInValidIndexes = insert.index > m_firstVisibleIndex && insert.index < m_firstVisibleIndex + m_visibleItems.count();
809 const bool firstItemWithViewOnTop = insert.index == 0 && m_firstVisibleIndex == 0 && !m_visibleItems.isEmpty() && m_visibleItems.first()->y() + m_clipItem->y() > contentY();
810 if (insertingInValidIndexes || firstItemWithViewOnTop)
811 {
812 // If the items we are adding won't be really visible
813 // we grow up instead of down to not change the viewport
814 bool growUp = false;
815 if (!firstItemWithViewOnTop) {
816 for (int i = 0; i < m_visibleItems.count(); ++i) {
817 if (!m_visibleItems[i]->culled()) {
818 if (insert.index <= m_firstVisibleIndex + i) {
819 growUp = true;
820 }
821 break;
822 }
823 }
824 }
826 const qreal oldFirstValidIndexPos = m_visibleItems.first()->y();
827 for (int i = insert.count - 1; i >= 0; --i) {
828 const int modelIndex = insert.index + i;
829 ListItem *item = createItem(modelIndex, false);
830 if (growUp) {
831 ListItem *firstItem = m_visibleItems.first();
832 firstItem->setY(firstItem->y() - item->height());
833 adjustMinYExtent();
834 }
835 // Adding an item may break a "same section" chain, so check
836 // if we need adding a new section item
837 if (m_sectionDelegate) {
838 ListItem *nextItem = itemAtIndex(modelIndex + 1);
839 if (nextItem && !nextItem->m_sectionItem) {
840 nextItem->m_sectionItem = getSectionItem(modelIndex + 1, true /* alredy inserted into m_visibleItems*/);
841 if (growUp && nextItem->m_sectionItem) {
842 ListItem *firstItem = m_visibleItems.first();
843 firstItem->setY(firstItem->y() - nextItem->m_sectionItem->height());
844 adjustMinYExtent();
845 }
846 }
847 }
848 }
849 if (firstItemWithViewOnTop) {
850 ListItem *firstItem = m_visibleItems.first();
851 firstItem->setY(oldFirstValidIndexPos);
852 }
853 } else if (insert.index <= m_firstVisibleIndex) {
854 m_firstVisibleIndex += insert.count;
855 }
857 for (int i = insert.count - 1; i >= 0; --i) {
858 const int modelIndex = insert.index + i;
859 if (modelIndex <= m_asyncRequestedIndex) {
860 m_asyncRequestedIndex++;
861 }
862 }
863 }
865 if (m_firstVisibleIndex != oldFirstVisibleIndex) {
866 adjustMinYExtent();
867 }
869 layout();
870 polish();
871 m_contentHeightDirty = true;
874void ListViewWithPageHeader::onShowHeaderAnimationFinished()
876 m_contentHeightDirty = true;
877 polish();
880void ListViewWithPageHeader::itemGeometryChanged(QQuickItem * /*item*/, const QRectF &newGeometry, const QRectF &oldGeometry)
882 const qreal heightDiff = newGeometry.height() - oldGeometry.height();
883 if (heightDiff != 0) {
884 if (oldGeometry.y() + oldGeometry.height() + m_clipItem->y() < contentY() && !m_visibleItems.isEmpty()) {
885 ListItem *firstItem = m_visibleItems.first();
886 firstItem->setY(firstItem->y() - heightDiff);
887 adjustMinYExtent();
888 layout();
889 }
890 refill();
891 adjustMinYExtent();
892 polish();
893 m_contentHeightDirty = true;
894 }
897void ListViewWithPageHeader::headerHeightChanged(qreal newHeaderHeight, qreal oldHeaderHeight, qreal oldHeaderY)
899 const qreal heightDiff = newHeaderHeight - oldHeaderHeight;
900 if (m_headerItemShownHeight > 0) {
901 // If the header is shown because of the clip
902 // Change its size
903 m_headerItemShownHeight += heightDiff;
904 m_headerItemShownHeight = qBound(static_cast<qreal>(0.), m_headerItemShownHeight, newHeaderHeight);
905 updateClipItem();
906 adjustMinYExtent();
907 } else {
908 if (oldHeaderY + oldHeaderHeight > contentY()) {
909 // If the header is shown because its position
910 // Change its size
911 ListItem *firstItem = m_visibleItems.first();
912 firstItem->setY(firstItem->y() + heightDiff);
913 layout();
914 } else {
915 // If the header is not on screen, just change the start of the list
916 // so the viewport is not changed
917 adjustMinYExtent();
918 }
919 }
923void ListViewWithPageHeader::adjustMinYExtent()
925 if (m_visibleItems.isEmpty()) {
926 m_minYExtent = 0;
927 } else {
928 qreal nonCreatedHeight = 0;
929 if (m_firstVisibleIndex != 0) {
930 // Calculate the average height of items to estimate the position of the list start
931 const int visibleItems = m_visibleItems.count();
932 qreal visibleItemsHeight = 0;
933 Q_FOREACH(ListItem *item, m_visibleItems) {
934 visibleItemsHeight += item->height();
935 }
936 nonCreatedHeight = m_firstVisibleIndex * visibleItemsHeight / visibleItems;
937// qDebug() << m_firstVisibleIndex << visibleItemsHeight << visibleItems << nonCreatedHeight;
938 }
939 m_minYExtent = nonCreatedHeight - m_visibleItems.first()->y() - m_clipItem->y() + (m_headerItem ? m_headerItem->implicitHeight() : 0);
940 }
943ListViewWithPageHeader::ListItem *ListViewWithPageHeader::itemAtIndex(int modelIndex) const
945 const int visibleIndexedModelIndex = modelIndex - m_firstVisibleIndex;
946 if (visibleIndexedModelIndex >= 0 && visibleIndexedModelIndex < m_visibleItems.count())
947 return m_visibleItems[visibleIndexedModelIndex];
949 return nullptr;
952void ListViewWithPageHeader::layout()
954 if (m_inLayout)
955 return;
957 m_inLayout = true;
958 if (!m_visibleItems.isEmpty()) {
959 const qreal visibleFrom = contentY() - m_clipItem->y() + m_headerItemShownHeight;
960 const qreal visibleTo = contentY() + height() - m_clipItem->y();
962 qreal pos = m_visibleItems.first()->y();
964// qDebug() << "ListViewWithPageHeader::layout Updating positions and heights. contentY" << contentY() << "minYExtent" << minYExtent();
965 int firstReallyVisibleItem = -1;
966 int modelIndex = m_firstVisibleIndex;
967 Q_FOREACH(ListItem *item, m_visibleItems) {
968 const bool cull = pos + item->height() < visibleFrom || pos >= visibleTo;
969 item->setCulled(cull);
970 item->setY(pos);
971 if (!cull && firstReallyVisibleItem == -1) {
972 firstReallyVisibleItem = modelIndex;
973 if (m_topSectionItem) {
974 // Update the top sticky section header
975 const QString section = m_delegateModel->stringValue(modelIndex, m_sectionProperty);
976 QQmlContext *context = QQmlEngine::contextForObject(m_topSectionItem)->parentContext();
977 context->setContextProperty(QLatin1String("section"), section);
979 // Positing the top section sticky item is a two step process
980 // First we set it either we cull it (because it doesn't need to be sticked to the top)
981 // or stick it to the top
982 // Then after the loop we'll make sure that if there's another section just below it
983 // pushed the sticky section up to make it disappear
984 const qreal topSectionStickPos = m_headerItemShownHeight + contentY() - m_clipItem->y();
985 if (topSectionStickPos <= pos) {
986 QQuickItemPrivate::get(m_topSectionItem)->setCulled(true);
987 if (item->m_sectionItem) {
988 // This seems it should happen since why would we cull the top section
989 // if the first visible item has no section header? This only happens briefly
990 // when increasing the height of a list that is at the bottom, the m_topSectionItem
991 // gets shown shortly in the next polish call
992 QQuickItemPrivate::get(item->m_sectionItem)->setCulled(false);
993 }
994 } else {
995 QQuickItemPrivate::get(m_topSectionItem)->setCulled(false);
996 m_topSectionItem->setY(topSectionStickPos);
997 if (item->m_sectionItem) {
998 QQuickItemPrivate::get(item->m_sectionItem)->setCulled(true);
999 }
1003 QQmlContext *context = QQmlEngine::contextForObject(item->m_item)->parentContext();
1004 const qreal clipFrom = visibleFrom + (!item->m_sectionItem && m_topSectionItem && !QQuickItemPrivate::get(m_topSectionItem)->culled ? m_topSectionItem->height() : 0);
1005 if (!cull && pos < clipFrom) {
1006 context->setContextProperty(QLatin1String("heightToClip"), clipFrom - pos);
1007 } else {
1008 context->setContextProperty(QLatin1String("heightToClip"), QVariant::fromValue<int>(0));
1010// qDebug() << "ListViewWithPageHeader::layout" << item->m_item;
1011 pos += item->height();
1012 ++modelIndex;
1015 // Second step of section sticky item positioning
1016 // Look at the next section header, check if it's pushing up the sticky one
1017 if (m_topSectionItem) {
1018 if (firstReallyVisibleItem >= 0) {
1019 for (int i = firstReallyVisibleItem - m_firstVisibleIndex + 1; i < m_visibleItems.count(); ++i) {
1020 ListItem *item = m_visibleItems[i];
1021 if (item->m_sectionItem) {
1022 if (m_topSectionItem->y() + m_topSectionItem->height() > item->y()) {
1023 m_topSectionItem->setY(item->y() - m_topSectionItem->height());
1025 break;
1031 m_inLayout = false;
1034void ListViewWithPageHeader::updatePolish()
1036 Q_FOREACH(ListItem *item, m_itemsToRelease)
1037 reallyReleaseItem(item);
1038 m_itemsToRelease.clear();
1040 if (!model())
1041 return;
1043 layout();
1045 refill();
1047 if (m_contentHeightDirty) {
1048 qreal contentHeight;
1049 if (m_visibleItems.isEmpty()) {
1050 contentHeight = m_headerItem ? m_headerItem->height() : 0;
1051 } else {
1052 const int modelCount = model()->rowCount();
1053 const int visibleItems = m_visibleItems.count();
1054 const int lastValidIndex = m_firstVisibleIndex + visibleItems - 1;
1055 qreal nonCreatedHeight = 0;
1056 if (lastValidIndex != modelCount - 1) {
1057 const int visibleItems = m_visibleItems.count();
1058 qreal visibleItemsHeight = 0;
1059 Q_FOREACH(ListItem *item, m_visibleItems) {
1060 visibleItemsHeight += item->height();
1062 const int unknownSizes = modelCount - (m_firstVisibleIndex + visibleItems);
1063 nonCreatedHeight = unknownSizes * visibleItemsHeight / visibleItems;
1065 ListItem *item = m_visibleItems.last();
1066 contentHeight = nonCreatedHeight + item->y() + item->height() + m_clipItem->y();
1067 if (m_firstVisibleIndex != 0) {
1068 // Make sure that if we are shrinking we tell the view we still fit
1069 m_minYExtent = qMax(m_minYExtent, -(contentHeight - height()));
1073 m_contentHeightDirty = false;
1074 setContentHeight(contentHeight);
1078#include "moc_listviewwithpageheader.cpp"