aboutsummaryrefslogtreecommitdiffstats
path: root/src/qml/qml/qqmlobjectcreator_p.h
blob: 8b1c251e2b26424190862a3ebd0c80c38710e76f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QQMLOBJECTCREATOR_P_H
#define QQMLOBJECTCREATOR_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

#include <private/qqmlimport_p.h>
#include <private/qqmltypenamecache_p.h>
#include <private/qv4compileddata_p.h>
#include <private/qfinitestack_p.h>
#include <private/qrecursionwatcher_p.h>
#include <private/qqmlprofiler_p.h>
#include <private/qv4qmlcontext_p.h>
#include <private/qqmlguardedcontextdata_p.h>
#include <private/qqmlfinalizer_p.h>
#include <private/qqmlvmemetaobject_p.h>

#include <qpointer.h>

QT_BEGIN_NAMESPACE

class QQmlAbstractBinding;
class QQmlInstantiationInterrupt;
class QQmlIncubatorPrivate;

struct AliasToRequiredInfo {
    QString propertyName;
    QUrl fileUrl;
};

/*!
\internal
This struct contains information solely used for displaying error messages
\variable aliasesToRequired allows us to give the user a way to know which (aliasing) properties
can be set to set the required property
\sa QQmlComponentPrivate::unsetRequiredPropertyToQQmlError
*/
struct RequiredPropertyInfo
{
    QString propertyName;
    QUrl fileUrl;
    QV4::CompiledData::Location location;
    QVector<AliasToRequiredInfo> aliasesToRequired;
};

struct RequiredPropertyKey
{
    RequiredPropertyKey() = default;
    RequiredPropertyKey(const QObject *object, const QQmlPropertyData *data)
        : object(object)
        , data(data)
    {}

    const QObject *object = nullptr;
    const QQmlPropertyData *data = nullptr;

private:
    friend size_t qHash(const RequiredPropertyKey &key, size_t seed = 0)
    {
        return qHashMulti(seed, key.object, key.data);
    }

    friend bool operator==(const RequiredPropertyKey &a, const RequiredPropertyKey &b)
    {
        return a.object == b.object && a.data == b.data;
    }
};

class RequiredProperties : public QHash<RequiredPropertyKey, RequiredPropertyInfo> {};

struct DeferredQPropertyBinding {
    QObject *target = nullptr;
    int properyIndex = -1;
    QUntypedPropertyBinding binding;
};

class ObjectInCreationGCAnchorList {
public:
    // this is a non owning view, rule of zero applies
    ObjectInCreationGCAnchorList() = default;
    ObjectInCreationGCAnchorList(const QV4::Scope &scope, int totalObjectCount)
    {
        allJavaScriptObjects = scope.alloc(totalObjectCount);
    }
    void trackObject(QV4::ExecutionEngine *engine, QObject *instance);
    bool canTrack() const { return allJavaScriptObjects; }
private:
    QV4::Value *allJavaScriptObjects = nullptr; // pointer to vector on JS stack to reference JS wrappers during creation phase.
};

struct QQmlObjectCreatorSharedState final : QQmlRefCounted<QQmlObjectCreatorSharedState>
{
    QQmlRefPointer<QQmlContextData> rootContext;
    QQmlRefPointer<QQmlContextData> creationContext;
    QFiniteStack<QQmlAbstractBinding::Ptr> allCreatedBindings;
    QFiniteStack<QQmlParserStatus*> allParserStatusCallbacks;
    QFiniteStack<QQmlGuard<QObject> > allCreatedObjects;
    ObjectInCreationGCAnchorList allJavaScriptObjects; // pointer to vector on JS stack to reference JS wrappers during creation phase.
    QQmlComponentAttached *componentAttached;
    QList<QQmlFinalizerHook *> finalizeHooks;
    QQmlVmeProfiler profiler;
    QRecursionNode recursionNode;
    RequiredProperties requiredProperties;
    QList<DeferredQPropertyBinding> allQPropertyBindings;
    bool hadTopLevelRequiredProperties;
};

class Q_QML_EXPORT QQmlObjectCreator
{
    Q_DECLARE_TR_FUNCTIONS(QQmlObjectCreator)
public:
    QQmlObjectCreator(QQmlRefPointer<QQmlContextData> parentContext,
                      const QQmlRefPointer<QV4::ExecutableCompilationUnit> &compilationUnit,
                      const QQmlRefPointer<QQmlContextData> &creationContext,
                      QQmlIncubatorPrivate  *incubator = nullptr);
    ~QQmlObjectCreator();

