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
qqmlpreviewbindingpatchcontext.cpp
Go to the documentation of this file.
1// Copyright (C) 2026 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 reason:default
4
6
7#include <private/qqmlcomponent_p.h>
8#include <private/qqmlnotifier_p.h>
9#include <private/qqmlobjectcreator_p.h>
10#include <private/qqmlproperty_p.h>
11#include <private/qqmlproperty_p.h>
12#include <private/qqmlpropertybinding_p.h>
13#include <private/qqmlpropertytopropertybinding_p.h>
14#include <private/qqmltypeloader_p.h>
15#include <private/qqmlvaluetypeproxybinding_p.h>
16#include <private/qqmlvme_p.h>
17#include <private/qv4functionobject_p.h>
18#include <private/qv4generatorobject_p.h>
19#include <private/qv4qmlcontext_p.h>
20#include <private/qv4resolvedtypereference_p.h>
21
22#include <QtCore/qqueue.h>
23#include <QtCore/qset.h>
24
26
27namespace QQmlPreview {
28
29
30static bool functionBelongsToObject(const QV4::Function *f,
31 const QQmlRefPointer<QV4::ExecutableCompilationUnit> &cu,
32 int objectIndex)
33{
34 if (f->executableCompilationUnit() != cu)
35 return false;
36
37 const QV4::CompiledData::Object *obj = cu->objectAt(objectIndex);
38 for (auto binding = obj->bindingsBegin(), end = obj->bindingsEnd(); binding != end; ++binding) {
39 switch (binding->type()) {
40 case QV4::CompiledData::Binding::Type_GroupedProperty:
41 case QV4::CompiledData::Binding::Type_AttachedProperty:
42 case QV4::CompiledData::Binding::Type_Object:
43 if (functionBelongsToObject(f, cu, binding->value.objectIndex))
44 return true;
45 break;
46 case QV4::CompiledData::Binding::Type_Script:
47 if (cu->runtimeFunctions[binding->value.compiledScriptIndex] == f)
48 return true;
49 default:
50 break;
51 }
52 }
53 return false;
54}
55
56// A binding that lives in one of target's outer contexts is recreated when that context's root is
57// rebuilt, so it is not actually external. Returns true if `cu` is reachable through the context
58// chain before we leave the set of units being rebuilt.
59static bool rebuildReachesUnitViaContext(const QQmlRefPointer<QV4::ExecutableCompilationUnit> &cu,
60 const std::vector<CompositeLevel> &internalUnits,
61 QObject *target)
62{
63 const QQmlData *ddata = QQmlData::get(target);
64 if (!ddata)
65 return false;
66
67 for (QQmlRefPointer<QQmlContextData> context = ddata->outerContext; context;
68 context = context->parent()) {
69 const QQmlRefPointer<QV4::ExecutableCompilationUnit> ctxCu = context->typeCompilationUnit();
70 if (!ctxCu)
71 continue;
72
73 if (ctxCu == cu)
74 return true;
75
76 if (std::any_of(internalUnits.begin(), internalUnits.end(),
77 [&](const CompositeLevel &level) {
78 return level.oldCu == ctxCu || level.newCu == ctxCu;
79 })) {
80 break;
81 }
82 }
83
84 return false;
85}
86
87// Classifies a single binding's JavaScript function: does it belong to one of the compilation
88// units participating in the rebuild (internal, will be recreated), or to some other component
89// (external, must be preserved)? A null function is treated as external.
90static bool isExternalFunction(const QV4::Function *f,
91 const std::vector<CompositeLevel> &internalUnits, QObject *target)
92{
93 if (!f)
94 return true;
95
96 for (const auto &internalUnit : internalUnits) {
97 if (functionBelongsToObject(f, internalUnit.oldCu, internalUnit.objectIndex)
98 || functionBelongsToObject(f, internalUnit.newCu, internalUnit.objectIndex)) {
99 return false;
100 }
101 }
102
103 return !rebuildReachesUnitViaContext(f->executableCompilationUnit(), internalUnits, target);
104}
105
106// A translation binding has no JavaScript function, so it cannot be classified via
107// isExternalFunction. Classify it by its compilation unit instead: it is internal if that unit is
108// one of the units being rebuilt, directly or through the context chain.
109static bool isExternalUnitBinding(const QQmlRefPointer<QV4::ExecutableCompilationUnit> &cu,
110 const std::vector<CompositeLevel> &internalUnits, QObject *target)
111{
112 if (!cu)
113 return true;
114
115 for (const auto &internalUnit : internalUnits) {
116 if (internalUnit.oldCu == cu || internalUnit.newCu == cu)
117 return false;
118 }
119
120 return !rebuildReachesUnitViaContext(cu, internalUnits, target);
121}
122
123// Determines whether a binding on a property is "external", i.e. not from any of the
124// compilation units that participate in the rebuild of this object.
125// External bindings come from other compilation units (e.g. a parent component setting a
126// property binding on a child instance) and must be preserved across rebuilds.
127static bool isExternalBinding(const QQmlAnyBinding &binding,
128 const std::vector<CompositeLevel> &internalUnits, QObject *target)
129{
130 if (!binding)
131 return false;
132
133 if (const QQmlAbstractBinding *abstractBinding = binding.asAbstractBinding()) {
134 switch (abstractBinding->kind()) {
135 case QQmlAbstractBinding::QmlBinding: {
136 const auto *qmlBinding = static_cast<const QQmlBinding *>(abstractBinding);
137 if (const QV4::Function *f = qmlBinding->function())
138 return isExternalFunction(f, internalUnits, target);
139 // No function: this may be a translation binding. Classify it by its compilation unit.
140 return isExternalUnitBinding(qmlBinding->compilationUnit(), internalUnits, target);
141 }
142 case QQmlAbstractBinding::ValueTypeProxy: {
143 // A value-type group binding has no function of its own: it is a proxy holding one
144 // QQmlBinding per bound sub-property. Classify it by its sub-bindings.
145 const auto *proxy = static_cast<const QQmlValueTypeProxyBinding *>(abstractBinding);
146 for (QQmlAbstractBinding *sub = proxy->subBindings(); sub; sub = sub->nextBinding()) {
147 if (sub->kind() != QQmlAbstractBinding::QmlBinding)
148 continue;
149 if (!isExternalFunction(static_cast<const QQmlBinding *>(sub)->function(),
150 internalUnits, target)) {
151 return false;
152 }
153 }
154 return true;
155 }
156 case QQmlAbstractBinding::PropertyToPropertyBinding:
157 return true;
158 }
159 return true;
160 }
161
162 if (const QPropertyBindingPrivate *priv =
163 QPropertyBindingPrivate::get(binding.asUntypedPropertyBinding())) {
164 if (priv->isQmlBinding()) {
165 // Check if it's a QQmlPropertyBinding with a JS expression we can trace back to a CU.
166 const auto base = static_cast<const QQmlPropertyBindingBase *>(priv);
167 if (base->bindingKind() == QQmlPropertyBindingBase::BindingKind::JavaScript) {
168 if (const QQmlPropertyBindingJS *jsExpr =
169 static_cast<const QQmlPropertyBinding *>(base)->jsExpression()) {
170 return isExternalFunction(jsExpr->function(), internalUnits, target);
171 }
172 }
173 } else if (const auto cu = QQmlTranslationPropertyBinding::compilationUnit(priv)) {
174 // A translation binding on a bindable property is a plain QUntypedPropertyBinding
175 // rather than a QQmlPropertyBinding. Recover its compilation unit to classify it like
176 // the QQmlBinding case.
177 return isExternalUnitBinding(cu, internalUnits, target);
178 }
179 }
180
181 return true;
182}
183
184static QObject *propertyToPropertySource(const QQmlAnyBinding &binding)
185{
186 if (const QQmlAbstractBinding *abstractBinding = binding.asAbstractBinding()) {
187 if (abstractBinding->kind() == QQmlAbstractBinding::PropertyToPropertyBinding) {
188 return static_cast<const QQmlPropertyToUnbindablePropertyBinding *>(abstractBinding)
189 ->source();
190 }
191 } else if (const QPropertyBindingPrivate *priv =
192 QPropertyBindingPrivate::get(binding.asUntypedPropertyBinding());
193 priv && priv->isQmlBinding()) {
194 const auto base = static_cast<const QQmlPropertyBindingBase *>(priv);
195 if (base->bindingKind() == QQmlPropertyBindingBase::BindingKind::PropertyToProperty)
196 return static_cast<const QQmlPropertyToBindablePropertyBinding *>(priv)->source();
197 }
198 return nullptr;
199}
200
201static QVariant literalBindingValue(const QQmlRefPointer<QV4::ExecutableCompilationUnit> &unit,
202 const QV4::CompiledData::Binding *binding)
203{
204 switch (binding->type()) {
205 case QV4::CompiledData::Binding::Type_Number: {
206 const double d = unit->bindingValueAsNumber(binding);
207 return QV4::Value::isInt32(d) ? QVariant(int(d)) : QVariant(d);
208 }
209 case QV4::CompiledData::Binding::Type_Boolean:
210 return QVariant(bool(binding->value.b));
211 case QV4::CompiledData::Binding::Type_Translation:
212 case QV4::CompiledData::Binding::Type_TranslationById:
213 case QV4::CompiledData::Binding::Type_String:
214 return unit->bindingValueAsString(binding);
215 case QV4::CompiledData::Binding::Type_Null:
216 return QVariant::fromValue(nullptr);
217 default:
218 // Script bindings, object bindings, etc. carry no constant value.
219 return QVariant();
220 }
221}
222
223QVariant
224BindingPatchContext::literalValue(const QQmlRefPointer<QV4::ExecutableCompilationUnit> &unit,
225 const QV4::CompiledData::Binding *binding)
226{
227 return literalBindingValue(unit, binding);
228}
229
230static QVariant coerceToPropertyType(QV4::ExecutionEngine *v4, const QVariant &value,
231 QMetaType propertyType)
232{
233 if (propertyType == QMetaType::fromType<QVariant>() || value.metaType() == propertyType)
234 return value;
235
236 QV4::Scope scope(v4);
237 QV4::ScopedValue v(scope, v4->metaTypeToJS(value.metaType(), value.constData()));
238 QVariant result(propertyType);
239 v4->metaTypeFromJS(v, propertyType, result.data());
240 return result;
241}
242
243void BindingPatchContext::recordBindingValues(
244 const QQmlRefPointer<QV4::ExecutableCompilationUnit> &unit, int cuIndex,
245 QHash<QString, QVariant> *constantValues, QDuplicateTracker<QObject *> *seenChildren)
246{
247 Q_ASSERT(constantValues);
248
249 if (!unit || cuIndex >= unit->objectCount())
250 return;
251
252 const QV4::CompiledData::Object *obj = unit->objectAt(cuIndex);
253 const QQmlPropertyCache::ConstPtr cache = unit->propertyCachesPtr()->at(cuIndex);
254
255 for (auto binding = obj->bindingsBegin(), end = obj->bindingsEnd(); binding != end; ++binding) {
256
257 const QString name = targetPropertyName(unit, cuIndex, binding);
258 if (name.isEmpty())
259 continue;
260
261 switch (binding->type()) {
262 case QV4::CompiledData::Binding::Type_AttachedProperty:
263 attachedContext(unit, binding, seenChildren);
264 continue;
265 case QV4::CompiledData::Binding::Type_GroupedProperty:
266 childContext(unit, cuIndex, binding, seenChildren);
267 continue;
268 default:
269 break;
270 }
271
272 if (unit->bindingIsSignalHandler(cuIndex, int(binding - obj->bindingsBegin())))
273 continue;
274
275 if (unit->bindingIsCustomParser(cuIndex, int(binding - obj->bindingsBegin())))
276 continue;
277
278 const qsizetype size = constantValues->size();
279 QVariant &value = (*constantValues)[name];
280 if (constantValues->size() == size)
281 continue;
282
283 // Extract constant value from the binding for comparison. Script and object bindings
284 // yield an invalid QVariant: they shouldn't be touched since we've just installed the
285 // new bindings (unless there is yet another, external binding).
286 value = literalBindingValue(unit, binding);
287 }
288
289 for (int propertyIndex = 0, end = obj->propertyCount(); propertyIndex != end; ++propertyIndex) {
290 const qsizetype size = constantValues->size();
291 QVariant &value =
292 (*constantValues)[unit->stringAt(obj->propertyTable()[propertyIndex].nameIndex())];
293 if (constantValues->size() != size)
294 value = QVariant(cache->property(cache->propertyOffset() + propertyIndex)->propType());
295 }
296}
297
298void BindingPatchContext::stashExternalState(const std::vector<CompositeLevel> &internalUnits,
299 QDuplicateTracker<QObject *> *seenChildren)
300{
301 // Determine which properties are assigned by the CU and their constant values
302 QHash<QString, QVariant> constantValues;
303 recordBindingValues(unit, objectIndex, &constantValues, seenChildren);
304
305 if (prefix.isEmpty()) {
306 const QQmlData *ddata = QQmlData::get(m_object);
307 if (ddata->compilationUnit) {
308 recordBindingValues(ddata->compilationUnit, ddata->cuObjectIndex, &constantValues,
309 seenChildren);
310 }
311
312 if (ddata->hasVMEMetaObject) {
313 for (QQmlVMEMetaObject *vmeMeta = static_cast<QQmlVMEMetaObject *>(
314 QObjectPrivate::get(m_object)->metaObject);
315 vmeMeta; vmeMeta = vmeMeta->parentVMEMetaObject()) {
316 if (auto cu = vmeMeta->compilationUnit())
317 recordBindingValues(cu, vmeMeta->qmlObjectId(), &constantValues, seenChildren);
318 }
319 }
320 }
321
322 // Iterate all properties. For those in the CU's binding table, check if the current state
323 // differs from what the CU set (indicating an external override to preserve). For the rest,
324 // check for external bindings installed by other components.
325 // Additionally, for QObject* properties pointing to QML-created children, register them
326 // as child contexts so their external signal handlers are stashed recursively at the end.
327 const QMetaObject *mo = m_object->metaObject();
328 for (int i = 0, count = mo->propertyCount(); i < count; ++i) {
329 const QMetaProperty metaProp = mo->property(i);
330 const QString propName = QString::fromUtf8(metaProp.name());
331
332 const QQmlProperty qProp(m_object, propName);
333 if (!qProp.isValid())
334 continue;
335
336 // Discover QML-created child objects accessible via QObject* properties.
337 // Objects without a CU (like lazily-created grouped property objects) survive
338 // rebuilds unchanged and don't need stashing.
339 if (qProp.propertyMetaType().flags().testFlag(QMetaType::PointerToQObject)) {
340 if (QObject *child = qProp.read().value<QObject *>()) {
341 if (QQmlData *childDdata = QQmlData::get(child)) {
342 if (const auto &childCU = childDdata->compilationUnit; childCU
343 && std::find_if(internalUnits.begin(), internalUnits.end(),
344 [&](const CompositeLevel &level) {
345 return level.newCu == childCU || level.oldCu == childCU;
346 })
347 != internalUnits.end()) {
348 childContext(propName, child, childCU, childDdata->cuObjectIndex,
349 seenChildren);
350 }
351 }
352 }
353 }
354
355 const auto it = constantValues.constFind(propName);
356 if (it == constantValues.cend()) {
357 // Property not in CU's binding table — check for external bindings.
358 const QQmlAnyBinding binding = QQmlAnyBinding::ofProperty(qProp);
359 if (isExternalBinding(binding, internalUnits, m_object)) {
360 QQmlAnyBinding taken = QQmlAnyBinding::takeFrom(qProp);
361 m_storedBindings.push_back(
362 { propName, std::move(taken), propertyToPropertySource(binding) });
363 }
364 continue;
365 }
366
367 // Property is in the CU's binding table.
368 const QQmlAnyBinding binding = QQmlAnyBinding::ofProperty(qProp);
369 if (isExternalBinding(binding, internalUnits, m_object)) {
370 QQmlAnyBinding taken = QQmlAnyBinding::takeFrom(qProp);
371 m_storedBindings.push_back(
372 { propName, std::move(taken), propertyToPropertySource(binding) });
373 continue;
374 }
375
376 // Internal binding is still valid. Apparently it doesn't get overridden by an external
377 // constant or binding. Nothing to store.
378 if (binding)
379 continue;
380
381 if (!it->isValid()) {
382 // This is potentially an internal binding overridden by an external constant. But
383 // it can also be an enum assignment optimized away to omit the binding itself. We
384 // can't discern those. So we don't store them for now.
385 // TODO: We can probably do better here.
386 continue;
387 }
388
389 // Two constant values. Figure out if they're the same. If not, store.
390
391 const QVariant expected = coerceToPropertyType(unit->engine, *it, qProp.propertyMetaType());
392 if (const QVariant current = qProp.read(); current != expected)
393 m_storedValues.push_back({ propName, current });
394 }
395
396 const auto stashBoundSignal = [&](QQmlBoundSignal *boundSignal) {
397 const QByteArray signature =
398 QMetaObjectPrivate::signal(m_object->metaObject(), boundSignal->signalIndex())
399 .methodSignature();
400 QQmlNotifierEndpoint *next = boundSignal->nextEndpoint();
401 boundSignal->disconnect();
402 m_storedSignalHandlers.push_back(
403 { QString::fromUtf8(signature), std::unique_ptr<QQmlBoundSignal>(boundSignal) });
404 return next;
405 };
406
407 // Stash external signal handlers connected to this object's signals.
408 // A handler is "internal" only if its function will be recreated during repopulation
409 // (i.e., it's a signal handler binding at one of the specific object indices being rebuilt).
410 // Only QQmlBoundSignal endpoints are stashed — other notifier endpoints (e.g. alias
411 // tracking) are embedded in VME data arrays and cannot be safely owned or relocated.
412 if (QQmlNotifyList *list = QQmlData::get(m_object)->notifyList.loadRelaxed()) {
413 // Ensure all endpoints are moved from the pending 'todo' list into the
414 // laid-out 'notifies' array. Endpoints remain in 'todo' until a signal
415 // with a high enough index is actually delivered, so without this call
416 // we'd miss handlers for signals that were never fired (e.g. clicked()).
417 if (list->todo)
418 list->layout();
419 for (quint16 i = 0, end = list->notifiesSize; i < end; ++i) {
420 for (QQmlNotifierEndpoint *ep = list->notifies[i]; ep;) {
421 if (ep->callbackType() != QQmlNotifierEndpoint::QQmlBoundSignal) {
422 ep = ep->nextEndpoint();
423 continue;
424 }
425
426 QQmlBoundSignal *boundSignal = static_cast<QQmlBoundSignal *>(ep);
427 QQmlBoundSignalExpression *expr = boundSignal->expression();
428 if (!expr) {
429 ep = stashBoundSignal(boundSignal);
430 continue;
431 }
432
433 const QV4::Function *f = expr->function();
434 if (!f) {
435 ep = stashBoundSignal(boundSignal);
436 continue;
437 }
438
439 bool isInternal = false;
440 for (const CompositeLevel &internalUnit : internalUnits) {
441 if (functionBelongsToObject(f, internalUnit.oldCu, internalUnit.objectIndex)
442 || functionBelongsToObject(f, internalUnit.newCu,
443 internalUnit.objectIndex)) {
444 isInternal = true;
445 break;
446 }
447 }
448
449 ep = isInternal ? ep->nextEndpoint() : stashBoundSignal(boundSignal);
450 }
451 }
452 }
453
454 // Recurse into child contexts (grouped properties)
455 for (auto &[name, child] : m_children) {
456 if (child)
457 child->stashExternalState(internalUnits, seenChildren);
458 }
459}
460
462{
463 if (!m_object)
464 return;
465
466 // After a rebuild, child objects (accessed via grouped properties) may have
467 // been replaced. Re-fetch QObject pointers from the parent's properties so
468 // that restoreExternalState() reconnects to the new objects.
469 for (auto &[name, child] : m_children) {
470 if (!child)
471 continue;
472
473 // Children with a non-empty prefix share m_object with their parent
474 // (value-type grouped properties like "font."). Update them to match.
475 if (!child->prefix.isEmpty()) {
476 child->m_object = m_object;
477 child->refreshObjects();
478 continue;
479 }
480
481 if (QObject *newObj = m_object->property(name.toUtf8()).value<QObject *>())
482 child->m_object = newObj;
483
484 child->refreshObjects();
485 }
486}
487
489{
490 if (!m_object)
491 return;
492
493 // Restore external bindings (look up by name since indices may have shifted)
494 for (auto &stored : m_storedBindings) {
495 if (!stored.binding)
496 continue;
497
498 // If this was a property-to-property binding, verify the source object survived the
499 // rebuild. Delegate model items (the source for required-property bindings) are
500 // destroyed when the delegate is re-instantiated and new bindings are created
501 // automatically. Restoring a stale binding would dereference freed memory.
502 if (stored.sourceGuard.isNull()) {
503 bool isPTP = false;
504 if (auto *abstractBinding = stored.binding.asAbstractBinding()) {
505 isPTP = abstractBinding->kind()
506 == QQmlAbstractBinding::PropertyToPropertyBinding;
507 } else if (const QPropertyBindingPrivate *priv = QPropertyBindingPrivate::get(
508 stored.binding.asUntypedPropertyBinding())) {
509 const auto base = static_cast<const QQmlPropertyBindingBase *>(priv);
510 isPTP = base->bindingKind()
511 == QQmlPropertyBindingBase::BindingKind::PropertyToProperty;
512 }
513 if (isPTP)
514 continue;
515 }
516
517 QQmlProperty qProp(m_object, stored.propertyName);
518 if (!qProp.isValid())
519 continue;
520
521 // After a rebuild, child objects may have been replaced (refreshObjects).
522 // The stashed binding's targetObject still references the old object.
523 // Update it to the new object before installing, otherwise installOn()
524 // asserts that targetObject() == target.object().
525 if (auto *abstractBinding = stored.binding.asAbstractBinding()) {
526 if (abstractBinding->targetObject() != qProp.object())
527 abstractBinding->setTarget(qProp);
528 }
529
530 stored.binding.installOn(qProp);
531 }
532 m_storedBindings.clear();
533
534 // Restore externally set values (only if no new binding was installed)
535 for (auto &stored : m_storedValues) {
536 const QMetaObject *mo = m_object->metaObject();
537 const int idx = mo->indexOfProperty(stored.propertyName.toUtf8().constData());
538 if (idx < 0)
539 continue;
540
541 // Don't overwrite if a binding was just installed by repopulateBindings
542 QQmlProperty qProp(m_object, stored.propertyName);
543 if (!qProp.isValid())
544 continue;
545 QQmlAnyBinding currentBinding = QQmlAnyBinding::ofProperty(qProp);
546 if (currentBinding)
547 continue;
548
549 mo->property(idx).write(m_object, stored.value);
550 }
551 m_storedValues.clear();
552
553 // Restore external signal handlers that were detached during stash.
554 // Reconnect them to this object's signals.
555 if (!m_storedSignalHandlers.empty()) {
556 QQmlEngine *engine = unit->engine->qmlEngine();
557 for (auto &stored : m_storedSignalHandlers) {
558 const QMetaObject *metaObject = m_object->metaObject();
559 const int signalIndex = QMetaObjectPrivate::signalIndex(
560 metaObject->method(metaObject->indexOfSignal(stored.signature.toUtf8())));
561 if (signalIndex >= 0)
562 QQmlData::connectEndpoint(stored.handler.release(), m_object, signalIndex, engine);
563 }
564 }
565 m_storedSignalHandlers.clear();
566
567 // Recurse into child contexts (grouped properties)
568 for (auto &[name, child] : m_children) {
569 if (child)
570 child->restoreExternalState();
571 }
572}
573
574// The object referenced by the id "name" in the context the object belongs to, or nullptr if
575// there is no such id. Used to resolve the first chain part of a generalized grouped property
576// ("someId.x": here name == "someId").
577static QObject *idTarget(QObject *object, const QString &name)
578{
579 const QQmlData *ddata = QQmlData::get(object);
580 Q_ASSERT(ddata);
581 QQmlContextData *context = ddata->ownContext ? ddata->ownContext.data() : ddata->context;
582 Q_ASSERT(context);
583 return context->asQQmlContext()->objectForName(name);
584}
585
587BindingPatchContext::childContext(const QQmlRefPointer<QV4::ExecutableCompilationUnit> &unit,
588 int objectIndex, const QV4::CompiledData::Binding *binding,
589 QDuplicateTracker<QObject *> *seenChildren)
590{
591 const QString name = unit->stringAt(binding->propertyNameIndex);
592
593 const size_t size = m_children.size();
594 std::unique_ptr<BindingPatchContext> &child = m_children[name];
595 if (size == m_children.size())
596 return child.get();
597
598 if (!seenChildren)
599 return nullptr;
600
601 const QByteArray nameUtf8 = name.toUtf8();
602 QObject *groupObject = nullptr;
603 if (m_object->metaObject()->indexOfProperty(nameUtf8.constData()) >= 0) {
604 // "name" is a property of m_object, so it always wins over an id of the same name. A
605 // QObject-valued property recurses into that object; a value-type property
606 // ("font.pixelSize") uses a prefix on m_object (target stays null).
607 groupObject = m_object->property(nameUtf8).value<QObject *>();
608 } else if (unit->bindingIsDeferred(
609 objectIndex, int(binding - unit->objectAt(objectIndex)->bindingTable()))) {
610 // Not a property of m_object: a deferred group binding is a generalized grouped
611 // property whose first chain part is an id ("someId.x"), targeting an external object.
612 //
613 // This is a deferred property, so it's not actually guaranteed to do what we think
614 // it does. However, if we actually find the expected object and if we can patch its
615 // property, that is it's current value is the one we'd expect from the old binding, we
616 // assume we're guessing right.
617 groupObject = idTarget(m_object, name);
618 }
619
620 if (groupObject) {
621 if (seenChildren->hasSeen(groupObject))
622 return nullptr;
623 child = std::make_unique<BindingPatchContext>(groupObject, unit,
624 binding->value.objectIndex);
625 } else {
626 child = std::make_unique<BindingPatchContext>(m_object, unit, binding->value.objectIndex,
627 name);
628 }
629 return child.get();
630}
631
633BindingPatchContext::childContext(const QString &name, QObject *object,
634 const QQmlRefPointer<QV4::ExecutableCompilationUnit> &unit,
635 int objectIndex, QDuplicateTracker<QObject *> *seenChildren)
636{
637 const size_t size = m_children.size();
638 std::unique_ptr<BindingPatchContext> &child = m_children[name];
639 if (size == m_children.size()) {
640 Q_ASSERT(!child || child->m_object == object);
641 return child.get();
642 }
643
644 if (!seenChildren || seenChildren->hasSeen(object))
645 return nullptr;
646
647 child = std::make_unique<BindingPatchContext>(object, unit, objectIndex);
648 return child.get();
649}
650
652BindingPatchContext::attachedContext(const QQmlRefPointer<QV4::ExecutableCompilationUnit> &unit,
653 const QV4::CompiledData::Binding *binding,
654 QDuplicateTracker<QObject *> *seenChildren)
655{
656 const QString name = unit->stringAt(binding->propertyNameIndex);
657
658 const size_t size = m_children.size();
659 std::unique_ptr<BindingPatchContext> &child = m_children[name];
660 if (size == m_children.size())
661 return child.get();
662
663 if (!seenChildren)
664 return nullptr;
665
666 QV4::ResolvedTypeReference *typeRef = unit->resolvedType(binding->propertyNameIndex);
667 Q_ASSERT(typeRef);
668 QQmlAttachedPropertiesFunc func =
669 typeRef->type().attachedPropertiesFunction(unit->engine->typeLoader());
670 Q_ASSERT(func);
671
672 if (QObject *attached = QQmlData::get(m_object)->attachedProperties()->value(func)) {
673 if (seenChildren->hasSeen(attached))
674 return nullptr;
675 child = std::make_unique<BindingPatchContext>(attached, unit, binding->value.objectIndex);
676 }
677 return child.get();
678}
679
680bool BindingPatchContext::applyBindingChange(const QQmlRefPointer<QV4::ExecutableCompilationUnit> &newUnit,
681 const QV4::CompiledData::Change &change)
682{
683 Q_ASSERT(change.type == QV4::CompiledData::ChangeType::BindingChanged);
684
685 if (!m_object || objectIndex < 0 || objectIndex >= unit->objectCount())
686 return false;
687
688 if (objectIndex == change.objectIndex) {
689 patchBinding(newUnit, change);
690 return true;
691 }
692
693 QDuplicateTracker<QObject *> seenChildren;
694 const QV4::CompiledData::Object *obj = unit->objectAt(objectIndex);
695 for (auto binding = obj->bindingsBegin(), end = obj->bindingsEnd(); binding != end; ++binding) {
696 BindingPatchContext *child = nullptr;
697 switch (binding->type()) {
698 case QV4::CompiledData::Binding::Type_GroupedProperty:
699 child = childContext(unit, objectIndex, binding, &seenChildren);
700 break;
701 case QV4::CompiledData::Binding::Type_AttachedProperty:
702 child = attachedContext(unit, binding, &seenChildren);
703 break;
704 default:
705 continue;
706 }
707 if (child && child->applyBindingChange(newUnit, change))
708 return true;
709 }
710
711 return false;
712}
713
715 const std::vector<QQmlRefPointer<QV4::ExecutableCompilationUnit>> &unitsToUnparent,
716 const std::vector<CompositeLevel> &internalUnits)
717{
718 QQmlData *ddata = QQmlData::get(m_object);
719
720 const auto levelFor = [&internalUnits](
721 const QQmlRefPointer<QV4::ExecutableCompilationUnit> &oldCu, int oldIndex) {
722 for (const CompositeLevel &level : internalUnits) {
723 if (level.oldCu == oldCu && level.objectIndex == oldIndex)
724 return level;
725 }
726 return CompositeLevel();
727 };
728
729 const QHash<QQmlAttachedPropertiesFunc, QObject *> *attachedProperties =
730 ddata->hasExtendedData() ? ddata->attachedProperties() : nullptr;
731 QObjectList children = m_object->children();
732
733 // Remove the children we shouldn't retire from the list. That is the ones that haven't been
734 // created by the relevant compilation units.
735 const auto newEnd = std::remove_if(children.begin(), children.end(), [&](QObject *child) {
736 const QQmlData *childDdata = QQmlData::get(child);
737 if (!childDdata)
738 return true;
739
740 const QQmlRefPointer<QV4::ExecutableCompilationUnit> &cu = childDdata->compilationUnit;
741 if (!cu)
742 return true;
743
744 if (std::find(unitsToUnparent.begin(), unitsToUnparent.end(), cu) == unitsToUnparent.end())
745 return true;
746
747 if (!attachedProperties)
748 return false;
749
750 for (QObject *attached : *attachedProperties) {
751 if (attached == child)
752 return true;
753 }
754
755 return false;
756 });
757 children.erase(newEnd, children.end());
758
759 // Remove childrens' bindings before resetBindings() runs.
760 // resetBindings() clears list/default properties via list.clear(), which calls
761 // setParentItem(nullptr) and emits parentChanged. Any QProperty binding on a
762 // child that reads 'parent' would then fire with parent == null. Clearing those
763 // bindings first prevents a flood of related warnings.
764 for (QObject *child : children)
765 clearBindingsRecursive(child);
766
767 const CompositeLevel level = levelFor(unit, objectIndex);
768 resetBindings(unit, objectIndex, level.newCu, level.objectIndex);
769
770 for (QQmlVMEMetaObject *vmeMeta = ddata->hasVMEMetaObject
771 ? static_cast<QQmlVMEMetaObject *>(QObjectPrivate::get(m_object)->metaObject)
772 : nullptr;
773 vmeMeta; vmeMeta = vmeMeta->parentVMEMetaObject()) {
774 const CompositeLevel level = levelFor(vmeMeta->compilationUnit(), vmeMeta->qmlObjectId());
775 resetBindings(vmeMeta->compilationUnit(), vmeMeta->qmlObjectId(), level.newCu,
776 level.objectIndex);
777 }
778
779 // Remove remaining composite signal handlers (all internal ones).
780 // External handlers were already detached by stashExternalState() and are invisible here.
781 // The object creator will recreate the internal handlers when it rebuilds the object.
782 while (QQmlBoundSignal *signalHandler = ddata->signalHandlers)
783 delete signalHandler;
784
785 // Objects from the old CU or composite-level CUs will be recreated by
786 // repopulateBindings. Unparent them so they don't interfere with the new objects.
787 // Attached property objects are reused across rebuilds.
788 for (QObject *child : children)
789 retireObject(child);
790}
791
792// Fully retire an old object that is being replaced by repopulateBindings.
793// Recursively removes bindings from all descendants (unlinking expressions
794// from context lists), then removes the subtree from the tree and schedules it
795// for deletion. compilationUnit is intentionally left intact. The GC needs it.
796void BindingPatchContext::retireObject(QObject *object)
797{
798 // Remove from parent (in QtQuick "visual parent" or parentItem) via the meta property system.
799 // We must not assume any particular property to be the "parent" property here. That's what
800 // we have the ParentProperty classInfo for.
801 const QMetaObject *mo = object->metaObject();
802 if (const int classInfoIndex = mo->indexOfClassInfo("ParentProperty"); classInfoIndex >= 0) {
803 const QMetaClassInfo classInfo = mo->classInfo(classInfoIndex);
804 if (const int propertyIndex = mo->indexOfProperty(classInfo.value()); propertyIndex >= 0) {
805 const QMetaProperty property = mo->property(propertyIndex);
806 if ((!property.isResettable() || !property.reset(object)) && property.isWritable())
807 property.write(object, QVariant(property.metaType()));
808 }
809 }
810
811 // Unparent from QObject hierarchy so it no longer appears in
812 // parent->children(), then schedule deletion. The destructor will
813 // cascade-delete all QObject children (the recursive descendants).
814 // Mark the whole subtree as queued for deletion right away. Descendants may themselves be
815 // pending rebuild targets (e.g. inline component instances); they must not be rebuilt anymore.
816 QQml_setParent_noEvent(object, nullptr);
817 QQmlData::markAsDeleted(object);
818 object->deleteLater();
819}
820
821void BindingPatchContext::clearBindingsRecursive(QObject *object)
822{
823 QQueue<QObject *> queue;
824 queue.enqueue(object);
825
826 while (!queue.isEmpty()) {
827 QObject *next = queue.dequeue();
828 queue.append(next->children());
829
830 QQmlData *ddata = QQmlData::get(next);
831 if (!ddata)
832 continue;
833
834 while (ddata->bindings)
835 QQmlPropertyPrivate::removeBinding(ddata->bindings);
836
837 // QProperty (BINDABLE) bindings live in the property's QPropertyBindingStorage,
838 // not in ddata->bindings. Remove them so they don't re-evaluate when
839 // setParentItem(nullptr) emits parentChanged during retireObject().
840 const QMetaObject *mo = next->metaObject();
841 for (int i = 0, n = mo->propertyCount(); i < n; ++i) {
842 if (!ddata->hasBindingBit(i))
843 continue;
844 const QMetaProperty prop = mo->property(i);
845 if (!prop.isBindable())
846 continue;
847 QUntypedBindable bindable = prop.bindable(next);
848 if (bindable.hasBinding())
849 bindable.takeBinding();
850 }
851
852 // Don't delete signal handlers right away since we might still have
853 // them in other objects "external" state. Disable them so that they
854 // don't fire anymore until this object is actually deleted.
855 for (QQmlBoundSignal *sig = ddata->signalHandlers; sig; sig = sig->m_nextSignal)
856 sig->setEnabled(false);
857 }
858}
859
860// Map the names of the properties that the new compilation unit binds on the given object
861// to their bindings. repopulateBindings() will re-assign these, so resetting them before
862// is redundant.
864 const QQmlRefPointer<QV4::ExecutableCompilationUnit> &unit, int cuIndex)
865{
866 ReboundBindings bindings;
867 if (!unit || cuIndex < 0 || cuIndex >= unit->objectCount())
868 return bindings;
869
870 const QV4::CompiledData::Object *obj = unit->objectAt(cuIndex);
871
872 for (auto binding = obj->bindingsBegin(), end = obj->bindingsEnd(); binding != end; ++binding)
873 bindings.insert(BindingPatchContext::targetPropertyName(unit, cuIndex, binding), binding);
874 return bindings;
875}
876
877// The new sub-object index for a group/attached property that the new CU rebinds with the
878// same kind of binding, or -1 if the new CU doesn't rebind it.
879static int reboundSubObjectIndex(const ReboundBindings &rebound,
880 const QString &name, QV4::CompiledData::Binding::Type type)
881{
882 const QV4::CompiledData::Binding *newBinding = rebound.value(name);
883 return (newBinding && newBinding->type() == type) ? newBinding->value.objectIndex : -1;
884}
885
886void BindingPatchContext::resetBinding(
887 int objectIndex, const QV4::CompiledData::Binding *binding, const QString &name,
888 const QQmlRefPointer<QV4::ExecutableCompilationUnit> &oldUnit,
889 const QQmlRefPointer<QV4::ExecutableCompilationUnit> &newUnit,
890 const ReboundBindings &rebound)
891{
892 QQmlProperty prop(m_object, prefix + name);
893 QQmlPropertyIndex propIdx = QQmlPropertyPrivate::propertyIndex(prop);
894 if (propIdx.coreIndex() < 0) {
895 // A generalized grouped property whose first chain part is an id (e.g. "someId.x")
896 // does not name a property of m_object; it targets an external object resolved by id.
897 // Reset the sub-bindings on that target.
898 Q_ASSERT(binding->isGroupedProperty());
899 if (BindingPatchContext *child = childContext(oldUnit, objectIndex, binding, nullptr)) {
900 child->resetBindings(
901 oldUnit, binding->value.objectIndex, newUnit,
902 reboundSubObjectIndex(rebound, name,
903 QV4::CompiledData::Binding::Type_GroupedProperty));
904 }
905 return;
906 }
907
908 const QMetaType type = prop.propertyMetaType();
909
910 const QMetaType::TypeFlags flags = type.flags();
911 if (flags.testFlag(QMetaType::IsQmlList)) {
912 // Lists need to always be cleared because they're generally additive.
913 // TODO: Handle ListPropertyAssignBehavior
914 QQmlListReference list = prop.read().value<QQmlListReference>();
915 if (list.clear())
916 return;
917 } else if (flags.testFlag(QMetaType::PointerToQObject) && binding->isGroupedProperty()) {
918 if (BindingPatchContext *child = childContext(oldUnit, objectIndex, binding, nullptr)) {
919 child->resetBindings(
920 oldUnit, binding->value.objectIndex, newUnit,
921 reboundSubObjectIndex(rebound, name,
922 QV4::CompiledData::Binding::Type_GroupedProperty));
923 }
924 return;
925 }
926
927 // Don't reset individual bindings that are re-bound anyway.
928 if (rebound.contains(name))
929 return;
930
931 if ((!prop.isResettable() || !prop.reset()) && prop.isWritable())
932 prop.write(QVariant(type));
933}
934
935void BindingPatchContext::resetBindings(
936 const QQmlRefPointer<QV4::ExecutableCompilationUnit> &oldUnit, int cuIndex,
937 const QQmlRefPointer<QV4::ExecutableCompilationUnit> &newUnit, int newCuIndex)
938{
939 const QV4::CompiledData::Object *obj = oldUnit->objectAt(cuIndex);
940
941 const ReboundBindings rebound = reboundBindings(newUnit, newCuIndex);
942
943 for (auto binding = obj->bindingsBegin(), end = obj->bindingsEnd(); binding != end; ++binding) {
944 const QString name = targetPropertyName(oldUnit, cuIndex, binding);
945 if (name.isEmpty())
946 continue;
947
948 if (binding->isAttachedProperty()) {
949 // Recurse into existing attached objects to reset their bindings.
950 // The object creator will reuse them via qmlAttachedPropertiesObject().
951 if (!QQmlData::get(m_object)->hasExtendedData())
952 continue;
953
954 if (BindingPatchContext *attached = attachedContext(oldUnit, binding, nullptr)) {
955 attached->resetBindings(
956 oldUnit, binding->value.objectIndex, newUnit,
957 reboundSubObjectIndex(rebound, name,
958 QV4::CompiledData::Binding::Type_AttachedProperty));
959 }
960
961 continue;
962 }
963
964 if (oldUnit->bindingIsCustomParser(cuIndex, int(binding - obj->bindingsBegin())))
965 continue;
966
967 // Signal handlers are disconnected centrally.
968 if (!oldUnit->bindingIsSignalHandler(cuIndex, int(binding - obj->bindingsBegin())))
969 resetBinding(cuIndex, binding, name, oldUnit, newUnit, rebound);
970 }
971}
972
973// The name of the property a binding assigns, resolving the default property for unnamed bindings.
974QString
975BindingPatchContext::targetPropertyName(const QQmlRefPointer<QV4::ExecutableCompilationUnit> &unit,
976 int objectIndex, const QV4::CompiledData::Binding *binding)
977{
978 if (binding->propertyNameIndex != 0)
979 return unit->stringAt(binding->propertyNameIndex);
980 const QQmlPropertyCache::ConstPtr cache = unit->propertyCachesPtr()->at(objectIndex);
981 return cache ? cache->defaultPropertyName() : QString();
982}
983
984void BindingPatchContext::patchBinding(
985 const QQmlRefPointer<QV4::ExecutableCompilationUnit> &newUnit,
986 const QV4::CompiledData::Change &change)
987{
988 const QV4::CompiledData::Binding *newBinding =
989 newUnit->objectAt(change.objectIndex)->bindingTable() + change.newIndex;
990 const QVariant newValue = literalBindingValue(newUnit, newBinding);
991 if (!newValue.isValid())
992 return; // Script binding: handled by function translation.
993
994 const QQmlProperty qProp(m_object,
995 prefix + targetPropertyName(newUnit, change.objectIndex, newBinding));
996 if (!qProp.isValid())
997 return;
998
999 QV4::ExecutionEngine *v4 = unit->engine;
1000 const QMetaType metaType = qProp.propertyMetaType();
1001
1002 const QV4::CompiledData::Binding *oldBinding =
1003 unit->objectAt(change.objectIndex)->bindingTable() + change.oldIndex;
1004 const QVariant expectedOld =
1005 coerceToPropertyType(v4, literalBindingValue(unit, oldBinding), metaType);
1006 if (qProp.read() == expectedOld)
1007 qProp.write(coerceToPropertyType(v4, newValue, metaType));
1008}
1009
1010} // namespace QQmlPreview
1011
1012QT_END_NAMESPACE
bool applyBindingChange(const QQmlRefPointer< QV4::ExecutableCompilationUnit > &newUnit, const QV4::CompiledData::Change &change)
void reset(const std::vector< QQmlRefPointer< QV4::ExecutableCompilationUnit > > &unitsToUnparent, const std::vector< CompositeLevel > &internalUnits)
BindingPatchContext * attachedContext(const QQmlRefPointer< QV4::ExecutableCompilationUnit > &unit, const QV4::CompiledData::Binding *binding, QDuplicateTracker< QObject * > *seenChildren)
BindingPatchContext * childContext(const QString &name, QObject *object, const QQmlRefPointer< QV4::ExecutableCompilationUnit > &unit, int objectIndex, QDuplicateTracker< QObject * > *seenChildren)
void stashExternalState(const std::vector< CompositeLevel > &internalUnits, QDuplicateTracker< QObject * > *seenChildren)
BindingPatchContext * childContext(const QQmlRefPointer< QV4::ExecutableCompilationUnit > &unit, int objectIndex, const QV4::CompiledData::Binding *binding, QDuplicateTracker< QObject * > *seenChildren)
static QVariant literalBindingValue(const QQmlRefPointer< QV4::ExecutableCompilationUnit > &unit, const QV4::CompiledData::Binding *binding)
static bool isExternalFunction(const QV4::Function *f, const std::vector< CompositeLevel > &internalUnits, QObject *target)
static QVariant coerceToPropertyType(QV4::ExecutionEngine *v4, const QVariant &value, QMetaType propertyType)
static ReboundBindings reboundBindings(const QQmlRefPointer< QV4::ExecutableCompilationUnit > &unit, int cuIndex)
static bool functionBelongsToObject(const QV4::Function *f, const QQmlRefPointer< QV4::ExecutableCompilationUnit > &cu, int objectIndex)
static QObject * propertyToPropertySource(const QQmlAnyBinding &binding)
static int reboundSubObjectIndex(const ReboundBindings &rebound, const QString &name, QV4::CompiledData::Binding::Type type)
static bool isExternalUnitBinding(const QQmlRefPointer< QV4::ExecutableCompilationUnit > &cu, const std::vector< CompositeLevel > &internalUnits, QObject *target)
static QObject * idTarget(QObject *object, const QString &name)
static bool isExternalBinding(const QQmlAnyBinding &binding, const std::vector< CompositeLevel > &internalUnits, QObject *target)
static bool rebuildReachesUnitViaContext(const QQmlRefPointer< QV4::ExecutableCompilationUnit > &cu, const std::vector< CompositeLevel > &internalUnits, QObject *target)
Combined button and popup list for selecting options.