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
qqmlengine_p.h
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
5#ifndef QQMLENGINE_P_H
6#define QQMLENGINE_P_H
7
8//
9// W A R N I N G
10// -------------
11//
12// This file is not part of the Qt API. It exists purely as an
13// implementation detail. This header file may change from version to
14// version without notice, or even be removed.
15//
16// We mean it.
17//
18
19#include "qqmlengine.h"
20
21#include <private/qfieldlist_p.h>
22#include <private/qintrusivelist_p.h>
23#include <private/qjsengine_p.h>
24#include <private/qjsvalue_p.h>
25#include <private/qqmlcontextdata_p.h>
26#include <private/qqmldirparser_p.h>
27#include <private/qqmlimport_p.h>
28#include <private/qqmlmetatype_p.h>
29#include <private/qqmlnotifierendpoint_p.h>
30#include <private/qqmlproperty_p.h>
31#include <private/qqmltypeloader_p.h>
32#include <private/qqmlvaluetype_p.h>
33#include <private/qrecyclepool_p.h>
34#include <private/qv4engine_p.h>
35
36#include <QtQml/qqml.h>
37#include <QtQml/qqmlcontext.h>
38
39#include <QtCore/qlist.h>
40#include <QtCore/qmetaobject.h>
41#include <QtCore/qmutex.h>
42#include <QtCore/qpointer.h>
43#include <QtCore/qproperty.h>
44#include <QtCore/qstack.h>
45#include <QtCore/qstring.h>
46#include <QtCore/qthread.h>
47
48#include <atomic>
49
50QT_BEGIN_NAMESPACE
51
52class QNetworkAccessManager;
54class QQmlIncubator;
55class QQmlMetaObject;
56class QQmlNetworkAccessManagerFactory;
57class QQmlObjectCreator;
58class QQmlProfiler;
60
61// This needs to be declared here so that the pool for it can live in QQmlEnginePrivate.
62// The inline method definitions are in qqmljavascriptexpression_p.h
64{
65public:
66 inline QQmlJavaScriptExpressionGuard(QQmlJavaScriptExpression *);
67
68 static inline QQmlJavaScriptExpressionGuard *New(QQmlJavaScriptExpression *e,
69 QQmlEngine *engine);
70 inline void Delete();
71
74};
75
78
79 QPropertyChangeTrigger(QQmlJavaScriptExpression *expression)
80 : QPropertyObserver(&QPropertyChangeTrigger::trigger)
81 , m_expression(expression)
82 {
83 }
84
88 static void trigger(QPropertyObserver *, QUntypedPropertyData *);
89
90 QMetaProperty property() const;
91};
92
94 TriggerList(QQmlJavaScriptExpression *expression)
95 : QPropertyChangeTrigger(expression)
96 {}
97 TriggerList *next = nullptr;
98};
99
100class Q_QML_EXPORT QQmlEnginePrivate : public QJSEnginePrivate
101{
102 Q_DECLARE_PUBLIC(QQmlEngine)
103public:
104 ~QQmlEnginePrivate() override;
105
106 void init();
107 // No mutex protecting baseModulesUninitialized, because use outside QQmlEngine
108 // is just qmlClearTypeRegistrations (which can't be called while an engine exists)
109 static bool baseModulesUninitialized;
110
111 QQmlPropertyCapture *propertyCapture = nullptr;
112
113 QRecyclePool<QQmlJavaScriptExpressionGuard> jsExpressionGuardPool;
114 QRecyclePool<TriggerList> qPropertyTriggerPool;
116 QQmlContext *rootContext = nullptr;
117 Q_OBJECT_BINDABLE_PROPERTY(QQmlEnginePrivate, QString, translationLanguage);
118
119#if !QT_CONFIG(qml_debug)
120 static const quintptr profiler = 0;
121#else
122 QQmlProfiler *profiler = nullptr;
123#endif
124
125 bool outputWarningsToMsgLog = true;
126
127 // TODO: Remove this when we can.
128 bool preferContextPropertiesOverJavaScriptGlobals = false;
129
130 // Bindings that have had errors during startup
131 QQmlDelayedError *erroredBindings = nullptr;
132 int inProgressCreations = 0;
133
134#if QT_CONFIG(qml_worker_script)
135 QThread *workerScriptEngine = nullptr;
136#endif
137
138 QUrl baseUrl;
139
140 QQmlObjectCreator *activeObjectCreator = nullptr;
141
142 mutable QRecursiveMutex imageProviderMutex;
143 QHash<QString,QSharedPointer<QQmlImageProviderBase> > imageProviders;
144 QSharedPointer<QQmlImageProviderBase> imageProvider(const QString &providerId) const;
145
146 int scarceResourcesRefCount = 0;
147 void referenceScarceResources();
148 void dereferenceScarceResources();
149
150 QString offlineStoragePath;
151
152 // Unfortunate workaround to avoid a circular dependency between
153 // qqmlengine_p.h and qqmlincubator_p.h
154 struct Incubator {
155 QIntrusiveListNode next;
156 };
157 QIntrusiveList<Incubator, &Incubator::next> incubatorList;
158 unsigned int incubatorCount = 0;
159 QQmlIncubationController *incubationController = nullptr;
160 void incubate(QQmlIncubator &, const QQmlRefPointer<QQmlContextData> &);
161
162 // These methods may be called from any thread
163 QString offlineStorageDatabaseDirectory() const;
164
165 template <typename T>
166 T singletonInstance(const QQmlType &type);
167
168 void sendQuit();
169 void sendExit(int retCode = 0);
170 void warning(const QQmlError &);
171 void warning(const QList<QQmlError> &);
172 static void warning(QQmlEngine *, const QQmlError &);
173 static void warning(QQmlEngine *, const QList<QQmlError> &);
174 static void warning(QQmlEnginePrivate *, const QQmlError &);
175 static void warning(QQmlEnginePrivate *, const QList<QQmlError> &);
176
177 inline static QQmlEnginePrivate *get(QQmlEngine *e);
178 inline static const QQmlEnginePrivate *get(const QQmlEngine *e);
179 inline static QQmlEngine *get(QQmlEnginePrivate *p);
180 inline static const QQmlEngine *get(const QQmlEnginePrivate *p);
181 inline static QQmlEnginePrivate *get(QV4::ExecutionEngine *e);
182
183 inline static QQmlEnginePrivate *get(QQmlContext *c);
184 inline static QQmlEnginePrivate *get(const QQmlRefPointer<QQmlContextData> &c);
185
186 static QList<QQmlError> qmlErrorFromDiagnostics(const QString &fileName, const QList<QQmlJS::DiagnosticMessage> &diagnosticMessages);
187
188 static bool designerMode();
189 static void activateDesignerMode();
190
191 static std::atomic<bool> qml_debugging_enabled;
192
193 QQmlGadgetPtrWrapper *valueTypeInstance(QMetaType type)
194 {
195 int typeIndex = type.id();
196 auto it = cachedValueTypeInstances.constFind(typeIndex);
197 if (it != cachedValueTypeInstances.cend())
198 return *it;
199
200 if (QQmlValueType *valueType = QQmlMetaType::valueType(type)) {
201 QQmlGadgetPtrWrapper *instance = new QQmlGadgetPtrWrapper(valueType);
202 cachedValueTypeInstances.insert(typeIndex, instance);
203 return instance;
204 }
205
206 return nullptr;
207 }
208
209 void executeRuntimeFunction(const QUrl &url, qsizetype functionIndex, QObject *thisObject,
210 int argc = 0, void **args = nullptr, QMetaType *types = nullptr);
211 void executeRuntimeFunction(const QV4::ExecutableCompilationUnit *unit, qsizetype functionIndex,
212 QObject *thisObject, int argc = 0, void **args = nullptr,
213 QMetaType *types = nullptr);
214 QV4::ExecutableCompilationUnit *compilationUnitFromUrl(const QUrl &url);
215
216 QQmlRefPointer<QQmlContextData>
217 createBareContext(const QQmlRefPointer<QV4::ExecutableCompilationUnit> &unit,
218 const QQmlRefPointer<QQmlContextData> &parentContext, int subComponentIndex)
219 {
220 Q_ASSERT(unit);
221
222 QQmlRefPointer<QQmlContextData> context = QQmlContextData::createRefCounted(parentContext);
223 context->setInternal(true);
224 context->setImports(unit->typeNameCache());
225 context->initFromTypeCompilationUnit(unit, subComponentIndex);
226 return context;
227 }
228
229 QQmlRefPointer<QQmlContextData>
230 createComponentRootContext(const QQmlRefPointer<QV4::ExecutableCompilationUnit> &unit,
231 const QQmlRefPointer<QQmlContextData> &parentContex,
232 int subComponentIndex);
233
234 static void setInternalContext(QObject *This, const QQmlRefPointer<QQmlContextData> &context,
235 QQmlContextData::QmlObjectKind kind)
236 {
237 Q_ASSERT(This);
238 QQmlData *ddata = QQmlData::get(This, /*create*/ true);
239 // NB: copied from QQmlObjectCreator::createInstance()
240 //
241 // the if-statement logic to determine the kind is:
242 // if (static_cast<quint32>(index) == 0 || ddata->rootObjectInCreation || isInlineComponent)
243 // then QQmlContextData::DocumentRoot. here, we pass this through qmltc
244 context->installContext(ddata, kind);
245 Q_ASSERT(qmlEngine(This));
246 }
247
248private:
249 class SingletonInstances : private QHash<QQmlType::SingletonInstanceInfo::ConstPtr, QJSValue>
250 {
251 public:
252 void convertAndInsert(
253 QV4::ExecutionEngine *engine, const QQmlType::SingletonInstanceInfo::ConstPtr &type,
254 QJSValue *value)
255 {
256 QJSValuePrivate::manageStringOnV4Heap(engine, value);
257 insert(type, *value);
258 }
259
260 // Returns an existing instance; used in singletonInstance to avoid a temporary
261 // QJSValue construction
262 QObject *getExistingQObject(const QQmlType::SingletonInstanceInfo::ConstPtr &type) const
263 {
264 const auto it = constFind(type);
265 return it == constEnd() ? nullptr : it->toQObject();
266 }
267
268 void clear()
269 {
270 const auto canDelete = [](QObject *instance, const auto &siinfo) -> bool {
271 if (!instance)
272 return false;
273
274 if (!siinfo->url.isEmpty())
275 return true;
276
277 const auto *ddata = QQmlData::get(instance, false);
278 return !(ddata && ddata->indestructible && ddata->explicitIndestructibleSet);
279 };
280
281 for (auto it = constBegin(), end = constEnd(); it != end; ++it) {
282 auto *instance = it.value().toQObject();
283 if (canDelete(instance, it.key()))
284 QQmlData::markAsDeleted(instance);
285 }
286
287 for (auto it = constBegin(), end = constEnd(); it != end; ++it) {
288 QObject *instance = it.value().toQObject();
289
290 if (canDelete(instance, it.key()))
291 delete instance;
292 }
293
294 QHash<QQmlType::SingletonInstanceInfo::ConstPtr, QJSValue>::clear();
295 }
296
297 using QHash<QQmlType::SingletonInstanceInfo::ConstPtr, QJSValue>::value;
298 using QHash<QQmlType::SingletonInstanceInfo::ConstPtr, QJSValue>::take;
299 };
300
301 SingletonInstances singletonInstances;
302 QHash<int, QQmlGadgetPtrWrapper *> cachedValueTypeInstances;
303
304 static bool s_designerMode;
305
306 void cleanupScarceResources();
307};
308
309/*
310 This function should be called prior to evaluation of any js expression,
311 so that scarce resources are not freed prematurely (eg, if there is a
312 nested javascript expression).
313 */
314inline void QQmlEnginePrivate::referenceScarceResources()
315{
316 scarceResourcesRefCount += 1;
317}
318
319/*
320 This function should be called after evaluation of the js expression is
321 complete, and so the scarce resources may be freed safely.
322 */
323inline void QQmlEnginePrivate::dereferenceScarceResources()
324{
325 Q_ASSERT(scarceResourcesRefCount > 0);
326 scarceResourcesRefCount -= 1;
327
328 // if the refcount is zero, then evaluation of the "top level"
329 // expression must have completed. We can safely release the
330 // scarce resources.
331 if (Q_LIKELY(scarceResourcesRefCount == 0)) {
332 if (Q_UNLIKELY(!v4Engine->scarceResources.isEmpty())) {
333 cleanupScarceResources();
334 }
335 }
336}
337
338QQmlEnginePrivate *QQmlEnginePrivate::get(QQmlEngine *e)
339{
340 Q_ASSERT(e);
341
342 return e->d_func();
343}
344
345const QQmlEnginePrivate *QQmlEnginePrivate::get(const QQmlEngine *e)
346{
347 Q_ASSERT(e);
348
349 return e ? e->d_func() : nullptr;
350}
351
352template<typename Context>
353QQmlEnginePrivate *contextEngine(const Context &context)
354{
355 if (!context)
356 return nullptr;
357 if (QQmlEngine *engine = context->engine())
358 return QQmlEnginePrivate::get(engine);
359 return nullptr;
360}
361
362QQmlEnginePrivate *QQmlEnginePrivate::get(QQmlContext *c)
363{
364 return contextEngine(c);
365}
366
367QQmlEnginePrivate *QQmlEnginePrivate::get(const QQmlRefPointer<QQmlContextData> &c)
368{
369 return contextEngine(c);
370}
371
372QQmlEngine *QQmlEnginePrivate::get(QQmlEnginePrivate *p)
373{
374 Q_ASSERT(p);
375
376 return p->q_func();
377}
378
379QQmlEnginePrivate *QQmlEnginePrivate::get(QV4::ExecutionEngine *e)
380{
381 QQmlEngine *qmlEngine = e->qmlEngine();
382 if (!qmlEngine)
383 return nullptr;
384 return get(qmlEngine);
385}
386
387template<>
388Q_QML_EXPORT QJSValue QQmlEnginePrivate::singletonInstance<QJSValue>(const QQmlType &type);
389
390template<typename T>
391T QQmlEnginePrivate::singletonInstance(const QQmlType &type) {
392 // Hot path of every singleton property lookup: avoid QJSValue construction once created.
393 if (QObject *instance = singletonInstances.getExistingQObject(type.singletonInstanceInfo()))
394 return qobject_cast<T>(instance);
395 return qobject_cast<T>(singletonInstance<QJSValue>(type).toQObject());
396}
397
398class QQmlComponentPrivate;
399struct LoadHelper final : QQmlTypeLoader::Blob
400{
401public:
406
408 QQmlTypeLoader *loader, QAnyStringView uri, QAnyStringView typeName,
409 QQmlTypeLoader::Mode mode);
410
411 QQmlType type() const { return m_type; }
412 QQmlTypeLoader::Mode mode() const { return m_mode; }
413 ResolveTypeResult resolveTypeResult() const { return m_resolveTypeResult; }
414
415 void registerCallback(QQmlComponentPrivate *callback);
416 void unregisterCallback(QQmlComponentPrivate *callback);
417
418protected:
419 void done() final;
420 void completed() final;
421 void dataReceived(const SourceCodeData &) final;
422 void initializeFromCachedUnit(const QQmlPrivate::CachedQmlUnit *) final { Q_UNREACHABLE(); }
423
424private:
425 bool couldFindModule() const;
426 QString m_uri;
427 QString m_typeName;
428 QQmlType m_type;
429 QQmlComponentPrivate *m_callback = nullptr;
430 QQmlTypeLoader::Mode m_mode = QQmlTypeLoader::Synchronous;
432};
433
434
435QT_END_NAMESPACE
436
437#endif // QQMLENGINE_P_H
The QJSValue class acts as a container for Qt/JavaScript data types.
Definition qjsvalue.h:32
QQmlApplicationEngine provides a convenient way to load an application from a single QML file.
friend class QQmlEnginePrivate
QQmlJavaScriptExpressionGuard(QQmlJavaScriptExpression *)
QQmlJavaScriptExpressionGuard * next
static QQmlJavaScriptExpressionGuard * New(QQmlJavaScriptExpression *e, QQmlEngine *engine)
QQmlJavaScriptExpression * expression
Combined button and popup list for selecting options.
static QUrl urlFromFilePath(const QString &filePath)
static QString translationsDirectoryFromLocalUrl(const QUrl &url)
QQmlEnginePrivate * contextEngine(const Context &context)
LoadHelper(QQmlTypeLoader *loader, QAnyStringView uri, QAnyStringView typeName, QQmlTypeLoader::Mode mode)
void dataReceived(const SourceCodeData &) final
Invoked when data for the blob is received.
QQmlType type() const
void completed() final
Invoked on the main thread sometime after done() was called on the load thread.
void registerCallback(QQmlComponentPrivate *callback)
void unregisterCallback(QQmlComponentPrivate *callback)
ResolveTypeResult resolveTypeResult() const
QQmlTypeLoader::Mode mode() const
void initializeFromCachedUnit(const QQmlPrivate::CachedQmlUnit *) final
void done() final
Invoked once data has either been received or a network error occurred, and all dependencies are comp...
static void trigger(QPropertyObserver *, QUntypedPropertyData *)
TriggerList * next
TriggerList(QQmlJavaScriptExpression *expression)