on 631e710 help sign in
unity8/plugins/ListViewWithPageHeader/listviewwithpageheader.cpp
1014 lines 39 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 * Note that minYExtent and height are not always totally accurate, since
74 * we don't have the items created we can't guess their heights
75 * so we can only guarantee the values are correct when the first/last
76 * items of the list are visible, otherwise we just live with good enough
77 * values that make the list scrollable
78 *
79 * There are a few things that are not really implemented or tested properly
80 * which we don't use at the moment like changing the model, changing
81 * the section delegate, having a section delegate that changes its size, etc.
82 * The known missing features are marked with TODOs along the code.
83 */
85#include "listviewwithpageheader.h"
87#include <QDebug>
88#include <qqmlinfo.h>
89#include <qqmlengine.h>
90#include <private/qquickvisualdatamodel_p.h>
91#include <private/qqmlglobal_p.h>
92#include <private/qquickitem_p.h>
93#include <private/qquickanimation_p.h>
94// #include <private/qquickrectangle_p.h>
96qreal ListViewWithPageHeader::ListItem::height() const
98 return m_item->height() + (m_sectionItem ? m_sectionItem->height() : 0);
101qreal ListViewWithPageHeader::ListItem::y() const
103 return m_item->y() - (m_sectionItem ? m_sectionItem->height() : 0);
106void ListViewWithPageHeader::ListItem::setY(qreal newY)
108 if (m_sectionItem) {
109 m_sectionItem->setY(newY);
110 m_item->setY(newY + m_sectionItem->height());
111 } else {
112 m_item->setY(newY);
113 }
116bool ListViewWithPageHeader::ListItem::culled() const
118 return QQuickItemPrivate::get(m_item)->culled;
121void ListViewWithPageHeader::ListItem::setCulled(bool culled)
123 QQuickItemPrivate::get(m_item)->setCulled(culled);
124 if (m_sectionItem)
125 QQuickItemPrivate::get(m_sectionItem)->setCulled(culled);
128ListViewWithPageHeader::ListViewWithPageHeader()
129 : m_delegateModel(nullptr)
130 , m_asyncRequestedIndex(-1)
131 , m_delegateValidated(false)
132 , m_firstVisibleIndex(-1)
133 , m_minYExtent(0)
134 , m_contentHeightDirty(false)
135 , m_headerItem(nullptr)
136 , m_previousContentY(0)
137 , m_headerItemShownHeight(0)
138 , m_sectionDelegate(nullptr)
139 , m_topSectionItem(nullptr)
140 , m_forceNoClip(false)
142 m_clipItem = new QQuickItem(contentItem());
143// m_clipItem = new QQuickRectangle(contentItem());
144// ((QQuickRectangle*)m_clipItem)->setColor(Qt::gray);
146 m_headerShowAnimation = new QQuickNumberAnimation(this);
147 m_headerShowAnimation->setEasing(QEasingCurve::OutQuad);
148 m_headerShowAnimation->setProperty("contentY");
149 m_headerShowAnimation->setDuration(200);
150 m_headerShowAnimation->setTargetObject(this);
152 connect(this, SIGNAL(contentWidthChanged()), this, SLOT(onContentWidthChanged()));
153 connect(this, SIGNAL(contentHeightChanged()), this, SLOT(onContentHeightChanged()));
154 connect(this, SIGNAL(heightChanged()), this, SLOT(onHeightChanged()));
157ListViewWithPageHeader::~ListViewWithPageHeader()
161QAbstractItemModel *ListViewWithPageHeader::model() const
163 return m_delegateModel ? m_delegateModel->model().value<QAbstractItemModel *>() : nullptr;
166void ListViewWithPageHeader::setModel(QAbstractItemModel *model)
168 if (model != this->model()) {
169 if (!m_delegateModel) {
170 createDelegateModel();
171 } else {
172 disconnect(m_delegateModel, SIGNAL(modelUpdated(QQuickChangeSet,bool)), this, SLOT(onModelUpdated(QQuickChangeSet,bool)));
173 }
174 m_delegateModel->setModel(QVariant::fromValue<QAbstractItemModel *>(model));
175 connect(m_delegateModel, SIGNAL(modelUpdated(QQuickChangeSet,bool)), this, SLOT(onModelUpdated(QQuickChangeSet,bool)));
176 Q_EMIT modelChanged();
177 // TODO?
178// Q_EMIT contentHeightChanged();
179// Q_EMIT contentYChanged();
180 }
183QQmlComponent *ListViewWithPageHeader::delegate() const
185 return m_delegateModel ? m_delegateModel->delegate() : nullptr;
188void ListViewWithPageHeader::setDelegate(QQmlComponent *delegate)
190 if (delegate != this->delegate()) {
191 if (!m_delegateModel) {
192 createDelegateModel();
193 }
195 // Cleanup the existing items
196 foreach(ListItem *item, m_visibleItems)
197 releaseItem(item);
198 m_visibleItems.clear();
199 m_firstVisibleIndex = -1;
200 adjustMinYExtent();
201 setContentY(0);
202 m_clipItem->setY(0);
203 if (m_topSectionItem) {
204 QQuickItemPrivate::get(m_topSectionItem)->setCulled(true);
205 }
207 m_delegateModel->setDelegate(delegate);
209 Q_EMIT delegateChanged();
210 m_delegateValidated = false;
211 m_contentHeightDirty = true;
212 polish();
213 }
216QQuickItem *ListViewWithPageHeader::header() const
218 return m_headerItem;
221void ListViewWithPageHeader::setHeader(QQuickItem *headerItem)
223 if (m_headerItem != headerItem) {
224 qreal oldHeaderHeight = 0;
225 qreal oldHeaderY = 0;
226 if (m_headerItem) {
227 oldHeaderHeight = m_headerItem->height();
228 oldHeaderY = m_headerItem->y();
229 QQuickItemPrivate::get(m_headerItem)->removeItemChangeListener(this, QQuickItemPrivate::Geometry);
230 m_headerItem->setParentItem(nullptr);
231 }
232 m_headerItem = headerItem;
233 if (m_headerItem) {
234 m_headerItem->setParentItem(contentItem());
235 m_headerItem->setZ(1);
236 QQuickItemPrivate::get(m_headerItem)->addItemChangeListener(this, QQuickItemPrivate::Geometry);
237 }
238 qreal newHeaderHeight = m_headerItem ? m_headerItem->height() : 0;
239 if (!m_visibleItems.isEmpty() && newHeaderHeight != oldHeaderHeight) {
240 headerHeightChanged(newHeaderHeight, oldHeaderHeight, oldHeaderY);
241 polish();
242 m_contentHeightDirty = true;
243 }
244 Q_EMIT headerChanged();
245 }
248QQmlComponent *ListViewWithPageHeader::sectionDelegate() const
250 return m_sectionDelegate;
253void ListViewWithPageHeader::setSectionDelegate(QQmlComponent *delegate)
255 if (delegate != m_sectionDelegate) {
256 // TODO clean existing sections
258 m_sectionDelegate = delegate;
260 m_topSectionItem = getSectionItem(QString());
261 m_topSectionItem->setZ(3);
262 QQuickItemPrivate::get(m_topSectionItem)->setCulled(true);
264 // TODO create sections for existing items
266 Q_EMIT sectionDelegateChanged();
267 }
270QString ListViewWithPageHeader::sectionProperty() const
272 return m_sectionProperty;
275void ListViewWithPageHeader::setSectionProperty(const QString &property)
277 if (property != m_sectionProperty) {
278 m_sectionProperty = property;
280 updateWatchedRoles();
282 // TODO recreate sections
284 Q_EMIT sectionPropertyChanged();
285 }
288bool ListViewWithPageHeader::forceNoClip() const
290 return m_forceNoClip;
293void ListViewWithPageHeader::setForceNoClip(bool noClip)
295 if (noClip != m_forceNoClip) {
296 m_forceNoClip = noClip;
297 updateClipItem();
298 Q_EMIT forceNoClipChanged();
299 }
302void ListViewWithPageHeader::positionAtBeginning()
304 qreal headerHeight = (m_headerItem ? m_headerItem->height() : 0);
305 if (m_firstVisibleIndex != 0) {
306 // This could be optimized by trying to reuse the interesection
307 // of items that may end up intersecting between the existing
308 // m_visibleItems and the items we are creating in the next loop
309 foreach(ListItem *item, m_visibleItems)
310 releaseItem(item);
311 m_visibleItems.clear();
312 m_firstVisibleIndex = -1;
314 // Create the item 0, it will be already correctly positioned at createItem()
315 m_clipItem->setY(0);
316 ListItem *item = createItem(0, false);
317 // Create the subsequent items
318 int modelIndex = 1;
319 qreal pos = item->y() + item->height();
320 const qreal buffer = height() / 2;
321 const qreal bufferTo = height() + buffer;
322 while (modelIndex < m_delegateModel->count() && pos <= bufferTo) {
323 if (!(item = createItem(modelIndex, false)))
324 break;
325 pos += item->height();
326 ++modelIndex;
327 }
329 m_previousContentY = m_visibleItems.first()->y() - headerHeight;
330 }
331 setContentY(m_visibleItems.first()->y() + m_clipItem->y() - headerHeight);
334void ListViewWithPageHeader::showHeader()
336 auto to = qMax(-minYExtent(), contentY() - m_headerItem->height() + m_headerItemShownHeight);
337 if (to != contentY()) {
338 m_headerShowAnimation->setTo(to);
339 m_headerShowAnimation->start();
340 }
343qreal ListViewWithPageHeader::minYExtent() const
345// qDebug() << "ListViewWithPageHeader::minYExtent" << m_minYExtent;
346 return m_minYExtent;
349void ListViewWithPageHeader::componentComplete()
351 if (m_delegateModel)
352 m_delegateModel->componentComplete();
354 QQuickFlickable::componentComplete();
356 polish();
359void ListViewWithPageHeader::viewportMoved(Qt::Orientations orient)
361 QQuickFlickable::viewportMoved(orient);
362// qDebug() << "ListViewWithPageHeader::viewportMoved" << contentY();
363 qreal diff = m_previousContentY - contentY();
364 if (m_headerItem) {
365 auto oldHeaderItemShownHeight = m_headerItemShownHeight;
366 if (contentY() < -m_minYExtent) {
367 // Stick the header item to the top when dragging down
368 m_headerItem->setY(contentY());
369 } else {
370 // We are going down (but it's not because of the rebound at the end)
371 // (but the header was not shown by it's own position)
372 // or the header is partially shown
373 const bool scrolledUp = m_previousContentY > contentY();
374 const bool notRebounding = contentY() + height() < contentHeight();
375 const bool notShownByItsOwn = contentY() + diff > m_headerItem->y() + m_headerItem->height();
377 if (!scrolledUp && contentY() == -m_minYExtent) {
378 m_headerItemShownHeight = 0;
379 m_headerItem->setY(contentY());
380 } else if ((scrolledUp && notRebounding && notShownByItsOwn) || (m_headerItemShownHeight > 0)) {
381 m_headerItemShownHeight += diff;
382 if (contentY() == -m_minYExtent) {
383 m_headerItemShownHeight = 0;
384 } else {
385 m_headerItemShownHeight = qBound(static_cast<qreal>(0.), m_headerItemShownHeight, m_headerItem->height());
386 }
387 if (m_headerItemShownHeight > 0) {
388 m_headerItem->setY(contentY() - m_headerItem->height() + m_headerItemShownHeight);
389 } else {
390 m_headerItem->setY(-m_minYExtent);
391 }
392 }
393 }
394 // We will be changing the clip item, need to accomadate for it
395 // otherwise we move the firstItem down/up twice (unless the
396 // show header animation is running, where we want to keep the viewport stable)
397 if (!m_headerShowAnimation->isRunning()) {
398 diff += oldHeaderItemShownHeight - m_headerItemShownHeight;
399 } else {
400 diff = -diff;
401 m_contentHeightDirty = true;
402 }
403 }
404 if (!m_visibleItems.isEmpty()) {
405 updateClipItem();
406 ListItem *firstItem = m_visibleItems.first();
407 firstItem->setY(firstItem->y() + diff);
408 if (m_headerShowAnimation->isRunning()) {
409 adjustMinYExtent();
410 }
411 }
413 m_previousContentY = contentY();
414 layout();
415 polish();
418void ListViewWithPageHeader::createDelegateModel()
420 m_delegateModel = new QQuickVisualDataModel(qmlContext(this), this);
421 connect(m_delegateModel, SIGNAL(createdItem(int,QQuickItem*)), this, SLOT(itemCreated(int,QQuickItem*)));
422 if (isComponentComplete())
423 m_delegateModel->componentComplete();
424 updateWatchedRoles();
427void ListViewWithPageHeader::refill()
429 if (!isComponentComplete()) {
430 return;
431 }
433 const qreal buffer = height() / 2;
434 const qreal from = contentY();
435 const qreal to = from + height();
436 const qreal bufferFrom = from - buffer;
437 const qreal bufferTo = to + buffer;
439 bool added = addVisibleItems(from, to, false);
440 bool removed = removeNonVisibleItems(bufferFrom, bufferTo);
441 added |= addVisibleItems(bufferFrom, bufferTo, true);
443 if (added || removed) {
444 m_contentHeightDirty = true;
445 }
448bool ListViewWithPageHeader::addVisibleItems(qreal fillFrom, qreal fillTo, bool asynchronous)
450 if (!delegate())
451 return false;
453 if (m_delegateModel->count() == 0)
454 return false;
456 ListItem *item;
457// qDebug() << "ListViewWithPageHeader::addVisibleItems" << fillFrom << fillTo << asynchronous;
459 int modelIndex = 0;
460 qreal pos = 0;
461 if (!m_visibleItems.isEmpty()) {
462 modelIndex = m_firstVisibleIndex + m_visibleItems.count();
463 item = m_visibleItems.last();
464 pos = item->y() + item->height() + m_clipItem->y();
465 }
466 bool changed = false;
467// qDebug() << (modelIndex < m_delegateModel->count()) << pos << fillTo;
468 while (modelIndex < m_delegateModel->count() && pos <= fillTo) {
469// qDebug() << "refill: append item" << modelIndex << "pos" << pos << "asynchronous" << asynchronous;
470 if (!(item = createItem(modelIndex, asynchronous)))
471 break;
472 pos += item->height();
473 ++modelIndex;
474 changed = true;
475 }
477 modelIndex = 0;
478 pos = 0;
479 if (!m_visibleItems.isEmpty()) {
480 modelIndex = m_firstVisibleIndex - 1;
481 item = m_visibleItems.first();
482 pos = item->y() + m_clipItem->y();
483 }
484 while (modelIndex >= 0 && pos > fillFrom) {
485// qDebug() << "refill: prepend item" << modelIndex << "pos" << pos << "fillFrom" << fillFrom << "asynchronous" << asynchronous;
486 if (!(item = createItem(modelIndex, asynchronous)))
487 break;
488 pos -= item->height();
489 --modelIndex;
490 changed = true;
491 }
493 return changed;
496void ListViewWithPageHeader::reallyReleaseItem(ListItem *listItem)
498 QQuickItem *item = listItem->m_item;
499 QQuickVisualModel::ReleaseFlags flags = m_delegateModel->release(item);
500 if (flags & QQuickVisualModel::Destroyed) {
501 item->setParentItem(nullptr);
502 }
503 delete listItem->m_sectionItem;
504 delete listItem;
507void ListViewWithPageHeader::releaseItem(ListItem *listItem)
509 QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(listItem->m_item);
510 itemPrivate->removeItemChangeListener(this, QQuickItemPrivate::Geometry);
511 m_itemsToRelease << listItem;
514void ListViewWithPageHeader::updateWatchedRoles()
516 if (m_delegateModel) {
517 QList<QByteArray> roles;
518 if (!m_sectionProperty.isEmpty())
519 roles << m_sectionProperty.toUtf8();
520 m_delegateModel->setWatchedRoles(roles);
521 }
524QQuickItem *ListViewWithPageHeader::getSectionItem(int modelIndex, bool alreadyInserted)
526 if (!m_sectionDelegate)
527 return nullptr;
529 const QString section = m_delegateModel->stringValue(modelIndex, m_sectionProperty);
530 if (modelIndex > 0) {
531 const QString prevSection = m_delegateModel->stringValue(modelIndex - 1, m_sectionProperty);
532 if (section == prevSection)
533 return nullptr;
534 }
535 if (modelIndex + 1 < model()->rowCount() && !alreadyInserted) {
536 // Already inserted items can't steal next section header
537 const QString nextSection = m_delegateModel->stringValue(modelIndex + 1, m_sectionProperty);
538 if (section == nextSection) {
539 // Steal the section header
540 ListItem *nextItem = itemAtIndex(modelIndex); // Not +1 since not yet inserted into m_visibleItems
541 if (nextItem) {
542 QQuickItem *sectionItem = nextItem->m_sectionItem;
543 nextItem->m_sectionItem = nullptr;
544 return sectionItem;
545 }
546 }
547 }
549 return getSectionItem(section);
552QQuickItem *ListViewWithPageHeader::getSectionItem(const QString &sectionText)
554 QQuickItem *sectionItem = nullptr;
556 QQmlContext *creationContext = m_sectionDelegate->creationContext();
557 QQmlContext *context = new QQmlContext(creationContext ? creationContext : qmlContext(this));
558 context->setContextProperty(QLatin1String("section"), sectionText);
559 QObject *nobj = m_sectionDelegate->beginCreate(context);
560 if (nobj) {
561 QQml_setParent_noEvent(context, nobj);
562 sectionItem = qobject_cast<QQuickItem *>(nobj);
563 if (!sectionItem) {
564 delete nobj;
565 } else {
566 sectionItem->setZ(2);
567 QQml_setParent_noEvent(sectionItem, m_clipItem);
568 sectionItem->setParentItem(m_clipItem);
569 }
570 } else {
571 delete context;
572 }
573 m_sectionDelegate->completeCreate();
575 // TODO attach to sectionItem so we can accomodate to it changing its height
577 return sectionItem;
580bool ListViewWithPageHeader::removeNonVisibleItems(qreal bufferFrom, qreal bufferTo)
582// qDebug() << "ListViewWithPageHeader::removeNonVisibleItems" << bufferFrom << bufferTo;
583 bool changed = false;
585 bool foundVisible = false;
586 int i = 0;
587 int removedItems = 0;
588 const auto oldFirstVisibleIndex = m_firstVisibleIndex;
589 while (i < m_visibleItems.count()) {
590 ListItem *item = m_visibleItems[i];
591 const qreal pos = item->y() + m_clipItem->y();
592// qDebug() << i << pos << (pos + item->height()) << bufferFrom << bufferTo;
593 if (pos + item->height() < bufferFrom || pos > bufferTo) {
594// qDebug() << "Releasing" << i << (pos + item->height() < bufferFrom) << pos + item->height() << bufferFrom << (pos > bufferTo) << pos << bufferTo;
595 releaseItem(item);
596 m_visibleItems.removeAt(i);
597 changed = true;
598 ++removedItems;
599 } else {
600 if (!foundVisible) {
601 foundVisible = true;
602 const int itemIndex = m_firstVisibleIndex + removedItems + i;
603 m_firstVisibleIndex = itemIndex;
604 }
605 ++i;
606 }
607 }
608 if (m_firstVisibleIndex != oldFirstVisibleIndex) {
609 adjustMinYExtent();
610 }
612 return changed;
615ListViewWithPageHeader::ListItem *ListViewWithPageHeader::createItem(int modelIndex, bool asynchronous)
617// qDebug() << "CREATE ITEM" << modelIndex;
618 if (asynchronous && m_asyncRequestedIndex != -1)
619 return nullptr;
621 m_asyncRequestedIndex = -1;
622 QQuickItem *item = m_delegateModel->item(modelIndex, asynchronous);
623 if (!item) {
624 m_asyncRequestedIndex = modelIndex;
625 return 0;
626 } else {
627// qDebug() << "ListViewWithPageHeader::createItem::We have the item" << modelIndex << item;
628 ListItem *listItem = new ListItem;
629 listItem->m_item = item;
630 listItem->m_sectionItem = getSectionItem(modelIndex, false /*Not yet inserted into m_visibleItems*/);
631 QQuickItemPrivate::get(item)->addItemChangeListener(this, QQuickItemPrivate::Geometry);
632 ListItem *prevItem = itemAtIndex(modelIndex - 1);
633 bool lostItem = false; // Is an item that we requested async but because of model changes
634 // it is no longer attached to any of the existing items (has no prev nor next item)
635 // nor is the first item
636 if (prevItem) {
637 listItem->setY(prevItem->y() + prevItem->height());
638 } else {
639 ListItem *nextItem = itemAtIndex(modelIndex + 1);
640 if (nextItem) {
641 listItem->setY(nextItem->y() - listItem ->height());
642 } else if (modelIndex == 0 && m_headerItem) {
643 listItem->setY(m_headerItem->height());
644 } else if (!m_visibleItems.isEmpty()) {
645 lostItem = true;
646 }
647 }
648 if (lostItem) {
649 releaseItem(listItem);
650 listItem = nullptr;
651 } else {
652 listItem->setCulled(listItem->y() + listItem->height() + m_clipItem->y() < contentY() || listItem->y() + m_clipItem->y() >= contentY() + height());
653 if (m_visibleItems.isEmpty()) {
654 m_visibleItems << listItem;
655 } else {
656 m_visibleItems.insert(modelIndex - m_firstVisibleIndex, listItem);
657 }
658 if (m_firstVisibleIndex < 0 || modelIndex < m_firstVisibleIndex) {
659 m_firstVisibleIndex = modelIndex;
660 }
661 adjustMinYExtent();
662 }
663 return listItem;
664 }
667void ListViewWithPageHeader::itemCreated(int modelIndex, QQuickItem *item)
669// qDebug() << "ListViewWithPageHeader::itemCreated" << modelIndex << item;
671 item->setParentItem(m_clipItem);
672 QQmlContext *context = QQmlEngine::contextForObject(item)->parentContext();
673 context->setContextProperty(QLatin1String("ListViewWithPageHeader"), this);
674 if (modelIndex == m_asyncRequestedIndex) {
675 createItem(modelIndex, false);
676 refill();
677 }
680void ListViewWithPageHeader::updateClipItem()
682 m_clipItem->setHeight(height() - m_headerItemShownHeight);
683 m_clipItem->setY(contentY() + m_headerItemShownHeight);
684 m_clipItem->setClip(!m_forceNoClip && m_headerItemShownHeight > 0);
687void ListViewWithPageHeader::onContentHeightChanged()
689 updateClipItem();
692void ListViewWithPageHeader::onContentWidthChanged()
694 m_clipItem->setWidth(contentItem()->width());
697void ListViewWithPageHeader::onHeightChanged()
699 setMaximumFlickVelocity(height() * 10);
700 setFlickDeceleration(height() * 2);
703void ListViewWithPageHeader::onModelUpdated(const QQuickChangeSet &changeSet, bool /*reset*/)
705 // TODO Do something with reset
706// qDebug() << "ListViewWithPageHeader::onModelUpdated" << changeSet << reset;
707 const auto oldFirstVisibleIndex = m_firstVisibleIndex;
709 foreach(const QQuickChangeSet::Remove &remove, changeSet.removes()) {
710// qDebug() << "ListViewWithPageHeader::onModelUpdated Remove" << remove;
711 if (remove.index + remove.count > m_firstVisibleIndex && remove.index < m_firstVisibleIndex + m_visibleItems.count()) {
712 const qreal oldFirstValidIndexPos = m_visibleItems.first()->y();
713 // If all the items we are removing are either not created or culled
714 // we have to grow down to avoid viewport changing
715 bool growDown = true;
716 for (int i = 0; growDown && i < remove.count; ++i) {
717 const int modelIndex = remove.index + i;
718 ListItem *item = itemAtIndex(modelIndex);
719 if (item && !item->culled()) {
720 growDown = false;
721 }
722 }
723 for (int i = remove.count - 1; i >= 0; --i) {
724 const int visibleIndex = remove.index + i - m_firstVisibleIndex;
725 if (visibleIndex >= 0 && visibleIndex < m_visibleItems.count()) {
726 ListItem *item = m_visibleItems[visibleIndex];
727 // Pass the section item down if needed
728 if (item->m_sectionItem && visibleIndex + 1 < m_visibleItems.count()) {
729 ListItem *nextItem = m_visibleItems[visibleIndex + 1];
730 if (!nextItem->m_sectionItem) {
731 nextItem->m_sectionItem = item->m_sectionItem;
732 item->m_sectionItem = nullptr;
733 }
734 }
735 releaseItem(item);
736 m_visibleItems.removeAt(visibleIndex);
737 }
738 }
739 if (growDown) {
740 adjustMinYExtent();
741 } else if (remove.index <= m_firstVisibleIndex && !m_visibleItems.isEmpty()) {
742 // We removed the first item that is the one that positions the rest
743 // position the new first item correctly
744 m_visibleItems.first()->setY(oldFirstValidIndexPos);
745 }
746 } else if (remove.index + remove.count <= m_firstVisibleIndex) {
747 m_firstVisibleIndex -= remove.count;
748 }
749 for (int i = remove.count - 1; i >= 0; --i) {
750 const int modelIndex = remove.index + i;
751 if (modelIndex == m_asyncRequestedIndex) {
752 m_asyncRequestedIndex = -1;
753 } else if (modelIndex < m_asyncRequestedIndex) {
754 m_asyncRequestedIndex--;
755 }
756 }
757 }
759 foreach(const QQuickChangeSet::Insert &insert, changeSet.inserts()) {
760// qDebug() << "ListViewWithPageHeader::onModelUpdated Insert" << insert.index << insert.count;
761 const bool insertingInValidIndexes = insert.index > m_firstVisibleIndex && insert.index < m_firstVisibleIndex + m_visibleItems.count();
762 const bool firstItemWithViewOnTop = insert.index == 0 && m_firstVisibleIndex == 0 && m_visibleItems.first()->y() + m_clipItem->y() > contentY();
763 if (insertingInValidIndexes || firstItemWithViewOnTop)
764 {
765 // If the items we are adding won't be really visible
766 // we grow up instead of down to not change the viewport
767 bool growUp = false;
768 if (!firstItemWithViewOnTop) {
769 for (int i = 0; i < m_visibleItems.count(); ++i) {
770 if (!m_visibleItems[i]->culled()) {
771 if (insert.index <= m_firstVisibleIndex + i) {
772 growUp = true;
773 }
774 break;
775 }
776 }
777 }
779 const qreal oldFirstValidIndexPos = m_visibleItems.first()->y();
780 for (int i = insert.count - 1; i >= 0; --i) {
781 const int modelIndex = insert.index + i;
782 ListItem *item = createItem(modelIndex, false);
783 if (growUp) {
784 ListItem *firstItem = m_visibleItems.first();
785 firstItem->setY(firstItem->y() - item->height());
786 adjustMinYExtent();
787 }
788 // Adding an item may break a "same section" chain, so check
789 // if we need adding a new section item
790 if (m_sectionDelegate) {
791 ListItem *nextItem = itemAtIndex(modelIndex + 1);
792 if (nextItem && !nextItem->m_sectionItem) {
793 nextItem->m_sectionItem = getSectionItem(modelIndex + 1, true /* alredy inserted into m_visibleItems*/);
794 if (growUp) {
795 ListItem *firstItem = m_visibleItems.first();
796 firstItem->setY(firstItem->y() - nextItem->m_sectionItem->height());
797 adjustMinYExtent();
798 }
799 }
800 }
801 }
802 if (firstItemWithViewOnTop) {
803 ListItem *firstItem = m_visibleItems.first();
804 firstItem->setY(oldFirstValidIndexPos);
805 }
806 } else if (insert.index <= m_firstVisibleIndex) {
807 m_firstVisibleIndex += insert.count;
808 }
810 for (int i = insert.count - 1; i >= 0; --i) {
811 const int modelIndex = insert.index + i;
812 if (modelIndex <= m_asyncRequestedIndex) {
813 m_asyncRequestedIndex++;
814 }
815 }
816 }
818 if (m_firstVisibleIndex != oldFirstVisibleIndex) {
819 adjustMinYExtent();
820 }
822 layout();
823 polish();
824 m_contentHeightDirty = true;
827void ListViewWithPageHeader::itemGeometryChanged(QQuickItem *item, const QRectF &newGeometry, const QRectF &oldGeometry)
829 const qreal heightDiff = newGeometry.height() - oldGeometry.height();
830 if (heightDiff != 0) {
831 if (item == m_headerItem) {
832 headerHeightChanged(newGeometry.height(), oldGeometry.height(), oldGeometry.y());
833 } else {
834 if (oldGeometry.y() + oldGeometry.height() + m_clipItem->y() < contentY() && !m_visibleItems.isEmpty()) {
835 ListItem *firstItem = m_visibleItems.first();
836 firstItem->setY(firstItem->y() - heightDiff);
837 adjustMinYExtent();
838 layout();
839 }
840 }
841 refill();
842 adjustMinYExtent();
843 polish();
844 m_contentHeightDirty = true;
845 }
848void ListViewWithPageHeader::headerHeightChanged(qreal newHeaderHeight, qreal oldHeaderHeight, qreal oldHeaderY)
850 const qreal heightDiff = newHeaderHeight - oldHeaderHeight;
851 if (m_headerItemShownHeight > 0) {
852 // If the header is shown because of the clip
853 // Change its size
854 m_headerItemShownHeight += heightDiff;
855 m_headerItemShownHeight = qBound(static_cast<qreal>(0.), m_headerItemShownHeight, newHeaderHeight);
856 updateClipItem();
857 adjustMinYExtent();
858 } else {
859 if (oldHeaderY + oldHeaderHeight > contentY()) {
860 // If the header is shown because its position
861 // Change its size
862 ListItem *firstItem = m_visibleItems.first();
863 firstItem->setY(firstItem->y() + heightDiff);
864 layout();
865 } else {
866 // If the header is not on screen, just change the start of the list
867 // so the viewport is not changed
868 adjustMinYExtent();
869 }
870 }
874void ListViewWithPageHeader::adjustMinYExtent()
876 if (m_visibleItems.isEmpty()) {
877 m_minYExtent = 0;
878 } else {
879 qreal nonCreatedHeight = 0;
880 if (m_firstVisibleIndex != 0) {
881 // Calculate the average height of items to estimate the position of the list start
882 const int visibleItems = m_visibleItems.count();
883 qreal visibleItemsHeight = 0;
884 foreach(ListItem *item, m_visibleItems) {
885 visibleItemsHeight += item->height();
886 }
887 nonCreatedHeight = m_firstVisibleIndex * visibleItemsHeight / visibleItems;
888// qDebug() << m_firstVisibleIndex << visibleItemsHeight << visibleItems << nonCreatedHeight;
889 }
890 m_minYExtent = nonCreatedHeight - m_visibleItems.first()->y() - m_clipItem->y() + (m_headerItem ? m_headerItem->height() : 0);
891 }
894ListViewWithPageHeader::ListItem *ListViewWithPageHeader::itemAtIndex(int modelIndex) const
896 const int visibleIndexedModelIndex = modelIndex - m_firstVisibleIndex;
897 if (visibleIndexedModelIndex >= 0 && visibleIndexedModelIndex < m_visibleItems.count())
898 return m_visibleItems[visibleIndexedModelIndex];
900 return nullptr;
903void ListViewWithPageHeader::layout()
905 if (!m_visibleItems.isEmpty()) {
906 const qreal visibleFrom = contentY() - m_clipItem->y() + m_headerItemShownHeight;
907 const qreal visibleTo = contentY() + height() - m_clipItem->y();
909 qreal pos = m_visibleItems.first()->y();
911// qDebug() << "ListViewWithPageHeader::layout Updating positions and heights. contentY" << contentY() << "minYExtent" << minYExtent();
912 int firstReallyVisibleItem = -1;
913 int modelIndex = m_firstVisibleIndex;
914 foreach(ListItem *item, m_visibleItems) {
915 const bool cull = pos + item->height() < visibleFrom || pos >= visibleTo;
916 item->setCulled(cull);
917 item->setY(pos);
918 if (!cull && firstReallyVisibleItem == -1) {
919 firstReallyVisibleItem = modelIndex;
920 if (m_topSectionItem) {
921 // Update the top sticky section header
922 const QString section = m_delegateModel->stringValue(modelIndex, m_sectionProperty);
923 QQmlContext *context = QQmlEngine::contextForObject(m_topSectionItem)->parentContext();
924 context->setContextProperty(QLatin1String("section"), section);
926 // Positing the top section sticky item is a two step process
927 // First we set it either we cull it (because it doesn't need to be sticked to the top)
928 // or stick it to the top
929 // Then after the loop we'll make sure that if there's another section just below it
930 // pushed the sticky section up to make it disappear
931 const qreal topSectionStickPos = m_headerItemShownHeight + contentY() - m_clipItem->y();
932 if (topSectionStickPos <= pos) {
933 QQuickItemPrivate::get(m_topSectionItem)->setCulled(true);
934 QQuickItemPrivate::get(item->m_sectionItem)->setCulled(false);
935 } else {
936 QQuickItemPrivate::get(m_topSectionItem)->setCulled(false);
937 m_topSectionItem->setY(topSectionStickPos);
938 if (item->m_sectionItem) {
939 QQuickItemPrivate::get(item->m_sectionItem)->setCulled(true);
940 }
941 }
942 }
943 }
944 QQmlContext *context = QQmlEngine::contextForObject(item->m_item)->parentContext();
945 if (!cull && pos < visibleFrom) {
946 context->setContextProperty(QLatin1String("heightToClip"), visibleFrom - pos);
947 } else {
948 context->setContextProperty(QLatin1String("heightToClip"), QVariant::fromValue<int>(0));
949 }
950// qDebug() << "ListViewWithPageHeader::layout" << item->m_item;
951 pos += item->height();
952 ++modelIndex;
953 }
955 // Second step of section sticky item positioning
956 // Look at the next section header, check if it's pushing up the sticky one
957 if (m_topSectionItem) {
958 if (firstReallyVisibleItem >= 0) {
959 for (int i = firstReallyVisibleItem - m_firstVisibleIndex + 1; i < m_visibleItems.count(); ++i) {
960 ListItem *item = m_visibleItems[i];
961 if (item->m_sectionItem) {
962 if (m_topSectionItem->y() + m_topSectionItem->height() > item->y()) {
963 m_topSectionItem->setY(item->y() - m_topSectionItem->height());
964 }
965 break;
966 }
967 }
968 }
969 }
970 }
973void ListViewWithPageHeader::updatePolish()
975 Q_FOREACH(ListItem *item, m_itemsToRelease)
976 reallyReleaseItem(item);
977 m_itemsToRelease.clear();
979 if (!model())
980 return;
982 layout();
984 refill();
986 if (m_contentHeightDirty) {
987 qreal contentHeight;
988 const int modelCount = model()->rowCount();
989 const int visibleItems = m_visibleItems.count();
990 const int lastValidIndex = m_firstVisibleIndex + visibleItems - 1;
991 if (lastValidIndex == modelCount - 1) {
992 ListItem *item = m_visibleItems.last();
993 contentHeight = item->y() + item->height() + m_clipItem->y();
994 if (m_firstVisibleIndex != 0) {
995 // Make sure that if we are shrinking we tell the view we still fit
996 m_minYExtent = qMax(m_minYExtent, -(contentHeight - height()));
997 }
998 } else {
999 contentHeight = m_headerItem ? m_headerItem->height() : 0;
1000 if (!m_visibleItems.isEmpty()) {
1001 foreach(ListItem *item, m_visibleItems) {
1002 contentHeight += item->height();
1004 const int unknownSizes = modelCount - visibleItems;
1005 contentHeight += unknownSizes * contentHeight / visibleItems;
1009 m_contentHeightDirty = false;
1010 setContentHeight(contentHeight);
1014#include "moc_listviewwithpageheader.cpp"