    enum CreationFlags { NormalObject = 1, InlineComponent = 2 };
    QObject *create(int subComponentIndex = -1, QObject *parent = nullptr,
                    QQmlInstantiationInterrupt *interrupt = nullptr, int flags = NormalObject);

    bool populateDeferredProperties(QObject *instance, const QQmlData::DeferredData *deferredData);

    void beginPopulateDeferred(const QQmlRefPointer<QQmlContextData> &context);
    void populateDeferredBinding(const QQmlProperty &qmlProperty, int deferredIndex,
                                 const QV4::CompiledData::Binding *binding);
    void populateDeferredInstance(QObject *outerObject, int deferredIndex,
                                  int index, QObject *instance, QObject *bindingTarget,
                                  const QQmlPropertyData *valueTypeProperty,
                                  const QV4::CompiledData::Binding *binding = nullptr);
    void finalizePopulateDeferred();

    bool finalize(QQmlInstantiationInterrupt &interrupt);
    void clear();

    QQmlRefPointer<QQmlContextData> rootContext() const { return sharedState->rootContext; }
    QQmlComponentAttached **componentAttachment() { return &sharedState->componentAttached; }

    QList<QQmlError> errors;

    QQmlRefPointer<QQmlContextData> parentContextData() const
    {
        return parentContext.contextData();
    }
    QFiniteStack<QQmlGuard<QObject> > &allCreatedObjects() { return sharedState->allCreatedObjects; }

    RequiredProperties *requiredProperties() {return &sharedState->requiredProperties;}
    bool componentHadTopLevelRequiredProperties() const {return sharedState->hadTopLevelRequiredProperties;}

    static QQmlComponent *createComponent(QQmlEngine *engine,
                                          QV4::ExecutableCompilationUnit *compilationUnit,
                                          int index, QObject *parent,
                                          const QQmlRefPointer<QQmlContextData> &context);

    void removePendingBinding(QObject *target, int propertyIndex)
    {
        QList<DeferredQPropertyBinding> &pendingBindings = sharedState.data()->allQPropertyBindings;
        pendingBindings.removeIf([&](const DeferredQPropertyBinding &deferred) {
            return deferred.properyIndex == propertyIndex && deferred.target == target;
        });
    }

private:
    QQmlObjectCreator(QQmlRefPointer<QQmlContextData> contextData,
                      const QQmlRefPointer<QV4::ExecutableCompilationUnit> &compilationUnit,
                      QQmlObjectCreatorSharedState *inheritedSharedState,
                      bool isContextObject);

    void init(QQmlRefPointer<QQmlContextData> parentContext);

    QObject *createInstance(int index, QObject *parent = nullptr, bool isContextObject = false);

    bool populateInstance(int index, QObject *instance, QObject *bindingTarget,
                          const QQmlPropertyData *valueTypeProperty,
                          const QV4::CompiledData::Binding *binding = nullptr);

    // If qmlProperty and binding are null, populate all properties, otherwise only the given one.
    void populateDeferred(QObject *instance, int deferredIndex);
    void populateDeferred(QObject *instance, int deferredIndex,
                          const QQmlPropertyPrivate *qmlProperty,
                          const QV4::CompiledData::Binding *binding);

    enum BindingMode {
        ApplyNone      = 0x0,
        ApplyImmediate = 0x1,
        ApplyDeferred  = 0x2,
        ApplyAll       = ApplyImmediate | ApplyDeferred,
    };
    Q_DECLARE_FLAGS(BindingSetupFlags, BindingMode);

    void setupBindings(BindingSetupFlags mode = BindingMode::ApplyImmediate);
    bool setPropertyBinding(const QQmlPropertyData *property, const QV4::CompiledData::Binding *binding);
    void setPropertyValue(const QQmlPropertyData *property, const QV4::CompiledData::Binding *binding);
    void setupFunctions();

    QString stringAt(int idx) const { return compilationUnit->stringAt(idx); }
    void recordError(const QV4::CompiledData::Location &location, const QString &description);

    void registerObjectWithContextById(const QV4::CompiledData::Object *object, QObject *instance) const;

    inline QV4::QmlContext *currentQmlContext();
    QV4::ResolvedTypeReference *resolvedType(int id) const
    {
        return compilationUnit->resolvedType(id);
    }

    enum Phase {
        Startup,
        CreatingObjects,
        CreatingObjectsPhase2,
        ObjectsCreated,
        Finalizing,
        Done
    } phase;

