Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qqmllistmodel.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant
4
7
8#include <private/qjsvalue_p.h>
9
10#include <private/qqmlcustomparser_p.h>
11#include <private/qqmlengine_p.h>
12#include <private/qqmljsast_p.h>
13#include <private/qqmljsengine_p.h>
14#include <private/qqmllistwrapper_p.h>
15#include <private/qqmlnotifier_p.h>
16#include <private/qqmlopenmetaobject_p.h>
17
18#include <private/qv4alloca_p.h>
19#include <private/qv4dateobject_p.h>
20#include <private/qv4lookup_p.h>
21#include <private/qv4object_p.h>
22#include <private/qv4objectiterator_p.h>
23#include <private/qv4qmlcontext_p.h>
24#include <private/qv4sequenceobject_p.h>
25#include <private/qv4urlobject_p.h>
26
27#include <qqmlcontext.h>
28#include <qqmlinfo.h>
29
30#include <QtCore/qdebug.h>
31#include <QtCore/qstack.h>
32#include <QXmlStreamReader>
33#include <QtCore/qdatetime.h>
34#include <QScopedValueRollback>
35
36Q_DECLARE_METATYPE(const QV4::CompiledData::Binding*);
37
38#include <algorithm>
39#include <vector>
40
41QT_BEGIN_NAMESPACE
42
43// Set to 1024 as a debugging aid - easier to distinguish uids from indices of elements/models.
44enum { MIN_LISTMODEL_UID = 1024 };
45
46static QAtomicInt uidCounter(MIN_LISTMODEL_UID);
47
48template <typename T>
49static bool isMemoryUsed(const char *mem)
50{
51 for (size_t i=0 ; i < sizeof(T) ; ++i) {
52 if (mem[i] != 0)
53 return true;
54 }
55
56 return false;
57}
58
60{
61 static const QString roleTypeNames[] = {
62 QStringLiteral("String"), QStringLiteral("Number"), QStringLiteral("Bool"),
63 QStringLiteral("List"), QStringLiteral("QObject"), QStringLiteral("VariantMap"),
64 QStringLiteral("DateTime"), QStringLiteral("Url"), QStringLiteral("Function")
65 };
66
68 return roleTypeNames[t];
69
70 return QString();
71}
72
73const ListLayout::Role &ListLayout::getRoleOrCreate(const QString &key, Role::DataType type)
74{
75 QStringHash<Role *>::Node *node = roleHash.findNode(key);
76 if (node) {
77 const Role &r = *node->value;
78 if (type != r.type)
79 qmlWarning(nullptr) << QStringLiteral("Can't assign to existing role '%1' of different type [%2 -> %3]").arg(r.name).arg(roleTypeName(type)).arg(roleTypeName(r.type));
80 return r;
81 }
82
83 return createRole(key, type);
84}
85
86const ListLayout::Role &ListLayout::getRoleOrCreate(QV4::String *key, Role::DataType type)
87{
88 QStringHash<Role *>::Node *node = roleHash.findNode(key);
89 if (node) {
90 const Role &r = *node->value;
91 if (type != r.type)
92 qmlWarning(nullptr) << QStringLiteral("Can't assign to existing role '%1' of different type [%2 -> %3]").arg(r.name).arg(roleTypeName(type)).arg(roleTypeName(r.type));
93 return r;
94 }
95
96 QString qkey = key->toQString();
97
98 return createRole(qkey, type);
99}
100
101const ListLayout::Role &ListLayout::createRole(const QString &key, ListLayout::Role::DataType type)
102{
103 const int dataSizes[] = {
104 sizeof(StringOrTranslation),
105 sizeof(double),
106 sizeof(bool),
107 sizeof(ListModel *),
108 sizeof(QV4::PersistentValue),
109 sizeof(QVariantMap),
110 sizeof(QDateTime),
111 sizeof(QUrl),
112 sizeof(QJSValue)
113 };
114 const int dataAlignments[] = {
115 alignof(StringOrTranslation),
116 alignof(double),
117 alignof(bool),
118 alignof(ListModel *),
119 alignof(QV4::PersistentValue),
120 alignof(QVariantMap),
121 alignof(QDateTime),
122 alignof(QUrl),
123 alignof(QJSValue)
124 };
125
126 Role *r = new Role;
127 r->name = key;
128 r->type = type;
129
130 if (type == Role::List) {
131 r->subLayout = new ListLayout;
132 } else {
133 r->subLayout = nullptr;
134 }
135
136 int dataSize = dataSizes[type];
137 int dataAlignment = dataAlignments[type];
138
139 int dataOffset = (currentBlockOffset + dataAlignment-1) & ~(dataAlignment-1);
140 if (dataOffset + dataSize > ListElement::BLOCK_SIZE) {
141 r->blockIndex = ++currentBlock;
142 r->blockOffset = 0;
143 currentBlockOffset = dataSize;
144 } else {
145 r->blockIndex = currentBlock;
146 r->blockOffset = dataOffset;
147 currentBlockOffset = dataOffset + dataSize;
148 }
149
150 int roleIndex = roles.size();
151 r->index = roleIndex;
152
153 roles.append(r);
154 roleHash.insert(key, r);
155
156 return *r;
157}
158
159ListLayout::ListLayout(const ListLayout *other) : currentBlock(0), currentBlockOffset(0)
160{
161 const int otherRolesCount = other->roles.size();
162 roles.reserve(otherRolesCount);
163 for (int i=0 ; i < otherRolesCount; ++i) {
164 Role *role = new Role(other->roles[i]);
165 roles.append(role);
166 roleHash.insert(role->name, role);
167 }
168 currentBlockOffset = other->currentBlockOffset;
169 currentBlock = other->currentBlock;
170}
171
173{
174 qDeleteAll(roles);
175}
176
178{
179 int roleOffset = target->roles.size();
180 int newRoleCount = src->roles.size() - roleOffset;
181
182 for (int i=0 ; i < newRoleCount ; ++i) {
183 Role *role = new Role(src->roles[roleOffset + i]);
184 target->roles.append(role);
185 target->roleHash.insert(role->name, role);
186 }
187
188 target->currentBlockOffset = src->currentBlockOffset;
189 target->currentBlock = src->currentBlock;
190}
191
192ListLayout::Role::Role(const Role *other)
193{
194 name = other->name;
195 type = other->type;
198 index = other->index;
199 if (other->subLayout)
201 else
202 subLayout = nullptr;
203}
204
206{
207 delete subLayout;
208}
209
210const ListLayout::Role *ListLayout::getRoleOrCreate(const QString &key, const QVariant &data)
211{
212 Role::DataType type;
213
214 switch (data.userType()) {
215 case QMetaType::Double: type = Role::Number; break;
216 case QMetaType::Int: type = Role::Number; break;
217 case QMetaType::Bool: type = Role::Bool; break;
218 case QMetaType::QString: type = Role::String; break;
219 case QMetaType::QVariantMap: type = Role::VariantMap; break;
220 case QMetaType::QDateTime: type = Role::DateTime; break;
221 case QMetaType::QUrl: type = Role::Url; break;
222 default: {
223 if (data.userType() == qMetaTypeId<QJSValue>() &&
224 data.value<QJSValue>().isCallable()) {
225 type = Role::Function;
226 break;
227 } else if (data.userType() == qMetaTypeId<const QV4::CompiledData::Binding*>()
228 && data.value<const QV4::CompiledData::Binding*>()->isTranslationBinding()) {
229 type = Role::String;
230 break;
231 } else if (data.userType() >= QMetaType::User) {
232 type = Role::List;
233 break;
234 } else {
235 type = Role::Invalid;
236 break;
237 }
238 }
239 }
240
241 if (type == Role::Invalid) {
242 qmlWarning(nullptr) << "Can't create role for unsupported data type";
243 return nullptr;
244 }
245
246 return &getRoleOrCreate(key, type);
247}
248
249const ListLayout::Role *ListLayout::getExistingRole(const QString &key) const
250{
251 Role *r = nullptr;
252 QStringHash<Role *>::Node *node = roleHash.findNode(key);
253 if (node)
254 r = node->value;
255 return r;
256}
257
258const ListLayout::Role *ListLayout::getExistingRole(QV4::String *key) const
259{
260 Role *r = nullptr;
261 QStringHash<Role *>::Node *node = roleHash.findNode(key);
262 if (node)
263 r = node->value;
264 return r;
265}
266
268{
269 clear();
270}
271
272void StringOrTranslation::setString(const QString &s)
273{
274 clear();
275 if (s.isEmpty())
276 return;
277 QString::DataPointer dataPointer = s.data_ptr();
278 arrayData = dataPointer.d_ptr();
279 stringData = dataPointer.data();
280 stringSize = dataPointer.size;
281 if (arrayData)
282 arrayData->ref();
283}
284
285void StringOrTranslation::setTranslation(const QV4::CompiledData::Binding *binding)
286{
287 clear();
288 this->binding = binding;
289}
290
291QString StringOrTranslation::toString(const QQmlListModel *owner) const
292{
293 if (stringSize) {
294 if (arrayData)
295 arrayData->ref();
296 return QString(QStringPrivate(arrayData, stringData, stringSize));
297 }
298 if (!owner)
299 return QString();
300 return owner->m_compilationUnit->bindingValueAsString(binding);
301}
302
304{
305 if (!arrayData)
306 return QString();
307 arrayData->ref();
308 return QString(QStringPrivate(arrayData, stringData, stringSize));
309}
310
311void StringOrTranslation::clear()
312{
313 if (arrayData && !arrayData->deref())
314 QTypedArrayData<ushort>::deallocate(arrayData);
315 arrayData = nullptr;
316 stringData = nullptr;
317 stringSize = 0;
318 binding = nullptr;
319}
320
321QObject *ListModel::getOrCreateModelObject(QQmlListModel *model, int elementIndex)
322{
323 ListElement *e = elements[elementIndex];
324 if (e->m_objectCache == nullptr) {
325 void *memory = operator new(sizeof(QObject) + sizeof(QQmlData));
326 void *ddataMemory = ((char *)memory) + sizeof(QObject);
327 e->m_objectCache = new (memory) QObject;
328
329 const QAbstractDeclarativeData *old = std::exchange(
330 QObjectPrivate::get(e->m_objectCache)->declarativeData,
331 new (ddataMemory) QQmlData(QQmlData::DoesNotOwnMemory));
332 Q_ASSERT(!old); // QObject should really not manipulate QQmlData
333
334 (void)new ModelNodeMetaObject(e->m_objectCache, model, elementIndex);
335 }
336 return e->m_objectCache;
337}
338
339bool ListModel::sync(ListModel *src, ListModel *target)
340{
341 // Sanity check
342
343 bool hasChanges = false;
344
345 // Build hash of elements <-> uid for each of the lists
346 QHash<int, ElementSync> elementHash;
347 for (int i = 0; i < target->elementCount(); ++i) {
348 ListElement *e = target->elements[i];
349 int uid = e->getUid();
350 ElementSync sync;
351 sync.target = e;
352 sync.targetIndex = i;
353 elementHash.insert(uid, sync);
354 }
355 for (int i = 0; i < src->elementCount(); ++i) {
356 ListElement *e = src->elements[i];
357 int uid = e->getUid();
358
359 QHash<int, ElementSync>::iterator it = elementHash.find(uid);
360 if (it == elementHash.end()) {
361 ElementSync sync;
362 sync.src = e;
363 sync.srcIndex = i;
364 elementHash.insert(uid, sync);
365 } else {
366 ElementSync &sync = it.value();
367 sync.src = e;
368 sync.srcIndex = i;
369 }
370 }
371
372 QQmlListModel *targetModel = target->m_modelCache;
373
374 // Get list of elements that are in the target but no longer in the source. These get deleted first.
375 int rowsRemoved = 0;
376 for (int i = 0 ; i < target->elementCount() ; ++i) {
377 ListElement *element = target->elements[i];
378 ElementSync &s = elementHash.find(element->getUid()).value();
379 Q_ASSERT(s.targetIndex >= 0);
380 // need to update the targetIndex, to keep it correct after removals
381 s.targetIndex -= rowsRemoved;
382 if (s.src == nullptr) {
383 Q_ASSERT(s.targetIndex == i);
384 hasChanges = true;
385 if (targetModel)
386 targetModel->beginRemoveRows(QModelIndex(), i, i);
387 s.target->destroy(target->m_layout);
388 if (auto it = std::find(target->elements.begin(), target->elements.end(), s.target);
389 it != target->elements.end()) {
390 target->elements.erase(it);
391 }
392 delete s.target;
393 if (targetModel)
394 targetModel->endRemoveRows();
395 ++rowsRemoved;
396 --i;
397 continue;
398 }
399 }
400
401 // Sync the layouts
402 ListLayout::sync(src->m_layout, target->m_layout);
403
404 // Clear the target list, and append in correct order from the source
405 target->elements.clear();
406 for (int i = 0; i < src->elementCount(); ++i) {
407 ListElement *srcElement = src->elements[i];
408 ElementSync &s = elementHash.find(srcElement->getUid()).value();
409 Q_ASSERT(s.srcIndex >= 0);
410 ListElement *targetElement = s.target;
411 if (targetElement == nullptr) {
412 targetElement = new ListElement(srcElement->getUid());
413 }
414 s.changedRoles = ListElement::sync(srcElement, src->m_layout, targetElement, target->m_layout);
415 target->elements.push_back(targetElement);
416 }
417
418 target->updateCacheIndices();
419
420 // Update values stored in target meta objects
421 for (ListElement *e : target->elements) {
422 if (ModelNodeMetaObject *mo = e->objectCache())
423 mo->updateValues();
424 }
425
426 // now emit the change notifications required. This can be safely done, as we're only emitting changes, moves and inserts,
427 // so the model indices can't be out of bounds
428 //
429 // to ensure things are kept in the correct order, emit inserts and moves first. This shouls ensure all persistent
430 // model indices are updated correctly
431 //
432 // All rows before i are in their final place, so s.targetIndex always tracks the current
433 // position of a row that still has to be placed, and that position is never before i.
434 const int targetElementCount = target->elementCount();
435 for (int i = 0 ; i < targetElementCount ; ++i) {
436 ListElement *element = target->elements[i];
437 ElementSync &s = elementHash.find(element->getUid()).value();
438 Q_ASSERT(s.srcIndex >= 0);
439 const bool inserted = s.targetIndex == -1;
440 if (s.targetIndex != i) {
441 // rows between i and the old position (all rows, for an insertion) move down by one
442 const int oldIndex = s.targetIndex;
443 if (targetModel) {
444 if (inserted) {
445 targetModel->beginInsertRows(QModelIndex(), i, i);
446 targetModel->endInsertRows();
447 } else {
448 Q_ASSERT(oldIndex > i);
449 targetModel->beginMoveRows(QModelIndex(), oldIndex, oldIndex, QModelIndex(), i);
450 targetModel->endMoveRows();
451 }
452 }
453 for (int j = i + 1; j < targetElementCount; ++j) {
454 ElementSync &sToFix = elementHash.find(target->elements[j]->getUid()).value();
455 if (sToFix.targetIndex != -1 && (inserted || sToFix.targetIndex < oldIndex))
456 sToFix.targetIndex += 1;
457 }
458 hasChanges = true;
459 s.targetIndex = i;
460 }
461 if (!inserted && !s.changedRoles.isEmpty()) {
462 QModelIndex idx = targetModel->createIndex(i, 0);
463 if (targetModel)
464 targetModel->dataChanged(idx, idx, s.changedRoles);
465 hasChanges = true;
466 }
467 }
468 return hasChanges;
469}
470
471ListModel::ListModel(ListLayout *layout, QQmlListModel *modelCache) : m_layout(layout), m_modelCache(modelCache)
472{
473}
474
476{
477 for (const auto &destroyer : remove(0, elementCount()))
478 destroyer();
479
480 m_layout = nullptr;
481 if (m_modelCache && m_modelCache->m_primary == false)
482 delete m_modelCache;
483 m_modelCache = nullptr;
484}
485
487{
488 int elementIndex = elementCount();
489 newElement(elementIndex);
490 return elementIndex;
491}
492
493void ListModel::insertElement(int index)
494{
495 newElement(index);
496 updateCacheIndices(index);
497}
498
499void ListModel::move(int from, int to, int n)
500{
501 if (from > to) {
502 // Only move forwards - flip if backwards moving
503 int tfrom = from;
504 int tto = to;
505 from = tto;
506 to = tto+n;
507 n = tfrom-tto;
508 }
509
510 // Rotate the [from, to + n) sub-range so the n-element block starting at
511 // 'from' moves to the end of the range; no temporary storage required.
512 std::rotate(elements.begin() + from,
513 elements.begin() + from + n,
514 elements.begin() + to + n);
515
516 updateCacheIndices(from, to + n);
517}
518
519void ListModel::newElement(int index)
520{
521 ListElement *e = new ListElement;
522 elements.insert(elements.begin() + index, e);
523}
524
525void ListModel::updateCacheIndices(int start, int end)
526{
527 int count = elementCount();
528
529 if (end < 0 || end > count)
530 end = count;
531
532 for (int i = start; i < end; ++i) {
533 ListElement *e = elements[i];
534 if (ModelNodeMetaObject *mo = e->objectCache())
535 mo->m_elementIndex = i;
536 }
537}
538
539QVariant ListModel::getProperty(int elementIndex, int roleIndex, const QQmlListModel *owner, QV4::ExecutionEngine *eng)
540{
541 if (roleIndex >= m_layout->roleCount())
542 return QVariant();
543 ListElement *e = elements[elementIndex];
544 const ListLayout::Role &r = m_layout->getExistingRole(roleIndex);
545 return e->getProperty(r, owner, eng);
546}
547
548ListModel *ListModel::getListProperty(int elementIndex, const ListLayout::Role &role)
549{
550 ListElement *e = elements[elementIndex];
551 return e->getListProperty(role);
552}
553
555{
556 for (ListElement *e : elements) {
557 if (ModelNodeMetaObject *cache = e->objectCache()) {
558 // TODO: more fine grained tracking?
559 cache->updateValues();
560 }
561 }
562}
563
564void ListModel::set(int elementIndex, QV4::Object *object, QList<int> *roles)
565{
566 ListElement *e = elements[elementIndex];
567
568 QV4::ExecutionEngine *v4 = object->engine();
569 QV4::Scope scope(v4);
570 QV4::ScopedObject o(scope);
571
572 QV4::ObjectIterator it(scope, object, QV4::ObjectIterator::EnumerableOnly);
573 QV4::ScopedString propertyName(scope);
574 QV4::ScopedValue propertyValue(scope);
575 QV4::ScopedFunctionObject func(scope);
576 QV4::ScopedObject obj(scope);
577 while (1) {
578 propertyName = it.nextPropertyNameAsString(propertyValue);
579 if (!propertyName)
580 break;
581
582 // Check if this key exists yet
583 int roleIndex = -1;
584
585 // Add the value now
586 if (const QV4::String *s = propertyValue->as<QV4::String>()) {
587 const ListLayout::Role &r = m_layout->getRoleOrCreate(propertyName, ListLayout::Role::String);
588 roleIndex = e->setStringProperty(r, s->toQString());
589 } else if (propertyValue->isNumber()) {
590 const ListLayout::Role &r = m_layout->getRoleOrCreate(propertyName, ListLayout::Role::Number);
591 roleIndex = e->setDoubleProperty(r, propertyValue->asDouble());
592 } else if (QV4::ArrayObject *a = propertyValue->as<QV4::ArrayObject>()) {
593 roleIndex = setArrayLike(&o, propertyName, e, a);
594 } else if (QV4::Sequence *s = propertyValue->as<QV4::Sequence>()) {
595 roleIndex = setArrayLike(&o, propertyName, e, s);
596 } else if (QV4::QmlListWrapper *l = propertyValue->as<QV4::QmlListWrapper>()) {
597 roleIndex = setArrayLike(&o, propertyName, e, l);
598 } else if (propertyValue->isBoolean()) {
599 const ListLayout::Role &r = m_layout->getRoleOrCreate(propertyName, ListLayout::Role::Bool);
600 roleIndex = e->setBoolProperty(r, propertyValue->booleanValue());
601 } else if (QV4::DateObject *dd = propertyValue->as<QV4::DateObject>()) {
602 const ListLayout::Role &r = m_layout->getRoleOrCreate(propertyName, ListLayout::Role::DateTime);
603 QDateTime dt = dd->toQDateTime();
604 roleIndex = e->setDateTimeProperty(r, dt);
605 } else if (QV4::UrlObject *url = propertyValue->as<QV4::UrlObject>()) {
606 const ListLayout::Role &r = m_layout->getRoleOrCreate(propertyName, ListLayout::Role::Url);
607 QUrl qurl = QUrl(url->href());
608 roleIndex = e->setUrlProperty(r, qurl);
609 } else if (QV4::FunctionObject *f = propertyValue->as<QV4::FunctionObject>()) {
610 const ListLayout::Role &r = m_layout->getRoleOrCreate(propertyName, ListLayout::Role::Function);
611 func =f;
612 QJSValue jsv;
613 QJSValuePrivate::setValue(&jsv, func);
614 roleIndex = e->setFunctionProperty(r, jsv);
615 } else if (QV4::Object *o = propertyValue->as<QV4::Object>()) {
616 if (QV4::QObjectWrapper *wrapper = o->as<QV4::QObjectWrapper>()) {
617 const ListLayout::Role &role = m_layout->getRoleOrCreate(propertyName, ListLayout::Role::QObject);
619 roleIndex = e->setQObjectProperty(role, wrapper);
620 } else if (QVariant maybeUrl = QV4::ExecutionEngine::toVariant(
621 // gc will hold on to o via the scoped propertyValue; fromReturnedValue is safe
622 QV4::Value::fromReturnedValue(o->asReturnedValue()),
623 QMetaType::fromType<QUrl>(), true);
624 maybeUrl.metaType() == QMetaType::fromType<QUrl>()) {
625 const ListLayout::Role &r = m_layout->getRoleOrCreate(propertyName, ListLayout::Role::Url);
626 QUrl qurl = maybeUrl.toUrl();
627 roleIndex = e->setUrlProperty(r, qurl);
628 } else {
629 const ListLayout::Role &role = m_layout->getRoleOrCreate(propertyName, ListLayout::Role::VariantMap);
631 obj = o;
632 roleIndex = e->setVariantMapProperty(role, obj);
633 }
634 }
635 } else if (propertyValue->isNullOrUndefined()) {
636 const ListLayout::Role *r = m_layout->getExistingRole(propertyName);
637 if (r)
638 e->clearProperty(*r);
639 }
640
641 if (roleIndex != -1)
642 roles->append(roleIndex);
643 }
644
645 if (ModelNodeMetaObject *mo = e->objectCache())
646 mo->updateValues(*roles);
647}
648
649void ListModel::set(int elementIndex, QV4::Object *object, ListModel::SetElement reason)
650{
651 if (!object)
652 return;
653
654 ListElement *e = elements[elementIndex];
655
656 QV4::ExecutionEngine *v4 = object->engine();
657 QV4::Scope scope(v4);
658
659 QV4::ObjectIterator it(scope, object, QV4::ObjectIterator::EnumerableOnly);
660 QV4::ScopedString propertyName(scope);
661 QV4::ScopedValue propertyValue(scope);
662 QV4::ScopedObject o(scope);
663 while (1) {
664 propertyName = it.nextPropertyNameAsString(propertyValue);
665 if (!propertyName)
666 break;
667
668 // Add the value now
669 if (QV4::String *s = propertyValue->stringValue()) {
670 const ListLayout::Role &r = m_layout->getRoleOrCreate(propertyName, ListLayout::Role::String);
672 e->setStringPropertyFast(r, s->toQString());
673 } else if (propertyValue->isNumber()) {
674 const ListLayout::Role &r = m_layout->getRoleOrCreate(propertyName, ListLayout::Role::Number);
676 e->setDoublePropertyFast(r, propertyValue->asDouble());
677 }
678 } else if (QV4::ArrayObject *a = propertyValue->as<QV4::ArrayObject>()) {
679 setArrayLikeFast(&o, propertyName, e, a);
680 } else if (QV4::Sequence *s = propertyValue->as<QV4::Sequence>()) {
681 setArrayLikeFast(&o, propertyName, e, s);
682 } else if (QV4::QmlListWrapper *l = propertyValue->as<QV4::QmlListWrapper>()) {
683 setArrayLikeFast(&o, propertyName, e, l);
684 } else if (propertyValue->isBoolean()) {
685 const ListLayout::Role &r = m_layout->getRoleOrCreate(propertyName, ListLayout::Role::Bool);
687 e->setBoolPropertyFast(r, propertyValue->booleanValue());
688 }
689 } else if (QV4::DateObject *date = propertyValue->as<QV4::DateObject>()) {
690 const ListLayout::Role &r = m_layout->getRoleOrCreate(propertyName, ListLayout::Role::DateTime);
692 QDateTime dt = date->toQDateTime();
693 e->setDateTimePropertyFast(r, dt);
694 }
695 } else if (QV4::UrlObject *url = propertyValue->as<QV4::UrlObject>()){
696 const ListLayout::Role &r = m_layout->getRoleOrCreate(propertyName, ListLayout::Role::Url);
698 QUrl qurl = QUrl(url->href()); // does what the private UrlObject->toQUrl would do
699 e->setUrlPropertyFast(r, qurl);
700 }
701 } else if (QV4::FunctionObject *f = propertyValue->as<QV4::FunctionObject>()) {
702 const ListLayout::Role &r =
703 m_layout->getRoleOrCreate(propertyName, ListLayout::Role::Function);
705 QJSValue jsv;
706 QJSValuePrivate::setValue(&jsv, *f);
707 e->setFunctionPropertyFast(r, jsv);
708 }
709 } else if (QV4::Object *o = propertyValue->as<QV4::Object>()) {
710 if (QV4::QObjectWrapper *wrapper = o->as<QV4::QObjectWrapper>()) {
711 const ListLayout::Role &r = m_layout->getRoleOrCreate(propertyName, ListLayout::Role::QObject);
713 e->setQObjectPropertyFast(r, wrapper);
714 } else {
715 QVariant maybeUrl = QV4::ExecutionEngine::toVariant(
716 // gc will hold on to o via the scoped propertyValue; fromReturnedValue is safe
717 QV4::Value::fromReturnedValue(o->asReturnedValue()),
718 QMetaType::fromType<QUrl>(), true);
719 if (maybeUrl.metaType() == QMetaType::fromType<QUrl>()) {
720 const QUrl qurl = maybeUrl.toUrl();
721 const ListLayout::Role &r = m_layout->getRoleOrCreate(propertyName, ListLayout::Role::Url);
723 e->setUrlPropertyFast(r, qurl);
724 } else {
725 const ListLayout::Role &role = m_layout->getRoleOrCreate(propertyName, ListLayout::Role::VariantMap);
727 e->setVariantMapFast(role, o);
728 }
729 }
730 } else if (propertyValue->isNullOrUndefined()) {
731 if (reason == SetElement::WasJustInserted) {
732 QQmlError err;
733 auto memberName = propertyName->toString(v4)->toQString();
734 err.setDescription(QString::fromLatin1("%1 is %2. Adding an object with a %2 member does not create a role for it.").arg(memberName, propertyValue->isNull() ? QLatin1String("null") : QLatin1String("undefined")));
735 qmlWarning(nullptr, err);
736 } else {
737 const ListLayout::Role *r = m_layout->getExistingRole(propertyName);
738 if (r)
739 e->clearProperty(*r);
740 }
741 }
742 }
743}
744
745QList<std::function<void()>> ListModel::remove(int index, int count)
746{
747 QList<std::function<void()>> toDestroy;
748 auto layout = m_layout;
749 for (int i=0 ; i < count ; ++i) {
750 auto element = elements[index+i];
751 toDestroy.append([element, layout](){
752 element->destroy(layout);
753 delete element;
754 });
755 }
756 elements.erase(elements.begin() + index, elements.begin() + index + count);
757 updateCacheIndices(index);
758 return toDestroy;
759}
760
761void ListModel::insert(int elementIndex, QV4::Object *object)
762{
763 insertElement(elementIndex);
764 set(elementIndex, object, SetElement::WasJustInserted);
765}
766
767int ListModel::append(QV4::Object *object)
768{
769 int elementIndex = appendElement();
770 set(elementIndex, object, SetElement::WasJustInserted);
771 return elementIndex;
772}
773
774int ListModel::setOrCreateProperty(int elementIndex, const QString &key, const QVariant &data)
775{
776 int roleIndex = -1;
777
778 if (elementIndex >= 0 && elementIndex < elementCount()) {
779 ListElement *e = elements[elementIndex];
780
781 const ListLayout::Role *r = m_layout->getRoleOrCreate(key, data);
782 if (r) {
783 roleIndex = e->setVariantProperty(*r, data);
784
785 ModelNodeMetaObject *cache = e->objectCache();
786
787 if (roleIndex != -1 && cache)
788 cache->updateValues(QList<int>(1, roleIndex));
789 }
790 }
791
792 return roleIndex;
793}
794
795int ListModel::setExistingProperty(int elementIndex, const QString &key, const QV4::Value &data, QV4::ExecutionEngine *eng)
796{
797 int roleIndex = -1;
798
799 if (elementIndex >= 0 && elementIndex < elementCount()) {
800 ListElement *e = elements[elementIndex];
801 const ListLayout::Role *r = m_layout->getExistingRole(key);
802 if (r)
803 roleIndex = e->setJsProperty(*r, data, eng);
804 }
805
806 return roleIndex;
807}
808
809inline char *ListElement::getPropertyMemory(const ListLayout::Role &role)
810{
811 ListElement *e = this;
812 int blockIndex = 0;
813 while (blockIndex < role.blockIndex) {
814 if (e->next == nullptr) {
815 e->next = new ListElement;
816 e->next->uid = uid;
817 }
818 e = e->next;
819 ++blockIndex;
820 }
821
822 char *mem = &e->data[role.blockOffset];
823 return mem;
824}
825
826ModelNodeMetaObject *ListElement::objectCache()
827{
828 if (!m_objectCache)
829 return nullptr;
830 return ModelNodeMetaObject::get(m_objectCache);
831}
832
833StringOrTranslation *ListElement::getStringProperty(const ListLayout::Role &role)
834{
835 char *mem = getPropertyMemory(role);
836 StringOrTranslation *s = reinterpret_cast<StringOrTranslation *>(mem);
837 return s;
838}
839
840QV4::QObjectWrapper *ListElement::getQObjectProperty(const ListLayout::Role &role)
841{
842 char *mem = getPropertyMemory(role);
843 QV4::PersistentValue *g = reinterpret_cast<QV4::PersistentValue *>(mem);
844 return g->as<QV4::QObjectWrapper>();
845}
846
847QVariantMap *ListElement::getVariantMapProperty(const ListLayout::Role &role)
848{
849 QVariantMap *map = nullptr;
850
851 char *mem = getPropertyMemory(role);
852 if (isMemoryUsed<QVariantMap>(mem))
853 map = reinterpret_cast<QVariantMap *>(mem);
854
855 return map;
856}
857
858QDateTime *ListElement::getDateTimeProperty(const ListLayout::Role &role)
859{
860 QDateTime *dt = nullptr;
861
862 char *mem = getPropertyMemory(role);
863 if (isMemoryUsed<QDateTime>(mem))
864 dt = reinterpret_cast<QDateTime *>(mem);
865
866 return dt;
867}
868
869QUrl *ListElement::getUrlProperty(const ListLayout::Role &role)
870{
871 QUrl *url = nullptr;
872
873 char *mem = getPropertyMemory(role);
874 if (isMemoryUsed<QUrl>(mem))
875 url = reinterpret_cast<QUrl *>(mem);
876
877 return url;
878}
879
880QJSValue *ListElement::getFunctionProperty(const ListLayout::Role &role)
881{
882 QJSValue *f = nullptr;
883
884 char *mem = getPropertyMemory(role);
885 if (isMemoryUsed<QJSValue>(mem))
886 f = reinterpret_cast<QJSValue *>(mem);
887
888 return f;
889}
890
891QV4::PersistentValue *
892ListElement::getGuardProperty(const ListLayout::Role &role)
893{
894 char *mem = getPropertyMemory(role);
895
896 bool existingGuard = false;
897 for (size_t i = 0; i < sizeof(QV4::PersistentValue);
898 ++i) {
899 if (mem[i] != 0) {
900 existingGuard = true;
901 break;
902 }
903 }
904
905 QV4::PersistentValue *g = nullptr;
906
907 if (existingGuard)
908 g = reinterpret_cast<QV4::PersistentValue *>(mem);
909
910 return g;
911}
912
913ListModel *ListElement::getListProperty(const ListLayout::Role &role)
914{
915 char *mem = getPropertyMemory(role);
916 ListModel **value = reinterpret_cast<ListModel **>(mem);
917 return *value;
918}
919
920QVariant ListElement::getProperty(const ListLayout::Role &role, const QQmlListModel *owner, QV4::ExecutionEngine *eng)
921{
922 char *mem = getPropertyMemory(role);
923
924 QVariant data;
925
926 switch (role.type) {
928 {
929 double *value = reinterpret_cast<double *>(mem);
930 data = *value;
931 }
932 break;
934 {
935 StringOrTranslation *value = reinterpret_cast<StringOrTranslation *>(mem);
936 if (value->isSet())
937 data = value->toString(owner);
938 else
939 data = QString();
940 }
941 break;
943 {
944 bool *value = reinterpret_cast<bool *>(mem);
945 data = *value;
946 }
947 break;
949 {
950 ListModel **value = reinterpret_cast<ListModel **>(mem);
951 ListModel *model = *value;
952
953 if (model) {
954 if (model->m_modelCache == nullptr) {
955 model->m_modelCache = new QQmlListModel(owner, model, eng);
956 QQmlEngine::setContextForObject(model->m_modelCache, QQmlEngine::contextForObject(owner));
957 }
958
959 QObject *object = model->m_modelCache;
960 data = QVariant::fromValue(object);
961 }
962 }
963 break;
965 {
966 QV4::PersistentValue *guard = reinterpret_cast<QV4::PersistentValue *>(mem);
967 data = QVariant::fromValue(guard->as<QV4::QObjectWrapper>()->object());
968 }
969 break;
971 {
972 if (isMemoryUsed<QVariantMap>(mem)) {
973 QVariantMap *map = reinterpret_cast<QVariantMap *>(mem);
974 data = *map;
975 }
976 }
977 break;
979 {
980 if (isMemoryUsed<QDateTime>(mem)) {
981 QDateTime *dt = reinterpret_cast<QDateTime *>(mem);
982 data = *dt;
983 }
984 }
985 break;
987 {
988 if (isMemoryUsed<QUrl>(mem)) {
989 QUrl *url = reinterpret_cast<QUrl *>(mem);
990 data = *url;
991 }
992 }
993 break;
995 {
996 if (isMemoryUsed<QJSValue>(mem)) {
997 QJSValue *func = reinterpret_cast<QJSValue *>(mem);
998 data = QVariant::fromValue(*func);
999 }
1000 }
1001 break;
1002 default:
1003 break;
1004 }
1005
1006 return data;
1007}
1008
1009int ListElement::setStringProperty(const ListLayout::Role &role, const QString &s)
1010{
1011 int roleIndex = -1;
1012
1013 if (role.type == ListLayout::Role::String) {
1014 char *mem = getPropertyMemory(role);
1015 StringOrTranslation *c = reinterpret_cast<StringOrTranslation *>(mem);
1016 bool changed;
1017 if (!c->isSet() || c->isTranslation())
1018 changed = true;
1019 else
1020 changed = c->asString().compare(s) != 0;
1021 c->setString(s);
1022 if (changed)
1023 roleIndex = role.index;
1024 }
1025
1026 return roleIndex;
1027}
1028
1029int ListElement::setDoubleProperty(const ListLayout::Role &role, double d)
1030{
1031 int roleIndex = -1;
1032
1033 if (role.type == ListLayout::Role::Number) {
1034 char *mem = getPropertyMemory(role);
1035 double *value = reinterpret_cast<double *>(mem);
1036 bool changed = *value != d;
1037 *value = d;
1038 if (changed)
1039 roleIndex = role.index;
1040 }
1041
1042 return roleIndex;
1043}
1044
1045int ListElement::setBoolProperty(const ListLayout::Role &role, bool b)
1046{
1047 int roleIndex = -1;
1048
1049 if (role.type == ListLayout::Role::Bool) {
1050 char *mem = getPropertyMemory(role);
1051 bool *value = reinterpret_cast<bool *>(mem);
1052 bool changed = *value != b;
1053 *value = b;
1054 if (changed)
1055 roleIndex = role.index;
1056 }
1057
1058 return roleIndex;
1059}
1060
1061int ListElement::setListProperty(const ListLayout::Role &role, ListModel *m)
1062{
1063 int roleIndex = -1;
1064
1065 if (role.type == ListLayout::Role::List) {
1066 char *mem = getPropertyMemory(role);
1067 ListModel **value = reinterpret_cast<ListModel **>(mem);
1068 if (*value && *value != m) {
1069 (*value)->destroy();
1070 delete *value;
1071 }
1072 *value = m;
1073 roleIndex = role.index;
1074 }
1075
1076 return roleIndex;
1077}
1078
1079int ListElement::setQObjectProperty(const ListLayout::Role &role, QV4::QObjectWrapper *o)
1080{
1081 int roleIndex = -1;
1082
1083 if (role.type == ListLayout::Role::QObject) {
1084 char *mem = getPropertyMemory(role);
1085 if (isMemoryUsed<QVariantMap>(mem))
1086 reinterpret_cast<QV4::PersistentValue *>(mem)->set(o->engine(), *o);
1087 else
1088 new (mem) QV4::PersistentValue(o->engine(), o);
1089 roleIndex = role.index;
1090 }
1091
1092 return roleIndex;
1093}
1094
1095int ListElement::setVariantMapProperty(const ListLayout::Role &role, QV4::Object *o)
1096{
1097 int roleIndex = -1;
1098
1100 char *mem = getPropertyMemory(role);
1101 if (isMemoryUsed<QVariantMap>(mem)) {
1102 QVariantMap *map = reinterpret_cast<QVariantMap *>(mem);
1103 map->~QMap();
1104 }
1105 new (mem) QVariantMap(o->engine()->variantMapFromJS(o));
1106 roleIndex = role.index;
1107 }
1108
1109 return roleIndex;
1110}
1111
1112int ListElement::setVariantMapProperty(const ListLayout::Role &role, QVariantMap *m)
1113{
1114 int roleIndex = -1;
1115
1117 char *mem = getPropertyMemory(role);
1118 if (isMemoryUsed<QVariantMap>(mem)) {
1119 QVariantMap *map = reinterpret_cast<QVariantMap *>(mem);
1120 if (m && map->isSharedWith(*m))
1121 return roleIndex;
1122 map->~QMap();
1123 } else if (!m) {
1124 return roleIndex;
1125 }
1126 if (m)
1127 new (mem) QVariantMap(*m);
1128 else
1129 new (mem) QVariantMap;
1130 roleIndex = role.index;
1131 }
1132
1133 return roleIndex;
1134}
1135
1136int ListElement::setDateTimeProperty(const ListLayout::Role &role, const QDateTime &dt)
1137{
1138 int roleIndex = -1;
1139
1140 if (role.type == ListLayout::Role::DateTime) {
1141 char *mem = getPropertyMemory(role);
1142 if (isMemoryUsed<QDateTime>(mem)) {
1143 QDateTime *dt = reinterpret_cast<QDateTime *>(mem);
1144 dt->~QDateTime();
1145 }
1146 new (mem) QDateTime(dt);
1147 roleIndex = role.index;
1148 }
1149
1150 return roleIndex;
1151}
1152
1153int ListElement::setUrlProperty(const ListLayout::Role &role, const QUrl &url)
1154{
1155 int roleIndex = -1;
1156
1157 if (role.type == ListLayout::Role::Url) {
1158 char *mem = getPropertyMemory(role);
1159 if (isMemoryUsed<QUrl>(mem)) {
1160 QUrl *qurl = reinterpret_cast<QUrl *>(mem);
1161 qurl->~QUrl();
1162 }
1163 new (mem) QUrl(url);
1164 roleIndex = role.index;
1165 }
1166
1167 return roleIndex;
1168}
1169
1170int ListElement::setFunctionProperty(const ListLayout::Role &role, const QJSValue &f)
1171{
1172 int roleIndex = -1;
1173
1174 if (role.type == ListLayout::Role::Function) {
1175 char *mem = getPropertyMemory(role);
1176 if (isMemoryUsed<QJSValue>(mem)) {
1177 QJSValue *f = reinterpret_cast<QJSValue *>(mem);
1178 f->~QJSValue();
1179 }
1180 new (mem) QJSValue(f);
1181 roleIndex = role.index;
1182 }
1183
1184 return roleIndex;
1185}
1186
1187int ListElement::setTranslationProperty(const ListLayout::Role &role, const QV4::CompiledData::Binding *b)
1188{
1189 int roleIndex = -1;
1190
1191 if (role.type == ListLayout::Role::String) {
1192 char *mem = getPropertyMemory(role);
1193 StringOrTranslation *s = reinterpret_cast<StringOrTranslation *>(mem);
1194 s->setTranslation(b);
1195 roleIndex = role.index;
1196 }
1197
1198 return roleIndex;
1199}
1200
1201
1202void ListElement::setStringPropertyFast(const ListLayout::Role &role, const QString &s)
1203{
1204 char *mem = getPropertyMemory(role);
1205 reinterpret_cast<StringOrTranslation *>(mem)->setString(s);
1206}
1207
1208void ListElement::setDoublePropertyFast(const ListLayout::Role &role, double d)
1209{
1210 char *mem = getPropertyMemory(role);
1211 double *value = new (mem) double;
1212 *value = d;
1213}
1214
1215void ListElement::setBoolPropertyFast(const ListLayout::Role &role, bool b)
1216{
1217 char *mem = getPropertyMemory(role);
1218 bool *value = new (mem) bool;
1219 *value = b;
1220}
1221
1222void ListElement::setQObjectPropertyFast(const ListLayout::Role &role, QV4::QObjectWrapper *o)
1223{
1224 char *mem = getPropertyMemory(role);
1225 new (mem) QV4::PersistentValue(o->engine(), o);
1226}
1227
1228void ListElement::setListPropertyFast(const ListLayout::Role &role, ListModel *m)
1229{
1230 char *mem = getPropertyMemory(role);
1231 ListModel **value = new (mem) ListModel *;
1232 *value = m;
1233}
1234
1235void ListElement::setVariantMapFast(const ListLayout::Role &role, QV4::Object *o)
1236{
1237 char *mem = getPropertyMemory(role);
1238 QVariantMap *map = new (mem) QVariantMap;
1239 *map = o->engine()->variantMapFromJS(o);
1240}
1241
1242void ListElement::setDateTimePropertyFast(const ListLayout::Role &role, const QDateTime &dt)
1243{
1244 char *mem = getPropertyMemory(role);
1245 new (mem) QDateTime(dt);
1246}
1247
1248void ListElement::setUrlPropertyFast(const ListLayout::Role &role, const QUrl &url)
1249{
1250 char *mem = getPropertyMemory(role);
1251 new (mem) QUrl(url);
1252}
1253
1254void ListElement::setFunctionPropertyFast(const ListLayout::Role &role, const QJSValue &f)
1255{
1256 char *mem = getPropertyMemory(role);
1257 new (mem) QJSValue(f);
1258}
1259
1260void ListElement::clearProperty(const ListLayout::Role &role)
1261{
1262 switch (role.type) {
1263 case ListLayout::Role::String:
1264 setStringProperty(role, QString());
1265 break;
1267 setDoubleProperty(role, 0.0);
1268 break;
1270 setBoolProperty(role, false);
1271 break;
1273 setListProperty(role, nullptr);
1274 break;
1275 case ListLayout::Role::QObject:
1276 setQObjectProperty(role, nullptr);
1277 break;
1278 case ListLayout::Role::DateTime:
1279 setDateTimeProperty(role, QDateTime());
1280 break;
1281 case ListLayout::Role::Url:
1282 setUrlProperty(role, QUrl());
1283 break;
1284 case ListLayout::Role::VariantMap:
1285 setVariantMapProperty(role, (QVariantMap *)nullptr);
1286 break;
1288 setFunctionProperty(role, QJSValue());
1289 break;
1290 default:
1291 break;
1292 }
1293}
1294
1296{
1297 m_objectCache = nullptr;
1298 uid = uidCounter.fetchAndAddOrdered(1);
1299 next = nullptr;
1300 memset(data, 0, sizeof(data));
1301}
1302
1303ListElement::ListElement(int existingUid)
1304{
1305 m_objectCache = nullptr;
1306 uid = existingUid;
1307 next = nullptr;
1308 memset(data, 0, sizeof(data));
1309}
1310
1312{
1313 delete next;
1314}
1315
1316QList<int> ListElement::sync(ListElement *src, ListLayout *srcLayout, ListElement *target, ListLayout *targetLayout)
1317{
1318 QList<int> changedRoles;
1319 for (int i=0 ; i < srcLayout->roleCount() ; ++i) {
1320 const ListLayout::Role &srcRole = srcLayout->getExistingRole(i);
1321 const ListLayout::Role &targetRole = targetLayout->getExistingRole(i);
1322
1323 int roleIndex = -1;
1324 switch (srcRole.type) {
1326 {
1327 ListModel *srcSubModel = src->getListProperty(srcRole);
1328 ListModel *targetSubModel = target->getListProperty(targetRole);
1329
1330 if (srcSubModel) {
1331 if (targetSubModel == nullptr) {
1332 targetSubModel = new ListModel(targetRole.subLayout, nullptr);
1333 target->setListPropertyFast(targetRole, targetSubModel);
1334 }
1335 if (ListModel::sync(srcSubModel, targetSubModel))
1336 roleIndex = targetRole.index;
1337 }
1338 }
1339 break;
1341 {
1342 QV4::QObjectWrapper *object = src->getQObjectProperty(srcRole);
1343 roleIndex = target->setQObjectProperty(targetRole, object);
1344 }
1345 break;
1351 {
1352 QVariant v = src->getProperty(srcRole, nullptr, nullptr);
1353 roleIndex = target->setVariantProperty(targetRole, v);
1354 }
1355 break;
1357 {
1358 QVariantMap *map = src->getVariantMapProperty(srcRole);
1359 roleIndex = target->setVariantMapProperty(targetRole, map);
1360 }
1361 break;
1362 default:
1363 break;
1364 }
1365 if (roleIndex >= 0)
1366 changedRoles << roleIndex;
1367 }
1368
1369 return changedRoles;
1370}
1371
1372void ListElement::destroy(ListLayout *layout)
1373{
1374 if (layout) {
1375 for (int i=0 ; i < layout->roleCount() ; ++i) {
1376 const ListLayout::Role &r = layout->getExistingRole(i);
1377
1378 switch (r.type) {
1380 {
1381 StringOrTranslation *string = getStringProperty(r);
1382 if (string)
1384 }
1385 break;
1387 {
1388 ListModel *model = getListProperty(r);
1389 if (model) {
1390 model->destroy();
1391 delete model;
1392 }
1393 }
1394 break;
1396 {
1397 if (QV4::PersistentValue *guard = getGuardProperty(r))
1398 guard->~PersistentValue();
1399 }
1400 break;
1402 {
1403 QVariantMap *map = getVariantMapProperty(r);
1404 if (map)
1405 map->~QMap();
1406 }
1407 break;
1409 {
1410 QDateTime *dt = getDateTimeProperty(r);
1411 if (dt)
1412 dt->~QDateTime();
1413 }
1414 break;
1416 {
1417 QUrl *url = getUrlProperty(r);
1418 if (url)
1419 url->~QUrl();
1420 break;
1421 }
1423 {
1424 QJSValue *f = getFunctionProperty(r);
1425 if (f)
1426 f->~QJSValue();
1427 }
1428 break;
1429 default:
1430 // other types don't need explicit cleanup.
1431 break;
1432 }
1433 }
1434
1435 if (m_objectCache) {
1436 m_objectCache->~QObject();
1437 operator delete(m_objectCache);
1438 }
1439 }
1440
1441 if (next)
1442 next->destroy(nullptr);
1443 uid = -1;
1444}
1445
1446int ListElement::setVariantProperty(const ListLayout::Role &role, const QVariant &d)
1447{
1448 int roleIndex = -1;
1449
1450 switch (role.type) {
1452 roleIndex = setDoubleProperty(role, d.toDouble());
1453 break;
1455 if (d.userType() == qMetaTypeId<const QV4::CompiledData::Binding *>())
1456 roleIndex = setTranslationProperty(role, d.value<const QV4::CompiledData::Binding*>());
1457 else
1458 roleIndex = setStringProperty(role, d.toString());
1459 break;
1461 roleIndex = setBoolProperty(role, d.toBool());
1462 break;
1464 roleIndex = setListProperty(role, d.value<ListModel *>());
1465 break;
1467 QVariantMap map = d.toMap();
1468 roleIndex = setVariantMapProperty(role, &map);
1469 }
1470 break;
1472 roleIndex = setDateTimeProperty(role, d.toDateTime());
1473 break;
1475 roleIndex = setUrlProperty(role, d.toUrl());
1476 break;
1478 roleIndex = setFunctionProperty(role, d.value<QJSValue>());
1479 break;
1480 default:
1481 break;
1482 }
1483
1484 return roleIndex;
1485}
1486
1487int ListElement::setJsProperty(const ListLayout::Role &role, const QV4::Value &d, QV4::ExecutionEngine *eng)
1488{
1489 // Check if this key exists yet
1490 int roleIndex = -1;
1491
1492 QV4::Scope scope(eng);
1493
1494 // Add the value now
1495 if (d.isString()) {
1496 QString qstr = d.toQString();
1497 roleIndex = setStringProperty(role, qstr);
1498 } else if (d.isNumber()) {
1499 roleIndex = setDoubleProperty(role, d.asDouble());
1500 } else if (d.as<QV4::ArrayObject>()) {
1501 QV4::ScopedArrayObject a(scope, d);
1502 if (role.type == ListLayout::Role::List) {
1503 QV4::Scope scope(a->engine());
1504 QV4::ScopedObject o(scope);
1505
1506 ListModel *subModel = new ListModel(role.subLayout, nullptr);
1507 int arrayLength = a->getLength();
1508 for (int j=0 ; j < arrayLength ; ++j) {
1509 o = a->get(j);
1510 subModel->append(o);
1511 }
1512 roleIndex = setListProperty(role, subModel);
1513 } else {
1514 qmlWarning(nullptr) << QStringLiteral("Can't assign to existing role '%1' of different type [%2 -> %3]").arg(role.name).arg(roleTypeName(role.type)).arg(roleTypeName(ListLayout::Role::List));
1515 }
1516 } else if (d.isBoolean()) {
1517 roleIndex = setBoolProperty(role, d.booleanValue());
1518 } else if (d.as<QV4::DateObject>()) {
1519 QV4::Scoped<QV4::DateObject> dd(scope, d);
1520 QDateTime dt = dd->toQDateTime();
1521 roleIndex = setDateTimeProperty(role, dt);
1522 } else if (d.as<QV4::UrlObject>()) {
1523 QV4::Scoped<QV4::UrlObject> url(scope, d);
1524 QUrl qurl = QUrl(url->href());
1525 roleIndex = setUrlProperty(role, qurl);
1526 } else if (d.as<QV4::FunctionObject>()) {
1527 QV4::ScopedFunctionObject f(scope, d);
1528 QJSValue jsv;
1529 QJSValuePrivate::setValue(&jsv, f);
1530 roleIndex = setFunctionProperty(role, jsv);
1531 } else if (d.isObject()) {
1532 QV4::ScopedObject o(scope, d);
1533 QV4::QObjectWrapper *wrapper = o->as<QV4::QObjectWrapper>();
1534 if (role.type == ListLayout::Role::QObject && wrapper) {
1535 roleIndex = setQObjectProperty(role, wrapper);
1536 } else if (role.type == ListLayout::Role::VariantMap) {
1537 roleIndex = setVariantMapProperty(role, o);
1538 } else if (role.type == ListLayout::Role::Url) {
1539 QVariant maybeUrl = QV4::ExecutionEngine::toVariant(
1540 // gc will hold on to o via the scoped propertyValue; fromReturnedValue is safe
1541 QV4::Value::fromReturnedValue(o.asReturnedValue()),
1542 QMetaType::fromType<QUrl>(), true);
1543 if (maybeUrl.metaType() == QMetaType::fromType<QUrl>()) {
1544 roleIndex = setUrlProperty(role, maybeUrl.toUrl());
1545 }
1546 }
1547 } else if (d.isNullOrUndefined()) {
1548 clearProperty(role);
1549 }
1550
1551 return roleIndex;
1552}
1553
1554ModelNodeMetaObject::ModelNodeMetaObject(QObject *object, QQmlListModel *model, int elementIndex)
1555: QQmlOpenMetaObject(object), m_enabled(false), m_model(model), m_elementIndex(elementIndex), m_initialized(false)
1556{}
1557
1558void ModelNodeMetaObject::initialize()
1559{
1560 const int roleCount = m_model->m_listModel->roleCount();
1561 QList<QByteArray> properties;
1562 properties.reserve(roleCount);
1563 for (int i = 0 ; i < roleCount ; ++i) {
1564 const ListLayout::Role &role = m_model->m_listModel->getExistingRole(i);
1565 QByteArray name = role.name.toUtf8();
1566 properties << name;
1567 }
1568 type()->createProperties(properties);
1570 m_enabled = true;
1571}
1572
1576
1577#if QT_VERSION >= QT_VERSION_CHECK(7, 0, 0)
1578const QMetaObject *ModelNodeMetaObject::toDynamicMetaObject(QObject *object) const
1579#else
1580QMetaObject *ModelNodeMetaObject::toDynamicMetaObject(QObject *object)
1581#endif
1582{
1583 if (!m_initialized) {
1584 m_initialized = true;
1585 const_cast<ModelNodeMetaObject *>(this)->initialize();
1586 }
1587 return QQmlOpenMetaObject::toDynamicMetaObject(object);
1588}
1589
1591{
1592 QObjectPrivate *op = QObjectPrivate::get(obj);
1593 return static_cast<ModelNodeMetaObject*>(op->metaObject);
1594}
1595
1597{
1598 Q_ALLOCA_INIT();
1599 const int roleCount = m_model->m_listModel->roleCount();
1600 if (!m_initialized) {
1601 if (roleCount) {
1602 Q_ALLOCA_VAR(int, changedRoles, roleCount * sizeof(int));
1603 for (int i = 0; i < roleCount; ++i)
1604 changedRoles[i] = i;
1605 emitDirectNotifies(changedRoles, roleCount);
1606 }
1607 return;
1608 }
1609 for (int i=0 ; i < roleCount ; ++i) {
1610 const ListLayout::Role &role = m_model->m_listModel->getExistingRole(i);
1611 QByteArray name = role.name.toUtf8();
1612 const QVariant &data = m_model->data(m_elementIndex, i);
1613 setValue(name, data, role.type == ListLayout::Role::List);
1614 }
1615}
1616
1617void ModelNodeMetaObject::updateValues(const QList<int> &roles)
1618{
1619 if (!m_initialized) {
1620 emitDirectNotifies(roles.constData(), roles.size());
1621 return;
1622 }
1623 int roleCount = roles.size();
1624 for (int i=0 ; i < roleCount ; ++i) {
1625 int roleIndex = roles.at(i);
1626 const ListLayout::Role &role = m_model->m_listModel->getExistingRole(roleIndex);
1627 QByteArray name = role.name.toUtf8();
1628 const QVariant &data = m_model->data(m_elementIndex, roleIndex);
1629 setValue(name, data, role.type == ListLayout::Role::List);
1630 }
1631}
1632
1634{
1635 if (!m_enabled)
1636 return;
1637
1638 QString propName = QString::fromUtf8(name(index));
1639 const QVariant value = this->value(index);
1640
1641 QV4::Scope scope(m_model->engine());
1642 QV4::ScopedValue v(scope, scope.engine->fromVariant(value));
1643
1644 int roleIndex = m_model->m_listModel->setExistingProperty(m_elementIndex, propName, v, scope.engine);
1645 if (roleIndex != -1)
1646 m_model->emitItemsChanged(m_elementIndex, 1, QList<int>(1, roleIndex));
1647}
1648
1649// Does the emission of the notifiers when we haven't created the meta-object yet
1650void ModelNodeMetaObject::emitDirectNotifies(const int *changedRoles, int roleCount)
1651{
1652 Q_ASSERT(!m_initialized);
1653 QQmlData *ddata = QQmlData::get(object(), /*create*/false);
1654 if (!ddata)
1655 return;
1656 // There's nothing to emit if we're a list model in a worker thread.
1657 if (!qmlEngine(m_model))
1658 return;
1659 for (int i = 0; i < roleCount; ++i) {
1660 const int changedRole = changedRoles[i];
1661 QQmlNotifier::notify(ddata, changedRole);
1662 }
1663}
1664
1665namespace QV4 {
1666
1667bool ModelObject::virtualPut(Managed *m, PropertyKey id, const Value &value, Value *receiver)
1668{
1669 if (!id.isString())
1670 return Object::virtualPut(m, id, value, receiver);
1671 QString propName = id.toQString();
1672
1673 ModelObject *that = static_cast<ModelObject*>(m);
1674 if (!that->object())
1675 return false;
1676
1677 ExecutionEngine *eng = that->engine();
1678 const int elementIndex = that->d()->elementIndex();
1679 if (QQmlListModel *model = that->d()->m_model) {
1680 const int roleIndex
1681 = model->listModel()->setExistingProperty(elementIndex, propName, value, eng);
1682 if (roleIndex != -1)
1683 model->emitItemsChanged(elementIndex, 1, QList<int>(1, roleIndex));
1684 }
1685
1686 ModelNodeMetaObject *mo = ModelNodeMetaObject::get(that->object());
1687 if (mo->initialized())
1688 mo->emitPropertyNotification(propName.toUtf8());
1689 return true;
1690}
1691
1692ReturnedValue ModelObject::virtualGet(const Managed *m, PropertyKey id, const Value *receiver, bool *hasProperty)
1693{
1694 if (!id.isString())
1695 return QObjectWrapper::virtualGet(m, id, receiver, hasProperty);
1696
1697 const ModelObject *that = static_cast<const ModelObject*>(m);
1698 Scope scope(that);
1699 ScopedString name(scope, id.asStringOrSymbol());
1700 QQmlListModel *model = that->d()->m_model;
1701 if (!model || !that->object())
1702 return QObjectWrapper::virtualGet(m, id, receiver, hasProperty);
1703
1704 const ListLayout::Role *role = model->listModel()->getExistingRole(name);
1705 if (!role)
1706 return QObjectWrapper::virtualGet(m, id, receiver, hasProperty);
1707 if (hasProperty)
1708 *hasProperty = true;
1709
1710 if (QQmlEngine *qmlEngine = that->engine()->qmlEngine()) {
1711 QQmlEnginePrivate *ep = QQmlEnginePrivate::get(qmlEngine);
1712 if (ep && ep->propertyCapture)
1713 ep->propertyCapture->captureProperty(that->object(), -1, role->index, /*doNotify=*/ false);
1714 }
1715
1716 const int elementIndex = that->d()->elementIndex();
1717 QVariant value = model->data(elementIndex, role->index);
1718 return that->engine()->fromVariant(value);
1719}
1720
1721ReturnedValue ModelObject::virtualResolveLookupGetter(const Object *object, ExecutionEngine *engine, Lookup *lookup)
1722{
1723 lookup->call = Lookup::Call::GetterQObjectPropertyFallback;
1724 return lookup->getter(engine, *object);
1725}
1726
1728{
1731 PropertyKey next(const Object *o, Property *pd = nullptr, PropertyAttributes *attrs = nullptr) override;
1732
1733};
1734
1735PropertyKey ModelObjectOwnPropertyKeyIterator::next(const Object *o, Property *pd, PropertyAttributes *attrs)
1736{
1737 const ModelObject *that = static_cast<const ModelObject *>(o);
1738
1739 ExecutionEngine *v4 = that->engine();
1740
1741 QQmlListModel *model = that->d()->m_model;
1742 ListModel *listModel = model ? model->listModel() : nullptr;
1743 if (listModel && roleNameIndex < listModel->roleCount()) {
1744 Scope scope(that->engine());
1745 const ListLayout::Role &role = listModel->getExistingRole(roleNameIndex);
1746 ++roleNameIndex;
1747 ScopedString roleName(scope, v4->newString(role.name));
1748 if (attrs)
1749 *attrs = QV4::Attr_Data;
1750 if (pd) {
1751
1752 QVariant value = model->data(that->d()->elementIndex(), role.index);
1753 if (auto recursiveListModel = qvariant_cast<QQmlListModel*>(value)) {
1754 auto size = recursiveListModel->count();
1755 auto array = ScopedArrayObject{scope, v4->newArrayObject(size)};
1756 QV4::ScopedValue val(scope);
1757 for (auto i = 0; i < size; i++) {
1758 val = QJSValuePrivate::convertToReturnedValue(
1759 v4, recursiveListModel->get(i));
1760 array->arrayPut(i, val);
1761 }
1762 pd->value = array;
1763 } else {
1764 pd->value = v4->fromVariant(value);
1765 }
1766 }
1767 return roleName->toPropertyKey();
1768 }
1769
1770 // Fall back to QV4::Object as opposed to QV4::QObjectWrapper otherwise it will add
1771 // unnecessary entries that relate to the roles used. These just create extra work
1772 // later on as they will just be ignored.
1773 return ObjectOwnPropertyKeyIterator::next(o, pd, attrs);
1774}
1775
1776OwnPropertyKeyIterator *ModelObject::virtualOwnPropertyKeys(const Object *m, Value *target)
1777{
1778 *target = *m;
1780}
1781
1783
1784} // namespace QV4
1785
1786DynamicRoleModelNode::DynamicRoleModelNode(QQmlListModel *owner, int uid) : m_owner(owner), m_uid(uid), m_meta(new DynamicRoleModelNodeMetaObject(this))
1787{
1789}
1790
1791DynamicRoleModelNode *DynamicRoleModelNode::create(const QVariantMap &obj, QQmlListModel *owner)
1792{
1793 DynamicRoleModelNode *object = new DynamicRoleModelNode(owner, uidCounter.fetchAndAddOrdered(1));
1794 QList<int> roles;
1795 object->updateValues(obj, roles);
1796 return object;
1797}
1798
1800{
1801 QList<int> changedRoles;
1802 for (int i = 0; i < src->m_meta->count(); ++i) {
1803 const QByteArray &name = src->m_meta->name(i);
1804 QVariant value = src->m_meta->value(i);
1805
1806 QQmlListModel *srcModel = qobject_cast<QQmlListModel *>(value.value<QObject *>());
1807 QQmlListModel *targetModel = qobject_cast<QQmlListModel *>(target->m_meta->value(i).value<QObject *>());
1808
1809 bool modelHasChanges = false;
1810 if (srcModel) {
1811 if (targetModel == nullptr)
1812 targetModel = QQmlListModel::createWithOwner(target->m_owner);
1813
1814 modelHasChanges = QQmlListModel::sync(srcModel, targetModel);
1815
1816 QObject *targetModelObject = targetModel;
1817 value = QVariant::fromValue(targetModelObject);
1818 } else if (targetModel) {
1819 delete targetModel;
1820 }
1821
1822 if (target->setValue(name, value) || modelHasChanges)
1823 changedRoles << target->m_owner->m_roles.indexOf(QString::fromUtf8(name));
1824 }
1825 return changedRoles;
1826}
1827
1828void DynamicRoleModelNode::updateValues(const QVariantMap &object, QList<int> &roles)
1829{
1830 for (auto it = object.cbegin(), end = object.cend(); it != end; ++it) {
1831 const QString &key = it.key();
1832
1833 int roleIndex = m_owner->m_roles.indexOf(key);
1834 if (roleIndex == -1) {
1835 roleIndex = m_owner->m_roles.size();
1836 m_owner->m_roles.append(key);
1837 }
1838
1839 QVariant value = it.value();
1840
1841 // A JS array/object is translated into a (hierarchical) QQmlListModel,
1842 // so translate to a variant map/list first with toVariant().
1843 if (value.userType() == qMetaTypeId<QJSValue>())
1844 value = value.value<QJSValue>().toVariant();
1845
1846 if (value.userType() == QMetaType::QVariantList) {
1847 QQmlListModel *subModel = QQmlListModel::createWithOwner(m_owner);
1848
1849 QVariantList subArray = value.toList();
1850 QVariantList::const_iterator subIt = subArray.cbegin();
1851 QVariantList::const_iterator subEnd = subArray.cend();
1852 while (subIt != subEnd) {
1853 const QVariantMap &subObject = subIt->toMap();
1854 subModel->m_modelObjects.append(DynamicRoleModelNode::create(subObject, subModel));
1855 ++subIt;
1856 }
1857
1858 QObject *subModelObject = subModel;
1859 value = QVariant::fromValue(subModelObject);
1860 }
1861
1862 const QByteArray &keyUtf8 = key.toUtf8();
1863
1864 QQmlListModel *existingModel = qobject_cast<QQmlListModel *>(m_meta->value(keyUtf8).value<QObject *>());
1865 delete existingModel;
1866
1867 if (m_meta->setValue(keyUtf8, value))
1868 roles << roleIndex;
1869 }
1870}
1871
1876
1878{
1879 for (int i=0 ; i < count() ; ++i) {
1880 QQmlListModel *subModel = qobject_cast<QQmlListModel *>(value(i).value<QObject *>());
1881 delete subModel;
1882 }
1883}
1884
1886{
1887 if (!m_enabled)
1888 return;
1889
1890 QVariant v = value(index);
1891 QQmlListModel *model = qobject_cast<QQmlListModel *>(v.value<QObject *>());
1892 delete model;
1893}
1894
1896{
1897 if (!m_enabled)
1898 return;
1899
1900 QQmlListModel *parentModel = m_owner->m_owner;
1901
1902 QVariant v = value(index);
1903
1904 // A JS array/object is translated into a (hierarchical) QQmlListModel,
1905 // so translate to a variant map/list first with toVariant().
1906 if (v.userType() == qMetaTypeId<QJSValue>())
1907 v= v.value<QJSValue>().toVariant();
1908
1909 if (v.userType() == QMetaType::QVariantList) {
1910 QQmlListModel *subModel = QQmlListModel::createWithOwner(parentModel);
1911
1912 QVariantList subArray = v.toList();
1913 QVariantList::const_iterator subIt = subArray.cbegin();
1914 QVariantList::const_iterator subEnd = subArray.cend();
1915 while (subIt != subEnd) {
1916 const QVariantMap &subObject = subIt->toMap();
1917 subModel->m_modelObjects.append(DynamicRoleModelNode::create(subObject, subModel));
1918 ++subIt;
1919 }
1920
1921 QObject *subModelObject = subModel;
1922 v = QVariant::fromValue(subModelObject);
1923
1924 setValue(index, v);
1925 }
1926
1927 int elementIndex = parentModel->m_modelObjects.indexOf(m_owner);
1928 if (elementIndex != -1) {
1929 int roleIndex = parentModel->m_roles.indexOf(QString::fromLatin1(name(index).constData()));
1930 if (roleIndex != -1)
1931 parentModel->emitItemsChanged(elementIndex, 1, QList<int>(1, roleIndex));
1932 }
1933}
1934
1935/*!
1936 \qmltype ListModel
1937 \nativetype QQmlListModel
1938 //! \inherits AbstractListModel
1939 \inqmlmodule QtQml.Models
1940 \ingroup qtquick-models
1941 \brief Defines a free-form list data source.
1942
1943 The ListModel is a simple container of ListElement definitions, each
1944 containing data roles. The contents can be defined dynamically, or
1945 explicitly in QML.
1946
1947 The number of elements in the model can be obtained from its \l count property.
1948 A number of familiar methods are also provided to manipulate the contents of the
1949 model, including append(), insert(), move(), remove() and set(). These methods
1950 accept dictionaries as their arguments; these are translated to ListElement objects
1951 by the model.
1952
1953 Elements can be manipulated via the model using the setProperty() method, which
1954 allows the roles of the specified element to be set and changed.
1955
1956 ListModel inherits from \l{QAbstractListModel} and provides its \l{Q_INVOKABLE}
1957 methods. You can, for example use \l{QAbstractItemModel::index} to retrieve a
1958 \l{QModelIndex} for a row and column.
1959
1960 \section1 Example Usage
1961
1962 The following example shows a ListModel containing three elements, with the roles
1963 "name" and "cost".
1964
1965 \div {class="float-right"}
1966 \inlineimage listmodel.png
1967 {List showing Apple, Orange, and Banana with prices}
1968 \enddiv
1969
1970 \snippet qml/listmodel/listmodel.qml 0
1971
1972 Roles (properties) in each element must begin with a lower-case letter and
1973 should be common to all elements in a model. The ListElement documentation
1974 provides more guidelines for how elements should be defined.
1975
1976 Since the example model contains an \c id property, it can be referenced
1977 by views, such as the ListView in this example:
1978
1979 \snippet qml/listmodel/listmodel-simple.qml 0
1980 \dots 8
1981 \snippet qml/listmodel/listmodel-simple.qml 1
1982
1983 It is possible for roles to contain list data. In the following example we
1984 create a list of fruit attributes:
1985
1986 \snippet qml/listmodel/listmodel-nested.qml model
1987
1988 The delegate displays all the fruit attributes:
1989
1990 \div {class="float-right"}
1991 \inlineimage listmodel-nested.png
1992 {List showing fruits with nested attribute data}
1993 \enddiv
1994
1995 \snippet qml/listmodel/listmodel-nested.qml delegate
1996
1997 \section1 Modifying List Models
1998
1999 The content of a ListModel may be created and modified using the clear(),
2000 append(), set(), insert() and setProperty() methods. For example:
2001
2002 \snippet qml/listmodel/listmodel-modify.qml delegate
2003
2004 Note that when creating content dynamically the set of available properties
2005 cannot be changed once set. Whatever properties are first added to the model
2006 are the only permitted properties in the model.
2007
2008 \section1 Using Threaded List Models with WorkerScript
2009
2010 ListModel can be used together with WorkerScript to access a list model
2011 from multiple threads. This is useful if list modifications are
2012 synchronous and take some time: the list operations can be moved to a
2013 different thread to avoid blocking of the main GUI thread.
2014
2015 Here is an example that uses WorkerScript to periodically append the
2016 current time to a list model:
2017
2018 \snippet qml/listmodel/WorkerScript.qml 0
2019
2020 The included file, \tt dataloader.mjs, looks like this:
2021
2022 \snippet qml/listmodel/dataloader.mjs 0
2023
2024 The timer in the main example sends messages to the worker script by calling
2025 \l WorkerScript::sendMessage(). When this message is received,
2026 \c WorkerScript.onMessage() is invoked in \c dataloader.mjs,
2027 which appends the current time to the list model.
2028
2029 Note the call to sync() from the external thread.
2030 You must call sync() or else the changes made to the list from that
2031 thread will not be reflected in the list model in the main thread.
2032
2033 \sa {qml-data-models}{Data Models}, {Qt Qml}
2034*/
2035
2036QQmlListModel::QQmlListModel(QObject *parent)
2037: QAbstractListModel(parent)
2038{
2039 m_mainThread = true;
2040 m_primary = true;
2041 m_agent = nullptr;
2042 m_dynamicRoles = false;
2043
2044 m_layout = new ListLayout;
2045 m_listModel = new ListModel(m_layout, this);
2046
2047 m_engine = nullptr;
2048}
2049
2050QQmlListModel::QQmlListModel(const QQmlListModel *owner, ListModel *data, QV4::ExecutionEngine *engine, QObject *parent)
2051: QAbstractListModel(parent)
2052{
2053 m_mainThread = owner->m_mainThread;
2054 m_primary = false;
2055 m_agent = owner->m_agent;
2056
2057 Q_ASSERT(owner->m_dynamicRoles == false);
2058 m_dynamicRoles = false;
2059 m_layout = nullptr;
2060 m_listModel = data;
2061
2062 m_engine = engine;
2063 m_compilationUnit = owner->m_compilationUnit;
2064}
2065
2066QQmlListModel::QQmlListModel(QQmlListModel *orig, QQmlListModelWorkerAgent *agent)
2067: QAbstractListModel(agent)
2068{
2069 m_mainThread = false;
2070 m_primary = true;
2071 m_agent = agent;
2072 m_dynamicRoles = orig->m_dynamicRoles;
2073
2074 if (ListLayout *layout = orig->m_layout)
2075 m_layout = new ListLayout(layout);
2076 else
2077 m_layout = new ListLayout;
2078
2079 m_listModel = new ListModel(m_layout, this);
2080
2081 if (m_dynamicRoles)
2082 sync(orig, this);
2083 else
2084 ListModel::sync(orig->m_listModel, m_listModel);
2085
2086 m_engine = nullptr;
2087 m_compilationUnit = orig->m_compilationUnit;
2088}
2089
2090QQmlListModel::~QQmlListModel()
2091{
2092 qDeleteAll(m_modelObjects);
2093
2094 if (m_primary) {
2095 m_listModel->destroy();
2096 delete m_listModel;
2097
2098 if (m_mainThread && m_agent)
2099 m_agent->modelDestroyed();
2100 }
2101
2102 if (m_agent && m_ownAgent)
2103 m_agent->release();
2104
2105 m_listModel = nullptr;
2106
2107 delete m_layout;
2108 m_layout = nullptr;
2109}
2110
2111QQmlListModel *QQmlListModel::createWithOwner(QQmlListModel *newOwner)
2112{
2113 QQmlListModel *model = new QQmlListModel;
2114
2115 model->m_mainThread = newOwner->m_mainThread;
2116 model->m_engine = newOwner->m_engine;
2117 model->m_agent = newOwner->m_agent;
2118 model->m_dynamicRoles = newOwner->m_dynamicRoles;
2119
2120 QQmlEngine::setContextForObject(model, QQmlEngine::contextForObject(newOwner));
2121
2122 return model;
2123}
2124
2125QV4::ExecutionEngine *QQmlListModel::engine() const
2126{
2127 if (m_engine == nullptr) {
2128 m_engine = qmlEngine(this)->handle();
2129 }
2130
2131 return m_engine;
2132}
2133
2134bool QQmlListModel::sync(QQmlListModel *src, QQmlListModel *target)
2135{
2136 Q_ASSERT(src->m_dynamicRoles && target->m_dynamicRoles);
2137
2138 bool hasChanges = false;
2139
2140 target->m_roles = src->m_roles;
2141
2142 // Build hash of elements <-> uid for each of the lists
2143 QHash<int, ElementSync> elementHash;
2144 for (int i = 0 ; i < target->m_modelObjects.size(); ++i) {
2145 DynamicRoleModelNode *e = target->m_modelObjects.at(i);
2146 int uid = e->getUid();
2147 ElementSync sync;
2148 sync.target = e;
2149 sync.targetIndex = i;
2150 elementHash.insert(uid, sync);
2151 }
2152 for (int i = 0 ; i < src->m_modelObjects.size(); ++i) {
2153 DynamicRoleModelNode *e = src->m_modelObjects.at(i);
2154 int uid = e->getUid();
2155
2156 QHash<int, ElementSync>::iterator it = elementHash.find(uid);
2157 if (it == elementHash.end()) {
2158 ElementSync sync;
2159 sync.src = e;
2160 sync.srcIndex = i;
2161 elementHash.insert(uid, sync);
2162 } else {
2163 ElementSync &sync = it.value();
2164 sync.src = e;
2165 sync.srcIndex = i;
2166 }
2167 }
2168
2169 // Get list of elements that are in the target but no longer in the source. These get deleted first.
2170 int rowsRemoved = 0;
2171 for (int i = 0 ; i < target->m_modelObjects.size() ; ++i) {
2172 DynamicRoleModelNode *element = target->m_modelObjects.at(i);
2173 ElementSync &s = elementHash.find(element->getUid()).value();
2174 Q_ASSERT(s.targetIndex >= 0);
2175 // need to update the targetIndex, to keep it correct after removals
2176 s.targetIndex -= rowsRemoved;
2177 if (s.src == nullptr) {
2178 Q_ASSERT(s.targetIndex == i);
2179 hasChanges = true;
2180 target->beginRemoveRows(QModelIndex(), i, i);
2181 target->m_modelObjects.remove(i, 1);
2182 target->endRemoveRows();
2183 delete s.target;
2184 ++rowsRemoved;
2185 --i;
2186 continue;
2187 }
2188 }
2189
2190 // Clear the target list, and append in correct order from the source
2191 target->m_modelObjects.clear();
2192 for (int i = 0 ; i < src->m_modelObjects.size() ; ++i) {
2193 DynamicRoleModelNode *element = src->m_modelObjects.at(i);
2194 ElementSync &s = elementHash.find(element->getUid()).value();
2195 Q_ASSERT(s.srcIndex >= 0);
2196 DynamicRoleModelNode *targetElement = s.target;
2197 if (targetElement == nullptr) {
2198 targetElement = new DynamicRoleModelNode(target, element->getUid());
2199 }
2200 s.changedRoles = DynamicRoleModelNode::sync(element, targetElement);
2201 target->m_modelObjects.append(targetElement);
2202 }
2203
2204 // now emit the change notifications required. This can be safely done, as we're only emitting changes, moves and inserts,
2205 // so the model indices can't be out of bounds
2206 //
2207 // to ensure things are kept in the correct order, emit inserts and moves first. This shouls ensure all persistent
2208 // model indices are updated correctly
2209 //
2210 // All rows before i are in their final place, so s.targetIndex always tracks the current
2211 // position of a row that still has to be placed, and that position is never before i.
2212 const int targetElementCount = target->m_modelObjects.size();
2213 for (int i = 0 ; i < targetElementCount ; ++i) {
2214 DynamicRoleModelNode *element = target->m_modelObjects.at(i);
2215 ElementSync &s = elementHash.find(element->getUid()).value();
2216 Q_ASSERT(s.srcIndex >= 0);
2217 const bool inserted = s.targetIndex == -1;
2218 if (s.targetIndex != i) {
2219 // rows between i and the old position (all rows, for an insertion) move down by one
2220 const int oldIndex = s.targetIndex;
2221 if (inserted) {
2222 target->beginInsertRows(QModelIndex(), i, i);
2223 target->endInsertRows();
2224 } else {
2225 Q_ASSERT(oldIndex > i);
2226 target->beginMoveRows(QModelIndex(), oldIndex, oldIndex, QModelIndex(), i);
2227 target->endMoveRows();
2228 }
2229 for (int j = i + 1; j < targetElementCount; ++j) {
2230 ElementSync &sToFix
2231 = elementHash.find(target->m_modelObjects.at(j)->getUid()).value();
2232 if (sToFix.targetIndex != -1 && (inserted || sToFix.targetIndex < oldIndex))
2233 sToFix.targetIndex += 1;
2234 }
2235 hasChanges = true;
2236 s.targetIndex = i;
2237 }
2238 if (!inserted && !s.changedRoles.isEmpty()) {
2239 QModelIndex idx = target->createIndex(i, 0);
2240 emit target->dataChanged(idx, idx, s.changedRoles);
2241 hasChanges = true;
2242 }
2243 }
2244 return hasChanges;
2245}
2246
2247void QQmlListModel::emitItemsChanged(int index, int count, const QList<int> &roles)
2248{
2249 if (count <= 0)
2250 return;
2251
2252 if (m_mainThread)
2253 emit dataChanged(createIndex(index, 0), createIndex(index + count - 1, 0), roles);;
2254}
2255
2256void QQmlListModel::emitItemsAboutToBeInserted(int index, int count)
2257{
2258 Q_ASSERT(index >= 0 && count >= 0);
2259 if (m_mainThread)
2260 beginInsertRows(QModelIndex(), index, index + count - 1);
2261}
2262
2263void QQmlListModel::emitItemsInserted()
2264{
2265 if (m_mainThread) {
2266 endInsertRows();
2267 emit countChanged();
2268 }
2269}
2270
2271QQmlListModelWorkerAgent *QQmlListModel::agent()
2272{
2273 if (m_agent)
2274 return m_agent;
2275
2276 m_agent = new QQmlListModelWorkerAgent(this);
2277 m_ownAgent = true;
2278 return m_agent;
2279}
2280
2281QModelIndex QQmlListModel::index(int row, int column, const QModelIndex &parent) const
2282{
2283 return row >= 0 && row < count() && column == 0 && !parent.isValid()
2284 ? createIndex(row, column)
2285 : QModelIndex();
2286}
2287
2288int QQmlListModel::rowCount(const QModelIndex &parent) const
2289{
2290 return !parent.isValid() ? count() : 0;
2291}
2292
2293QVariant QQmlListModel::data(const QModelIndex &index, int role) const
2294{
2295 return data(index.row(), role);
2296}
2297
2298bool QQmlListModel::setData(const QModelIndex &index, const QVariant &value, int role)
2299{
2300 const int row = index.row();
2301 if (row >= count() || row < 0)
2302 return false;
2303
2304 if (m_dynamicRoles) {
2305 const QByteArray property = m_roles.at(role).toUtf8();
2306 if (m_modelObjects[row]->setValue(property, value)) {
2307 emitItemsChanged(row, 1, QList<int>(1, role));
2308 return true;
2309 }
2310 } else {
2311 const ListLayout::Role &r = m_listModel->getExistingRole(role);
2312 const int roleIndex = m_listModel->setOrCreateProperty(row, r.name, value);
2313 if (roleIndex != -1) {
2314 emitItemsChanged(row, 1, QList<int>(1, role));
2315 return true;
2316 }
2317 }
2318
2319 return false;
2320}
2321
2322QVariant QQmlListModel::data(int index, int role) const
2323{
2324 QVariant v;
2325
2326 if (index >= count() || index < 0)
2327 return v;
2328
2329 if (m_dynamicRoles)
2330 v = m_modelObjects[index]->getValue(m_roles[role]);
2331 else
2332 v = m_listModel->getProperty(index, role, this, engine());
2333
2334 return v;
2335}
2336
2337QHash<int, QByteArray> QQmlListModel::roleNames() const
2338{
2339 QHash<int, QByteArray> roleNames;
2340
2341 if (m_dynamicRoles) {
2342 const auto size = m_roles.size();
2343 roleNames.reserve(size);
2344 for (int i = 0 ; i < size ; ++i)
2345 roleNames.insert(i, m_roles.at(i).toUtf8());
2346 } else {
2347 const auto size = m_listModel->roleCount();
2348 roleNames.reserve(size);
2349 for (int i = 0 ; i < size; ++i) {
2350 const ListLayout::Role &r = m_listModel->getExistingRole(i);
2351 roleNames.insert(i, r.name.toUtf8());
2352 }
2353 }
2354
2355 return roleNames;
2356}
2357
2358/*!
2359 \qmlproperty bool ListModel::dynamicRoles
2360
2361 By default, the type of a role is fixed the first time
2362 the role is used. For example, if you create a role called
2363 "data" and assign a number to it, you can no longer assign
2364 a string to the "data" role. However, when the dynamicRoles
2365 property is enabled, the type of a given role is not fixed
2366 and can be different between elements.
2367
2368 The dynamicRoles property must be set before any data is
2369 added to the ListModel, and must be set from the main
2370 thread.
2371
2372 A ListModel that has data statically defined (via the
2373 ListElement QML syntax) cannot have the dynamicRoles
2374 property enabled.
2375
2376 There is a significant performance cost to using a
2377 ListModel with dynamic roles enabled. The cost varies
2378 from platform to platform but is typically somewhere
2379 between 4-6x slower than using static role types.
2380
2381 Due to the performance cost of using dynamic roles,
2382 they are disabled by default.
2383*/
2384void QQmlListModel::setDynamicRoles(bool enableDynamicRoles)
2385{
2386 if (m_mainThread && m_agent == nullptr) {
2387 if (enableDynamicRoles) {
2388 if (m_layout && m_layout->roleCount())
2389 qmlWarning(this) << tr("unable to enable dynamic roles as this model is not empty");
2390 else
2391 m_dynamicRoles = true;
2392 } else {
2393 if (m_roles.size()) {
2394 qmlWarning(this) << tr("unable to enable static roles as this model is not empty");
2395 } else {
2396 m_dynamicRoles = false;
2397 }
2398 }
2399 } else {
2400 qmlWarning(this) << tr("dynamic role setting must be made from the main thread, before any worker scripts are created");
2401 }
2402}
2403
2404/*!
2405 \qmlproperty int ListModel::count
2406 The number of data entries in the model.
2407*/
2408int QQmlListModel::count() const
2409{
2410 return m_dynamicRoles ? m_modelObjects.size() : m_listModel->elementCount();
2411}
2412
2413/*!
2414 \qmlmethod void ListModel::clear()
2415
2416 Deletes all content from the model. In particular this invalidates all objects you may have
2417 retrieved using \l get().
2418
2419 \sa append(), remove(), get()
2420*/
2421void QQmlListModel::clear()
2422{
2423 removeElements(0, count());
2424}
2425
2426/*!
2427 \qmlmethod void ListModel::remove(int index, int count = 1)
2428
2429 Deletes \a count number of items at \a index from the model.
2430
2431 \sa clear()
2432*/
2433void QQmlListModel::remove(QQmlV4FunctionPtr args)
2434{
2435 int argLength = args->length();
2436
2437 if (argLength == 1 || argLength == 2) {
2438 QV4::Scope scope(args->v4engine());
2439 int index = QV4::ScopedValue(scope, (*args)[0])->toInt32();
2440 int removeCount = (argLength == 2 ? QV4::ScopedValue(scope, (*args)[1])->toInt32() : 1);
2441
2442 if (index < 0 || index+removeCount > count() || removeCount <= 0) {
2443 qmlWarning(this) << tr("remove: indices [%1 - %2] out of range [0 - %3]").arg(index).arg(index+removeCount).arg(count());
2444 return;
2445 }
2446
2447 removeElements(index, removeCount);
2448 } else {
2449 qmlWarning(this) << tr("remove: incorrect number of arguments");
2450 }
2451}
2452
2453void QQmlListModel::removeElements(int index, int removeCount)
2454{
2455 Q_ASSERT(index >= 0 && removeCount >= 0);
2456
2457 if (!removeCount)
2458 return;
2459
2460 if (m_mainThread)
2461 beginRemoveRows(QModelIndex(), index, index + removeCount - 1);
2462
2463 QList<std::function<void()>> toDestroy;
2464 if (m_dynamicRoles) {
2465 for (int i=0 ; i < removeCount ; ++i) {
2466 auto modelObject = m_modelObjects[index+i];
2467 toDestroy.append([modelObject](){
2468 delete modelObject;
2469 });
2470 }
2471 m_modelObjects.remove(index, removeCount);
2472 } else {
2473 toDestroy = m_listModel->remove(index, removeCount);
2474 }
2475
2476 if (m_mainThread) {
2477 endRemoveRows();
2478 emit countChanged();
2479 }
2480 for (const auto &destroyer : std::as_const(toDestroy))
2481 destroyer();
2482}
2483
2484void QQmlListModel::updateTranslations()
2485{
2486 // assumption: it is impossible to have retranslatable strings in a
2487 // dynamic list model, as they would already have "decayed" to strings
2488 // when they were inserted
2489 if (m_dynamicRoles)
2490 return;
2491 Q_ASSERT(m_listModel);
2492
2493 QList<int> roles;
2494 for (int i = 0, end = m_listModel->roleCount(); i != end; ++i) {
2495 if (m_listModel->getExistingRole(i).type == ListLayout::Role::String)
2496 roles.append(i);
2497 }
2498
2499 if (!roles.isEmpty())
2500 emitItemsChanged(0, rowCount(QModelIndex()), roles);
2501
2502 m_listModel->updateTranslations();
2503}
2504
2505/*!
2506 \qmlmethod void ListModel::insert(int index, jsobject dict)
2507
2508 Adds a new item to the list model at position \a index, with the
2509 values in \a dict.
2510
2511 \code
2512 fruitModel.insert(2, {"cost": 5.95, "name":"Pizza"})
2513 \endcode
2514
2515 The \a index must be to an existing item in the list, or one past
2516 the end of the list (equivalent to append).
2517
2518 \sa set(), append()
2519*/
2520
2521void QQmlListModel::insert(QQmlV4FunctionPtr args)
2522{
2523 if (args->length() == 2) {
2524 QV4::Scope scope(args->v4engine());
2525 QV4::ScopedValue arg0(scope, (*args)[0]);
2526 int index = arg0->toInt32();
2527
2528 if (index < 0 || index > count()) {
2529 qmlWarning(this) << tr("insert: index %1 out of range").arg(index);
2530 return;
2531 }
2532
2533 QV4::ScopedObject argObject(scope, (*args)[1]);
2534 QV4::ScopedArrayObject objectArray(scope, (*args)[1]);
2535 if (objectArray) {
2536 QV4::ScopedObject argObject(scope);
2537
2538 int objectArrayLength = objectArray->getLength();
2539 emitItemsAboutToBeInserted(index, objectArrayLength);
2540 for (int i=0 ; i < objectArrayLength ; ++i) {
2541 argObject = objectArray->get(i);
2542
2543 if (m_dynamicRoles) {
2544 m_modelObjects.insert(index+i, DynamicRoleModelNode::create(scope.engine->variantMapFromJS(argObject), this));
2545 } else {
2546 m_listModel->insert(index+i, argObject);
2547 }
2548 }
2549 emitItemsInserted();
2550 } else if (argObject) {
2551 emitItemsAboutToBeInserted(index, 1);
2552
2553 if (m_dynamicRoles) {
2554 m_modelObjects.insert(index, DynamicRoleModelNode::create(scope.engine->variantMapFromJS(argObject), this));
2555 } else {
2556 m_listModel->insert(index, argObject);
2557 }
2558
2559 emitItemsInserted();
2560 } else {
2561 qmlWarning(this) << tr("insert: value is not an object");
2562 }
2563 } else {
2564 qmlWarning(this) << tr("insert: value is not an object");
2565 }
2566}
2567
2568bool QQmlListModel::canMove(int from, int to, int n) const
2569{
2570 if (from < 0 || to < 0 || n < 0 || n > count())
2571 return false;
2572
2573 const int maxIndex = count() - n;
2574 return from <= maxIndex && to <= maxIndex;
2575}
2576
2577/*!
2578 \qmlmethod void ListModel::move(int from, int to, int n)
2579
2580 Moves \a n items \a from one position \a to another.
2581
2582 The from and to ranges must exist; for example, to move the first 3 items
2583 to the end of the list:
2584
2585 \code
2586 fruitModel.move(0, fruitModel.count - 3, 3)
2587 \endcode
2588
2589 \sa append()
2590*/
2591void QQmlListModel::move(int from, int to, int n)
2592{
2593 if (n == 0 || from == to)
2594 return;
2595 if (!canMove(from, to, n)) {
2596 qmlWarning(this) << tr("move: out of range");
2597 return;
2598 }
2599
2600 if (m_mainThread)
2601 beginMoveRows(QModelIndex(), from, from + n - 1, QModelIndex(), to > from ? to + n : to);
2602
2603 if (m_dynamicRoles) {
2604
2605 int realFrom = from;
2606 int realTo = to;
2607 int realN = n;
2608
2609 if (from > to) {
2610 // Only move forwards - flip if backwards moving
2611 int tfrom = from;
2612 int tto = to;
2613 realFrom = tto;
2614 realTo = tto+n;
2615 realN = tfrom-tto;
2616 }
2617
2618 std::rotate(m_modelObjects.begin() + realFrom,
2619 m_modelObjects.begin() + realFrom + realN,
2620 m_modelObjects.begin() + realTo + realN);
2621
2622 } else {
2623 m_listModel->move(from, to, n);
2624 }
2625
2626 if (m_mainThread)
2627 endMoveRows();
2628}
2629
2630/*!
2631 \qmlmethod void ListModel::append(jsobject dict)
2632
2633 Adds a new item to the end of the list model, with the
2634 values in \a dict.
2635
2636 \code
2637 fruitModel.append({"cost": 5.95, "name":"Pizza"})
2638 \endcode
2639
2640 \sa set(), remove()
2641*/
2642void QQmlListModel::append(QQmlV4FunctionPtr args)
2643{
2644 if (args->length() == 1) {
2645 QV4::Scope scope(args->v4engine());
2646 QV4::ScopedObject argObject(scope, (*args)[0]);
2647 QV4::ScopedArrayObject objectArray(scope, (*args)[0]);
2648
2649 if (objectArray) {
2650 QV4::ScopedObject argObject(scope);
2651
2652 int objectArrayLength = objectArray->getLength();
2653 if (objectArrayLength > 0) {
2654 int index = count();
2655 emitItemsAboutToBeInserted(index, objectArrayLength);
2656
2657 for (int i=0 ; i < objectArrayLength ; ++i) {
2658 argObject = objectArray->get(i);
2659
2660 if (m_dynamicRoles) {
2661 m_modelObjects.append(DynamicRoleModelNode::create(scope.engine->variantMapFromJS(argObject), this));
2662 } else {
2663 m_listModel->append(argObject);
2664 }
2665 }
2666
2667 emitItemsInserted();
2668 }
2669 } else if (argObject) {
2670 int index;
2671
2672 if (m_dynamicRoles) {
2673 index = m_modelObjects.size();
2674 emitItemsAboutToBeInserted(index, 1);
2675 m_modelObjects.append(DynamicRoleModelNode::create(scope.engine->variantMapFromJS(argObject), this));
2676 } else {
2677 index = m_listModel->elementCount();
2678 emitItemsAboutToBeInserted(index, 1);
2679 m_listModel->append(argObject);
2680 }
2681
2682 emitItemsInserted();
2683 } else {
2684 qmlWarning(this) << tr("append: value is not an object");
2685 }
2686 } else {
2687 qmlWarning(this) << tr("append: value is not an object");
2688 }
2689}
2690
2691/*!
2692 \qmlmethod var ListModel::get(int index)
2693
2694 Returns the item at \a index in the list model. This allows the item
2695 data to be accessed or modified from JavaScript:
2696
2697 \code
2698 Component.onCompleted: {
2699 fruitModel.append({"cost": 5.95, "name":"Jackfruit"});
2700 console.log(fruitModel.get(0).cost);
2701 fruitModel.get(0).cost = 10.95;
2702 }
2703 \endcode
2704
2705 The \a index must be an element in the list.
2706
2707 Note that properties of the returned object that are themselves objects
2708 will also be models, and this get() method is used to access elements:
2709
2710 \code
2711 fruitModel.append(..., "attributes":
2712 [{"name":"spikes","value":"7mm"},
2713 {"name":"color","value":"green"}]);
2714 fruitModel.get(0).attributes.get(1).value; // == "green"
2715 \endcode
2716
2717 \warning The returned object is not guaranteed to remain valid. It
2718 should not be used in \l{Property Binding}{property bindings} or for
2719 storing data across modifications of its origin ListModel.
2720
2721 \sa append(), clear()
2722*/
2723QJSValue QQmlListModel::get(int index) const
2724{
2725 QV4::Scope scope(engine());
2726 QV4::ScopedValue result(scope, QV4::Value::undefinedValue());
2727
2728 if (index >= 0 && index < count()) {
2729
2730 if (m_dynamicRoles) {
2731 DynamicRoleModelNode *object = m_modelObjects[index];
2732 result = QV4::QObjectWrapper::wrap(scope.engine, object);
2733 } else {
2734 QObject *object = m_listModel->getOrCreateModelObject(const_cast<QQmlListModel *>(this), index);
2735 QQmlData *ddata = QQmlData::get(object);
2736 if (ddata->jsWrapper.isNullOrUndefined()) {
2737 result = scope.engine->memoryManager->allocate<QV4::ModelObject>(object, const_cast<QQmlListModel *>(this));
2738 // Keep track of the QObjectWrapper in persistent value storage
2739 ddata->jsWrapper.set(scope.engine, result);
2740 } else {
2741 result = ddata->jsWrapper.value();
2742 }
2743 }
2744 }
2745
2746 return QJSValuePrivate::fromReturnedValue(result->asReturnedValue());
2747}
2748
2749/*!
2750 \qmlmethod void ListModel::set(int index, jsobject dict)
2751
2752 Changes the item at \a index in the list model with the
2753 values in \a dict. Properties not appearing in \a dict
2754 are left unchanged.
2755
2756 \code
2757 fruitModel.set(3, {"cost": 5.95, "name":"Pizza"})
2758 \endcode
2759
2760 If \a index is equal to count() then a new item is appended to the
2761 list. Otherwise, \a index must be an element in the list.
2762
2763 \sa append()
2764*/
2765void QQmlListModel::set(int index, const QJSValue &value)
2766{
2767 QV4::Scope scope(engine());
2768 QV4::ScopedObject object(scope, QJSValuePrivate::asReturnedValue(&value));
2769
2770 if (!object) {
2771 qmlWarning(this) << tr("set: value is not an object");
2772 return;
2773 }
2774 if (index > count() || index < 0) {
2775 qmlWarning(this) << tr("set: index %1 out of range").arg(index);
2776 return;
2777 }
2778
2779
2780 if (index == count()) {
2781 emitItemsAboutToBeInserted(index, 1);
2782
2783 if (m_dynamicRoles) {
2784 m_modelObjects.append(DynamicRoleModelNode::create(scope.engine->variantMapFromJS(object), this));
2785 } else {
2786 m_listModel->insert(index, object);
2787 }
2788
2789 emitItemsInserted();
2790 } else {
2791
2792 QList<int> roles;
2793
2794 if (m_dynamicRoles) {
2795 m_modelObjects[index]->updateValues(scope.engine->variantMapFromJS(object), roles);
2796 } else {
2797 m_listModel->set(index, object, &roles);
2798 }
2799
2800 if (roles.size())
2801 emitItemsChanged(index, 1, roles);
2802 }
2803}
2804
2805/*!
2806 \qmlmethod void ListModel::setProperty(int index, string property, var value)
2807
2808 Changes the \a property of the item at \a index in the list model to \a value.
2809
2810 \code
2811 fruitModel.setProperty(3, "cost", 5.95)
2812 \endcode
2813
2814 The \a index must be an element in the list.
2815
2816 \sa append()
2817*/
2818void QQmlListModel::setProperty(int index, const QString& property, const QVariant& value)
2819{
2820 if (count() == 0 || index >= count() || index < 0) {
2821 qmlWarning(this) << tr("set: index %1 out of range").arg(index);
2822 return;
2823 }
2824
2825 if (m_dynamicRoles) {
2826 int roleIndex = m_roles.indexOf(property);
2827 if (roleIndex == -1) {
2828 roleIndex = m_roles.size();
2829 m_roles.append(property);
2830 }
2831 if (m_modelObjects[index]->setValue(property.toUtf8(), value))
2832 emitItemsChanged(index, 1, QList<int>(1, roleIndex));
2833 } else {
2834 int roleIndex = m_listModel->setOrCreateProperty(index, property, value);
2835 if (roleIndex != -1)
2836 emitItemsChanged(index, 1, QList<int>(1, roleIndex));
2837 }
2838}
2839
2840/*!
2841 \qmlmethod void ListModel::sync()
2842
2843 Writes any unsaved changes to the list model after it has been modified
2844 from a worker script.
2845*/
2846void QQmlListModel::sync()
2847{
2848 // This is just a dummy method to make it look like sync() exists in
2849 // ListModel (and not just QQmlListModelWorkerAgent) and to let
2850 // us document sync().
2851 qmlWarning(this) << "List sync() can only be called from a WorkerScript";
2852}
2853
2854bool QQmlListModelParser::verifyProperty(
2855 const QQmlRefPointer<QV4::CompiledData::CompilationUnit> &compilationUnit,
2856 const QV4::CompiledData::Binding *binding)
2857{
2858 if (binding->type() >= QV4::CompiledData::Binding::Type_Object) {
2859 const quint32 targetObjectIndex = binding->value.objectIndex;
2860 const QV4::CompiledData::Object *target = compilationUnit->objectAt(targetObjectIndex);
2861 QString objName = compilationUnit->stringAt(target->inheritedTypeNameIndex);
2862 if (objName != listElementTypeName) {
2863 const QMetaObject *mo = resolveType(objName);
2864 if (mo != &QQmlListElement::staticMetaObject) {
2865 error(target, QQmlListModel::tr("ListElement: cannot contain nested elements"));
2866 return false;
2867 }
2868 listElementTypeName = objName; // cache right name for next time
2869 }
2870
2871 if (!compilationUnit->stringAt(target->idNameIndex).isEmpty()) {
2872 error(target->locationOfIdProperty, QQmlListModel::tr("ListElement: cannot use reserved \"id\" property"));
2873 return false;
2874 }
2875
2876 const QV4::CompiledData::Binding *binding = target->bindingTable();
2877 for (quint32 i = 0; i < target->nBindings; ++i, ++binding) {
2878 QString propName = compilationUnit->stringAt(binding->propertyNameIndex);
2879 if (propName.isEmpty()) {
2880 error(binding, QQmlListModel::tr("ListElement: cannot contain nested elements"));
2881 return false;
2882 }
2883 if (!verifyProperty(compilationUnit, binding))
2884 return false;
2885 }
2886 } else if (binding->type() == QV4::CompiledData::Binding::Type_Script) {
2887 QString scriptStr = compilationUnit->bindingValueAsScriptString(binding);
2888 if (!binding->isFunctionExpression() && !definesEmptyList(scriptStr)) {
2889 bool ok;
2890 evaluateEnum(scriptStr, &ok);
2891 if (!ok) {
2892 error(binding, QQmlListModel::tr("ListElement: cannot use script for property value"));
2893 return false;
2894 }
2895 }
2896 }
2897
2898 return true;
2899}
2900
2901bool QQmlListModelParser::applyProperty(
2902 const QQmlRefPointer<QV4::ExecutableCompilationUnit> &compilationUnit,
2903 const QV4::CompiledData::Binding *binding, ListModel *model, QQmlListModel *owner,
2904 int outterElementIndex)
2905{
2906 const QString elementName = compilationUnit->stringAt(binding->propertyNameIndex);
2907
2908 bool roleSet = false;
2909 const QV4::CompiledData::Binding::Type bindingType = binding->type();
2910 if (bindingType >= QV4::CompiledData::Binding::Type_Object) {
2911 const quint32 targetObjectIndex = binding->value.objectIndex;
2912 const QV4::CompiledData::Object *target = compilationUnit->objectAt(targetObjectIndex);
2913
2914 ListModel *subModel = nullptr;
2915 if (outterElementIndex == -1) {
2916 subModel = model;
2917 } else {
2918 const ListLayout::Role &role = model->getOrCreateListRole(elementName);
2919 if (role.type == ListLayout::Role::List) {
2920 subModel = model->getListProperty(outterElementIndex, role);
2921 if (subModel == nullptr) {
2922 subModel = new ListModel(role.subLayout, nullptr);
2923 model->setOrCreateProperty(
2924 outterElementIndex, elementName,
2925 QVariant::fromValue(subModel));
2926 }
2927 }
2928 }
2929
2930 int elementIndex = subModel ? subModel->appendElement() : -1;
2931
2932 const QV4::CompiledData::Binding *subBinding = target->bindingTable();
2933 for (quint32 i = 0; i < target->nBindings; ++i, ++subBinding) {
2934 roleSet |= applyProperty(compilationUnit, subBinding, subModel, owner, elementIndex);
2935 }
2936 } else if (!model) {
2937 return false;
2938 } else {
2939 QVariant value;
2940
2941 const bool isTranslationBinding = binding->isTranslationBinding();
2942 if (isTranslationBinding) {
2943 value = QVariant::fromValue<const QV4::CompiledData::Binding*>(binding);
2944 } else if (binding->evaluatesToString()) {
2945 value = compilationUnit->bindingValueAsString(binding);
2946 } else if (bindingType == QV4::CompiledData::Binding::Type_Number) {
2947 value = compilationUnit->bindingValueAsNumber(binding);
2948 } else if (bindingType == QV4::CompiledData::Binding::Type_Boolean) {
2949 value = binding->valueAsBoolean();
2950 } else if (bindingType == QV4::CompiledData::Binding::Type_Null) {
2951 value = QVariant::fromValue(nullptr);
2952 } else if (bindingType == QV4::CompiledData::Binding::Type_Script) {
2953 QString scriptStr = compilationUnit->bindingValueAsScriptString(binding);
2954 if (definesEmptyList(scriptStr)) {
2955 value = QVariant::fromValue(
2956 new ListModel(model->getOrCreateListRole(elementName).subLayout, nullptr));
2957 } else if (binding->isFunctionExpression()) {
2958 QQmlBinding::Identifier id = binding->value.compiledScriptIndex;
2959 Q_ASSERT(id != QQmlBinding::Invalid);
2960
2961 auto v4 = compilationUnit->engine;
2962 QV4::Scope scope(v4);
2963
2964 if (model->m_modelCache == nullptr) {
2965 model->m_modelCache = new QQmlListModel(owner, model, v4);
2966 QQmlEngine::setContextForObject(
2967 model->m_modelCache, QQmlEngine::contextForObject(owner));
2968 }
2969
2970 // for now we do not provide a context object; data from the ListElement must be passed to the function
2971 QV4::ScopedContext context(scope, QV4::QmlContext::create(v4->rootContext(), QQmlContextData::get(qmlContext(model->m_modelCache)), nullptr));
2972 QV4::ScopedFunctionObject function(scope, QV4::FunctionObject::createScriptFunction(context, compilationUnit->runtimeFunctions[id]));
2973
2974 QJSValue v;
2975 QV4::ScopedValue result(scope, function->call(v4->globalObject, nullptr, 0));
2976 if (v4->hasException)
2977 v4->catchException();
2978 else
2979 QJSValuePrivate::setValue(&v, result);
2980 value.setValue(v);
2981 } else {
2982 bool ok;
2983 value = evaluateEnum(scriptStr, &ok);
2984 }
2985 } else {
2986 Q_UNREACHABLE();
2987 }
2988
2989 model->setOrCreateProperty(outterElementIndex, elementName, value);
2990 auto listModel = model->m_modelCache;
2991 if (isTranslationBinding && listModel) {
2992 if (!listModel->translationChangeHandler) {
2993 auto ep = QQmlEnginePrivate::get(compilationUnit->engine);
2994 model->m_modelCache->translationChangeHandler = std::make_unique<QPropertyNotifier>(
2995 ep->translationLanguage.addNotifier([listModel](){ listModel->updateTranslations(); }));
2996 }
2997 }
2998 roleSet = true;
2999 }
3000 return roleSet;
3001}
3002
3004 const QQmlRefPointer<QV4::CompiledData::CompilationUnit> &compilationUnit,
3005 const QList<const QV4::CompiledData::Binding *> &bindings)
3006{
3007 listElementTypeName = QString(); // unknown
3008
3009 for (const QV4::CompiledData::Binding *binding : bindings) {
3010 QString propName = compilationUnit->stringAt(binding->propertyNameIndex);
3011 if (!propName.isEmpty()) { // isn't default property
3012 error(binding, QQmlListModel::tr("ListModel: undefined property '%1'").arg(propName));
3013 return;
3014 }
3015 if (!verifyProperty(compilationUnit, binding))
3016 return;
3017 }
3018}
3019
3020void QQmlListModelParser::applyBindings(
3021 QObject *obj, const QQmlRefPointer<QV4::ExecutableCompilationUnit> &compilationUnit,
3022 const QList<const QV4::CompiledData::Binding *> &bindings)
3023{
3024 QQmlListModel *rv = static_cast<QQmlListModel *>(obj);
3025
3026 rv->m_engine = qmlEngine(rv)->handle();
3027 rv->m_compilationUnit = compilationUnit;
3028
3029 bool setRoles = false;
3030
3031 for (const QV4::CompiledData::Binding *binding : bindings) {
3032 if (binding->type() != QV4::CompiledData::Binding::Type_Object)
3033 continue;
3034 setRoles |= applyProperty(
3035 compilationUnit, binding, rv->m_listModel, rv, /*outter element index*/-1);
3036 }
3037
3038 if (setRoles == false)
3039 qmlWarning(obj) << "All ListElement declarations are empty, no roles can be created unless dynamicRoles is set.";
3040}
3041
3042bool QQmlListModelParser::definesEmptyList(QStringView s)
3043{
3044 if (s.startsWith(QLatin1Char('[')) && s.endsWith(QLatin1Char(']'))) {
3045 for (auto c : s.sliced(1).chopped(1)) {
3046 if (!c.isSpace())
3047 return false;
3048 }
3049 return true;
3050 }
3051 return false;
3052}
3053
3054
3055/*!
3056 \qmltype ListElement
3057 \nativetype QQmlListElement
3058 \inqmlmodule QtQml.Models
3059 \brief Defines a data item in a ListModel.
3060 \ingroup qtquick-models
3061
3062 List elements are defined inside ListModel definitions, and represent items in a
3063 list that will be displayed using ListView or \l Repeater items.
3064
3065 List elements are defined like other QML elements except that they contain
3066 a collection of \e role definitions instead of properties. Using the same
3067 syntax as property definitions, roles both define how the data is accessed
3068 and include the data itself.
3069
3070 The names used for roles must begin with a lower-case letter and should be
3071 common to all elements in a given model. Values must be simple constants; either
3072 strings (quoted and optionally within a call to
3073 \l [QML] {Qt::} {QT_TR_NOOP()}, boolean values (true, false), numbers, or
3074 enumeration values (such as AlignText.AlignHCenter).
3075
3076 Beginning with Qt 5.11 ListElement also allows assigning a function declaration to
3077 a role. This allows the definition of ListElements with callable actions.
3078
3079 \section1 Referencing Roles
3080
3081 The role names are used by delegates to obtain data from list elements.
3082 Each role name is accessible in the delegate's scope, and refers to the
3083 corresponding role in the current element. Where a role name would be
3084 ambiguous to use, it can be accessed via the \l{ListView::}{model}
3085 property (e.g., \c{model.cost} instead of \c{cost}).
3086
3087 \section1 Example Usage
3088
3089 The following model defines a series of list elements, each of which
3090 contain "name" and "cost" roles and their associated values.
3091
3092 \snippet qml/listmodel/listelements.qml model
3093
3094 The delegate obtains the name and cost for each element by simply referring
3095 to \c name and \c cost:
3096
3097 \snippet qml/listmodel/listelements.qml view
3098
3099 \sa ListModel
3100*/
3101
3102QT_END_NAMESPACE
3103
3104#include "moc_qqmllistmodel_p_p.cpp"
3105
3106#include "moc_qqmllistmodel_p.cpp"
DynamicRoleModelNodeMetaObject(DynamicRoleModelNode *object)
void propertyWritten(int index) override
void propertyWrite(int index) override
void updateValues(const QVariantMap &object, QList< int > &roles)
void setNodeUpdatesEnabled(bool enable)
ListElement(int existingUid)
Role(const Role *other)
ListLayout(const ListLayout *other)
int roleCount() const
const Role * getExistingRole(QV4::String *key) const
static void sync(ListLayout *src, ListLayout *target)
const Role & getExistingRole(int index) const
const Role & getRoleOrCreate(QV4::String *key, Role::DataType type)
void set(int elementIndex, QV4::Object *object, SetElement reason=SetElement::IsCurrentlyUpdated)
static bool sync(ListModel *src, ListModel *target)
int append(QV4::Object *object)
QVariant getProperty(int elementIndex, int roleIndex, const QQmlListModel *owner, QV4::ExecutionEngine *eng)
int elementCount() const
void move(int from, int to, int n)
void insertElement(int index)
ListModel(ListLayout *layout, QQmlListModel *modelCache)
int appendElement()
void insert(int elementIndex, QV4::Object *object)
void updateTranslations()
QObject * getOrCreateModelObject(QQmlListModel *model, int elementIndex)
ListModel * getListProperty(int elementIndex, const ListLayout::Role &role)
int roleCount() const
void set(int elementIndex, QV4::Object *object, QList< int > *roles)
const ListLayout::Role & getExistingRole(int index) const
void propertyWritten(int index) override
void updateValues(const QList< int > &roles)
ModelNodeMetaObject(QObject *object, QQmlListModel *model, int elementIndex)
\inmodule QtCore
Definition qobject.h:106
void verifyBindings(const QQmlRefPointer< QV4::CompiledData::CompilationUnit > &compilationUnit, const QList< const QV4::CompiledData::Binding * > &bindings) override
Definition qjsvalue.h:24
DEFINE_OBJECT_VTABLE(ModelObject)
static QAtomicInt uidCounter(MIN_LISTMODEL_UID)
Q_DECLARE_METATYPE(const QV4::CompiledData::Binding *)
static bool isMemoryUsed(const char *mem)
static QString roleTypeName(ListLayout::Role::DataType t)
PropertyKey next(const Object *o, Property *pd=nullptr, PropertyAttributes *attrs=nullptr) override
~ModelObjectOwnPropertyKeyIterator() override=default
QString toString(const QQmlListModel *owner) const
QString asString() const
void setTranslation(const QV4::CompiledData::Binding *binding)