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