    QQmlEngine *engine;
    QV4::ExecutionEngine *v4;
    QQmlRefPointer<QV4::ExecutableCompilationUnit> compilationUnit;
    const QV4::CompiledData::Unit *qmlUnit;
    QQmlGuardedContextData parentContext;
    QQmlRefPointer<QQmlContextData> context;
    const QQmlPropertyCacheVector *propertyCaches;
    QQmlRefPointer<QQmlObjectCreatorSharedState> sharedState;
    bool topLevelCreator;
    bool isContextObject;
    QQmlIncubatorPrivate *incubator;

    QObject *_qobject;
    QObject *_scopeObject;
    QObject *_bindingTarget;

    const QQmlPropertyData *_valueTypeProperty; // belongs to _qobjectForBindings's property cache
    int _compiledObjectIndex;
    const QV4::CompiledData::Object *_compiledObject;
    QQmlData *_ddata;
    QQmlPropertyCache::ConstPtr _propertyCache;
    QQmlVMEMetaObject *_vmeMetaObject;
    QQmlListProperty<void> _currentList;
    QV4::QmlContext *_qmlContext;

    friend struct QQmlObjectCreatorRecursionWatcher;

    typedef std::function<bool(QQmlObjectCreatorSharedState *sharedState)> PendingAliasBinding;
    std::vector<PendingAliasBinding> pendingAliasBindings;

    template<typename Functor>
    void doPopulateDeferred(QObject *instance, int deferredIndex, Functor f)
    {
        QQmlData *declarativeData = QQmlData::get(instance);

        // We're in the process of creating the object. We sure hope it's still alive.
        Q_ASSERT(declarativeData && declarativeData->propertyCache);

        QObject *bindingTarget = instance;

        QQmlPropertyCache::ConstPtr cache = declarativeData->propertyCache;
        QQmlVMEMetaObject *vmeMetaObject = QQmlVMEMetaObject::get(instance);

        QObject *scopeObject = instance;
        qt_ptr_swap(_scopeObject, scopeObject);

        QV4::Scope valueScope(v4);
        QScopedValueRollback<ObjectInCreationGCAnchorList> jsObjectGuard(
                sharedState->allJavaScriptObjects,
                ObjectInCreationGCAnchorList(valueScope, compilationUnit->totalObjectCount()));

        Q_ASSERT(topLevelCreator);
        QV4::QmlContext *qmlContext = static_cast<QV4::QmlContext *>(valueScope.alloc());

        qt_ptr_swap(_qmlContext, qmlContext);

        _propertyCache.swap(cache);
        qt_ptr_swap(_qobject, instance);

        int objectIndex = deferredIndex;
        std::swap(_compiledObjectIndex, objectIndex);

        const QV4::CompiledData::Object *obj = compilationUnit->objectAt(_compiledObjectIndex);
        qt_ptr_swap(_compiledObject, obj);
        qt_ptr_swap(_ddata, declarativeData);
        qt_ptr_swap(_bindingTarget, bindingTarget);
        qt_ptr_swap(_vmeMetaObject, vmeMetaObject);

        f();

        qt_ptr_swap(_vmeMetaObject, vmeMetaObject);
        qt_ptr_swap(_bindingTarget, bindingTarget);
        qt_ptr_swap(_ddata, declarativeData);
        qt_ptr_swap(_compiledObject, obj);
        std::swap(_compiledObjectIndex, objectIndex);
        qt_ptr_swap(_qobject, instance);
        _propertyCache.swap(cache);

        qt_ptr_swap(_qmlContext, qmlContext);
        qt_ptr_swap(_scopeObject, scopeObject);
    }
};

struct QQmlObjectCreatorRecursionWatcher
{
    QQmlObjectCreatorRecursionWatcher(QQmlObjectCreator *creator);

    bool hasRecursed() const { return watcher.hasRecursed(); }

private:
    QQmlRefPointer<QQmlObjectCreatorSharedState> sharedState;
    QRecursionWatcher<QQmlObjectCreatorSharedState, &QQmlObjectCreatorSharedState::recursionNode> watcher;
};

QV4::QmlContext *QQmlObjectCreator::currentQmlContext()
{
    if (!_qmlContext->isManaged())
        _qmlContext->setM(QV4::QmlContext::create(v4->rootContext(), context, _scopeObject));

    return _qmlContext;
}

QT_END_NAMESPACE

#endif // QQMLOBJECTCREATOR_P_H