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
qqmlexpression.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 "qqmlengine_p.h"
10#include "qqmlbinding_p.h"
11#include <private/qqmlsourcecoordinate_p.h>
12#include <private/qv4qmlcontext_p.h>
13
14#include <QtCore/qdebug.h>
15
16QT_BEGIN_NAMESPACE
17
18QQmlExpressionPrivate::QQmlExpressionPrivate()
19: QQmlJavaScriptExpression(),
20 expressionFunctionValid(true),
21 line(0), column(0)
22{
23}
24
28
29void QQmlExpressionPrivate::init(const QQmlRefPointer<QQmlContextData> &ctxt, const QString &expr,
30 QObject *me)
31{
32 expression = expr;
33
34 QQmlJavaScriptExpression::setContext(ctxt);
35 setScopeObject(me);
37}
38
39void QQmlExpressionPrivate::init(const QQmlRefPointer<QQmlContextData> &ctxt,
40 QV4::Function *runtimeFunction, QObject *me)
41{
43 QV4::ExecutionEngine *engine = ctxt->engine()->handle();
44 QV4::Scope scope(engine);
45 QV4::Scoped<QV4::QmlContext> qmlContext(scope, QV4::QmlContext::create(engine->rootContext(), ctxt, me));
46 setupFunction(qmlContext, runtimeFunction);
47
48 QQmlJavaScriptExpression::setContext(ctxt);
49 setScopeObject(me);
50}
51
52/*!
53 \class QQmlExpression
54 \since 5.0
55 \inmodule QtQml
56 \brief The QQmlExpression class evaluates JavaScript in a QML context.
57
58 For example, given a file \c main.qml like this:
59
60 \qml
61 import QtQuick 2.0
62
63 Item {
64 width: 200; height: 200
65 }
66 \endqml
67
68 The following code evaluates a JavaScript expression in the context of the
69 above QML:
70
71 \code
72 QQmlEngine *engine = new QQmlEngine;
73 QQmlComponent component(engine, QUrl::fromLocalFile("main.qml"));
74
75 QObject *myObject = component.create();
76 QQmlExpression *expr = new QQmlExpression(engine->rootContext(), myObject, "width * 2");
77 int result = expr->evaluate().toInt(); // result = 400
78 \endcode
79*/
80
81/*!
82 Create an invalid QQmlExpression.
83
84 As the expression will not have an associated QQmlContext, this will be a
85 null expression object and its value will always be an invalid QVariant.
86 */
87QQmlExpression::QQmlExpression()
88: QObject(*new QQmlExpressionPrivate, nullptr)
89{
90}
91
92/*!
93 Create a QQmlExpression object that is a child of \a parent.
94
95 The \a script provides the expression to be evaluated, the context to evaluate it in,
96 and the scope object to evaluate it with. If provided, \a ctxt and \a scope will override
97 the context and scope object provided by \a script.
98
99 \note The resulting expression can always be evaluated, but its source code,
100 as returned by expression(), may not be available. If the QML module that
101 produced \a script was compiled ahead of time, the source code of
102 non-literal script strings can be discarded. See expression() for details.
103
104 \sa QQmlScriptString
105*/
106QQmlExpression::QQmlExpression(const QQmlScriptString &script, QQmlContext *ctxt, QObject *scope, QObject *parent)
107: QObject(*new QQmlExpressionPrivate, parent)
108{
109 Q_D(QQmlExpression);
110 if (ctxt && !ctxt->isValid())
111 return;
112
113 const QQmlScriptStringPrivate *scriptPrivate = script.d.data();
114 if (!scriptPrivate) {
115 // A null QQmlScriptStringPrivate is an empty expression without context.
116 // We may still want the explicitly passed context, though.
117 if (ctxt)
118 d->init(QQmlContextData::get(ctxt), QString(), scope);
119 return;
120 }
121
122 if (!ctxt && (!scriptPrivate->context || !scriptPrivate->context->isValid()))
123 return;
124
125 QQmlRefPointer<QQmlContextData> evalCtxtData
126 = QQmlContextData::get(ctxt ? ctxt : scriptPrivate->context);
127 QObject *scopeObject = scope ? scope : scriptPrivate->scope;
128 QV4::Function *runtimeFunction = nullptr;
129
130 if (scriptPrivate->context) {
131 QQmlRefPointer<QQmlContextData> ctxtdata = QQmlContextData::get(scriptPrivate->context);
132 QQmlEnginePrivate *engine = QQmlEnginePrivate::get(scriptPrivate->context->engine());
133 if (engine && ctxtdata && ctxtdata->typeCompilationUnit()) {
134 d->url = ctxtdata->urlString();
135 d->line = scriptPrivate->lineNumber;
136 d->column = scriptPrivate->columnNumber;
137
138 if (scriptPrivate->bindingId != QQmlBinding::Invalid)
139 runtimeFunction = ctxtdata->typeCompilationUnit()->runtimeFunctions.at(scriptPrivate->bindingId);
140 }
141 }
142
143 if (runtimeFunction) {
144 d->expression = scriptPrivate->script;
145 d->init(evalCtxtData, runtimeFunction, scopeObject);
146 } else
147 d->init(evalCtxtData, scriptPrivate->script, scopeObject);
148}
149
150/*!
151 Create a QQmlExpression object that is a child of \a parent.
152
153 The \a expression JavaScript will be executed in the \a ctxt QQmlContext.
154 If specified, the \a scope object's properties will also be in scope during
155 the expression's execution.
156*/
157QQmlExpression::QQmlExpression(QQmlContext *ctxt, QObject *scope, const QString &expression,
158 QObject *parent)
159: QObject(*new QQmlExpressionPrivate, parent)
160{
161 Q_D(QQmlExpression);
162 d->init(QQmlContextData::get(ctxt), expression, scope);
163}
164
165/*!
166 \internal
167*/
168QQmlExpression::QQmlExpression(QQmlExpressionPrivate &dd, QObject *parent) : QObject(dd, parent)
169{
170// Q_D(QQmlExpression);
171// d->init(QQmlContextData::get(ctxt), expression, scope);
172}
173
174/*!
175 Destroy the QQmlExpression instance.
176*/
177QQmlExpression::~QQmlExpression()
178{
179}
180
181/*!
182 Returns the QQmlEngine this expression is associated with, or \nullptr if there
183 is no association or the QQmlEngine has been destroyed.
184*/
185QQmlEngine *QQmlExpression::engine() const
186{
187 Q_D(const QQmlExpression);
188 return d->engine();
189}
190
191/*!
192 Returns the QQmlContext this expression is associated with, or \nullptr if there
193 is no association or the QQmlContext has been destroyed.
194*/
195QQmlContext *QQmlExpression::context() const
196{
197 Q_D(const QQmlExpression);
198 return d->publicContext();
199}
200
201/*!
202 Returns the expression string.
203
204 If this expression was constructed from a \l QQmlScriptString, its source
205 code is not guaranteed to be available. A QML module compiled ahead of time
206 may not retain the source code of non-literal script strings. In that case
207 the expression can still be evaluated via evaluate(), but expression()
208 returns an empty string and produces a warning. Only literals (numbers,
209 strings, booleans, \c null and \c undefined) are guaranteed to be available
210 as source code.
211*/
212QString QQmlExpression::expression() const
213{
214 Q_D(const QQmlExpression);
215 if (d->expressionFunctionValid) {
216 qWarning("QQmlExpression: Attempted to retrieve potentially discarded source code of "
217 "expression. Only literals (numbers, strings, booleans, null, undefined) are "
218 "guaranteed to be available from QQmlExpression::expression().");
219 }
220 return d->expression;
221}
222
223/*!
224 Set the expression to \a expression.
225*/
226void QQmlExpression::setExpression(const QString &expression)
227{
228 Q_D(QQmlExpression);
229
230 d->resetNotifyOnValueChanged();
231 d->expression = expression;
232 d->expressionFunctionValid = false;
233}
234
235// Must be called with a valid handle scope
237{
239 createQmlBinding(context(), scopeObject(), expression, url, line);
241 if (hasError()) {
242 if (isUndefined)
243 *isUndefined = true;
244 return QV4::Encode::undefined();
245 }
246 }
247
248 return evaluate(isUndefined);
249}
250
251QVariant QQmlExpressionPrivate::value(bool *isUndefined)
252{
253 Q_Q(QQmlExpression);
254
255 if (!hasValidContext()) {
256 qWarning("QQmlExpression: Attempted to evaluate an expression in an invalid context");
257 return QVariant();
258 }
259
260 QQmlEngine *engine = q->engine();
261 QQmlEnginePrivate *ep = QQmlEnginePrivate::get(engine);
262 QVariant rv;
263
264 ep->referenceScarceResources(); // "hold" scarce resources in memory during evaluation.
265
266 {
267 QV4::Scope scope(engine->handle());
268 QV4::ScopedValue result(scope, v4value(isUndefined));
269 if (!hasError())
270 rv = QV4::ExecutionEngine::toVariant(result, QMetaType {});
271 }
272
273 ep->dereferenceScarceResources(); // "release" scarce resources if top-level expression evaluation is complete.
274
275 return rv;
276}
277
278/*!
279 Evaulates the expression, returning the result of the evaluation,
280 or an invalid QVariant if the expression is invalid or has an error.
281
282 \a valueIsUndefined is set to true if the expression resulted in an
283 undefined value.
284
285 \sa hasError(), error()
286*/
287QVariant QQmlExpression::evaluate(bool *valueIsUndefined)
288{
289 Q_D(QQmlExpression);
290 return d->value(valueIsUndefined);
291}
292
293/*!
294Returns true if the valueChanged() signal is emitted when the expression's evaluated
295value changes.
296*/
297bool QQmlExpression::notifyOnValueChanged() const
298{
299 Q_D(const QQmlExpression);
300 return d->notifyOnValueChanged();
301}
302
303/*!
304 Sets whether the valueChanged() signal is emitted when the
305 expression's evaluated value changes.
306
307 If \a notifyOnChange is true, the QQmlExpression will
308 monitor properties involved in the expression's evaluation, and emit
309 QQmlExpression::valueChanged() if they have changed. This
310 allows an application to ensure that any value associated with the
311 result of the expression remains up to date.
312
313 If \a notifyOnChange is false (default), the QQmlExpression
314 will not montitor properties involved in the expression's
315 evaluation, and QQmlExpression::valueChanged() will never be
316 emitted. This is more efficient if an application wants a "one off"
317 evaluation of the expression.
318*/
319void QQmlExpression::setNotifyOnValueChanged(bool notifyOnChange)
320{
321 Q_D(QQmlExpression);
322 d->setNotifyOnValueChanged(notifyOnChange);
323}
324
325/*!
326 Returns the source file URL for this expression. The source location must
327 have been previously set by calling setSourceLocation().
328*/
329QString QQmlExpression::sourceFile() const
330{
331 Q_D(const QQmlExpression);
332 return d->url;
333}
334
335/*!
336 Returns the source file line number for this expression. The source location
337 must have been previously set by calling setSourceLocation().
338*/
339int QQmlExpression::lineNumber() const
340{
341 Q_D(const QQmlExpression);
342 return qmlConvertSourceCoordinate<quint16, int>(d->line);
343}
344
345/*!
346 Returns the source file column number for this expression. The source location
347 must have been previously set by calling setSourceLocation().
348*/
349int QQmlExpression::columnNumber() const
350{
351 Q_D(const QQmlExpression);
352 return qmlConvertSourceCoordinate<quint16, int>(d->column);
353}
354
355/*!
356 Set the location of this expression to \a line and \a column of \a url. This information
357 is used by the script engine.
358*/
359void QQmlExpression::setSourceLocation(const QString &url, int line, int column)
360{
361 Q_D(QQmlExpression);
362 d->url = url;
363 d->line = qmlConvertSourceCoordinate<int, quint16>(line);
364 d->column = qmlConvertSourceCoordinate<int, quint16>(column);
365}
366
367/*!
368 Returns the expression's scope object, if provided, otherwise 0.
369
370 In addition to data provided by the expression's QQmlContext, the scope
371 object's properties are also in scope during the expression's evaluation.
372*/
373QObject *QQmlExpression::scopeObject() const
374{
375 Q_D(const QQmlExpression);
376 return d->scopeObject();
377}
378
379/*!
380 Returns true if the last call to evaluate() resulted in an error,
381 otherwise false.
382
383 \sa error(), clearError()
384*/
385bool QQmlExpression::hasError() const
386{
387 Q_D(const QQmlExpression);
388 return d->hasError();
389}
390
391/*!
392 Clear any expression errors. Calls to hasError() following this will
393 return false.
394
395 \sa hasError(), error()
396*/
397void QQmlExpression::clearError()
398{
399 Q_D(QQmlExpression);
400 d->clearError();
401}
402
403/*!
404 Return any error from the last call to evaluate(). If there was no error,
405 this returns an invalid QQmlError instance.
406
407 \sa hasError(), clearError()
408*/
409
410QQmlError QQmlExpression::error() const
411{
412 Q_D(const QQmlExpression);
413 return d->error(engine());
414}
415
416/*!
417 \fn void QQmlExpression::valueChanged()
418
419 Emitted each time the expression value changes from the last time it was
420 evaluated. The expression must have been evaluated at least once (by
421 calling QQmlExpression::evaluate()) before this signal will be emitted.
422*/
423
425{
426 Q_Q(QQmlExpression);
427 emit q->valueChanged();
428}
429
431{
432 return QLatin1Char('"') + expression + QLatin1Char('"');
433}
434
435QT_END_NAMESPACE
436
437#include <moc_qqmlexpression.cpp>
void expressionChanged() override
QV4::ReturnedValue v4value(bool *isUndefined=nullptr)
QVariant value(bool *isUndefined=nullptr)
QString expressionIdentifier() const override
~QQmlExpressionPrivate() override
friend class QQmlEnginePrivate