aboutsummaryrefslogtreecommitdiffstats
path: root/src/qml/qml/qqmlexpression.cpp
blob: 5864c3245c6484ae2145344229e92ea899b0acd8 (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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qqmlexpression.h"
#include "qqmlexpression_p.h"

#include "qqmlglobal_p.h"
#include "qqmlengine_p.h"
#include "qqmlcontext_p.h"
#include "qqmlscriptstring_p.h"
#include "qqmlbinding_p.h"
#include <private/qqmlsourcecoordinate_p.h>
#include <private/qv4qmlcontext_p.h>

#include <QtCore/qdebug.h>

QT_BEGIN_NAMESPACE

QQmlExpressionPrivate::QQmlExpressionPrivate()
: QQmlJavaScriptExpression(),
  expressionFunctionValid(true),
  line(0), column(0)
{
}

QQmlExpressionPrivate::~QQmlExpressionPrivate()
{
}

void QQmlExpressionPrivate::init(const QQmlRefPointer<QQmlContextData> &ctxt, const QString &expr,
                                 QObject *me)
{
    expression = expr;

    QQmlJavaScriptExpression::setContext(ctxt);
    setScopeObject(me);
    expressionFunctionValid = false;
}

void QQmlExpressionPrivate::init(const QQmlRefPointer<QQmlContextData> &ctxt,
                                 QV4::Function *runtimeFunction, QObject *me)
{
    expressionFunctionValid = true;
    QV4::ExecutionEngine *engine = ctxt->engine()->handle();
    QV4::Scope scope(engine);
    QV4::Scoped<QV4::QmlContext> qmlContext(scope, QV4::QmlContext::create(engine->rootContext(), ctxt, me));
    setupFunction(qmlContext, runtimeFunction);

    QQmlJavaScriptExpression::setContext(ctxt);
    setScopeObject(me);
}

/*!
    \class QQmlExpression
    \since 5.0
    \inmodule QtQml
    \brief The QQmlExpression class evaluates JavaScript in a QML context.

    For example, given a file \c main.qml like this:

    \qml
    import QtQuick 2.0

    Item {
        width: 200; height: 200
    }
    \endqml

    The following code evaluates a JavaScript expression in the context of the
    above QML:

    \code
    QQmlEngine *engine = new QQmlEngine;
    QQmlComponent component(engine, QUrl::fromLocalFile("main.qml"));

    QObject *myObject = component.create();
    QQmlExpression *expr = new QQmlExpression(engine->rootContext(), myObject, "width * 2");
    int result = expr->evaluate().toInt();  // result = 400
    \endcode
*/

/*!
    Create an invalid QQmlExpression.

    As the expression will not have an associated QQmlContext, this will be a
    null expression object and its value will always be an invalid QVariant.
 */
QQmlExpression::QQmlExpression()
: QObject(*new QQmlExpressionPrivate, nullptr)
{
}

/*!
    Create a QQmlExpression object that is a child of \a parent.

    The \a script provides the expression to be evaluated, the context to evaluate it in,
    and the scope object to evaluate it with. If provided, \a ctxt and \a scope will override
    the context and scope object provided by \a script.

    \sa QQmlScriptString
*/
QQmlExpression::QQmlExpression(const QQmlScriptString &script, QQmlContext *ctxt, QObject *scope, QObject *parent)
: QObject(*new QQmlExpressionPrivate, parent)
{
    Q_D(QQmlExpression);
    if (ctxt && !ctxt->isValid())
        return;

    const QQmlScriptStringPrivate *scriptPrivate = script.d.data();
    if (!ctxt && (!scriptPrivate->context || !scriptPrivate->context->isValid()))
        return;

    QQmlRefPointer<QQmlContextData> evalCtxtData
            = QQmlContextData::get(ctxt ? ctxt : scriptPrivate->context);
    QObject *scopeObject = scope ? scope : scriptPrivate->scope;
    QV4::Function *runtimeFunction = nullptr;

    if (scriptPrivate->context) {
        QQmlRefPointer<QQmlContextData> ctxtdata = QQmlContextData::get(scriptPrivate->context);
        QQmlEnginePrivate *engine = QQmlEnginePrivate::get(scriptPrivate->context->engine());
        if (engine
                && ctxtdata
                && !ctxtdata->urlString().isEmpty()
                && ctxtdata->typeCompilationUnit()) {
            d->url = ctxtdata->urlString();
            d->line = scriptPrivate->lineNumber;
            d->column = scriptPrivate->columnNumber;

            if (scriptPrivate->bindingId != QQmlBinding::Invalid)
                runtimeFunction = ctxtdata->typeCompilationUnit()->runtimeFunctions.at(scriptPrivate->bindingId);
        }
    }

    if (runtimeFunction) {
        d->expression = scriptPrivate->script;
        d->init(evalCtxtData, runtimeFunction, scopeObject);
    } else
        d->init(evalCtxtData, scriptPrivate->script, scopeObject);
}

/*!
    Create a QQmlExpression object that is a child of \a parent.

    The \a expression JavaScript will be executed in the \a ctxt QQmlContext.
    If specified, the \a scope object's properties will also be in scope during
    the expression's execution.
*/
QQmlExpression::QQmlExpression(QQmlContext *ctxt, QObject *scope, const QString &expression,
                               QObject *parent)
: QObject(*new QQmlExpressionPrivate, parent)
{
    Q_D(QQmlExpression);
    d->init(QQmlContextData::get(ctxt), expression, scope);
}

/*!
    \internal
*/
QQmlExpression::QQmlExpression(QQmlExpressionPrivate &dd, QObject *parent) : QObject(dd, parent)
{
//    Q_D(QQmlExpression);
//    d->init(QQmlContextData::get(ctxt), expression, scope);
}

/*!
    Destroy the QQmlExpression instance.
*/
QQmlExpression::~QQmlExpression()
{
}

/*!
    Returns the QQmlEngine this expression is associated with, or 0 if there
    is no association or the QQmlEngine has been destroyed.
*/
QQmlEngine *QQmlExpression::engine() const
{
    Q_D(const QQmlExpression);
    return d->engine();
}

/*!
    Returns the QQmlContext this expression is associated with, or 0 if there
    is no association or the QQmlContext has been destroyed.
*/
QQmlContext *QQmlExpression::context() const
{
    Q_D(const QQmlExpression);
    return d->publicContext();
}

/*!
    Returns the expression string.
*/
QString QQmlExpression::expression() const
{
    Q_D(const QQmlExpression);
    return d->expression;
}

/*!
    Set the expression to \a expression.
*/
void QQmlExpression::setExpression(const QString &expression)
{
    Q_D(QQmlExpression);

    d->resetNotifyOnValueChanged();
    d->expression = expression;
    d->expressionFunctionValid = false;
}

// Must be called with a valid handle scope
QV4::ReturnedValue QQmlExpressionPrivate::v4value(bool *isUndefined)
{
    if (!expressionFunctionValid) {
        createQmlBinding(context(), scopeObject(), expression, url, line);
        expressionFunctionValid = true;
        if (hasError()) {
            if (isUndefined)
                *isUndefined = true;
            return QV4::Encode::undefined();
        }
    }

    return evaluate(isUndefined);
}

QVariant QQmlExpressionPrivate::value(bool *isUndefined)
{
    Q_Q(QQmlExpression);

    if (!hasValidContext()) {
        qWarning("QQmlExpression: Attempted to evaluate an expression in an invalid context");
        return QVariant();
    }

    QQmlEngine *engine = q->engine();
    QQmlEnginePrivate *ep = QQmlEnginePrivate::get(engine);
    QVariant rv;

    ep->referenceScarceResources(); // "hold" scarce resources in memory during evaluation.

    {
        QV4::Scope scope(engine->handle());
        QV4::ScopedValue result(scope, v4value(isUndefined));
        if (!hasError())
            rv = scope.engine->toVariant(result, -1);
    }

    ep->dereferenceScarceResources(); // "release" scarce resources if top-level expression evaluation is complete.

    return rv;
}

/*!
    Evaulates the expression, returning the result of the evaluation,
    or an invalid QVariant if the expression is invalid or has an error.

    \a valueIsUndefined is set to true if the expression resulted in an
    undefined value.

    \sa hasError(), error()
*/
QVariant QQmlExpression::evaluate(bool *valueIsUndefined)
{
    Q_D(QQmlExpression);
    return d->value(valueIsUndefined);
}

/*!
Returns true if the valueChanged() signal is emitted when the expression's evaluated
value changes.
*/
bool QQmlExpression::notifyOnValueChanged() const
{
    Q_D(const QQmlExpression);
    return d->notifyOnValueChanged();
}

/*!
  Sets whether the valueChanged() signal is emitted when the
  expression's evaluated value changes.

  If \a notifyOnChange is true, the QQmlExpression will
  monitor properties involved in the expression's evaluation, and emit
  QQmlExpression::valueChanged() if they have changed.  This
  allows an application to ensure that any value associated with the
  result of the expression remains up to date.

  If \a notifyOnChange is false (default), the QQmlExpression
  will not montitor properties involved in the expression's
  evaluation, and QQmlExpression::valueChanged() will never be
  emitted.  This is more efficient if an application wants a "one off"
  evaluation of the expression.
*/
void QQmlExpression::setNotifyOnValueChanged(bool notifyOnChange)
{
    Q_D(QQmlExpression);
    d->setNotifyOnValueChanged(notifyOnChange);
}

/*!
    Returns the source file URL for this expression.  The source location must
    have been previously set by calling setSourceLocation().
*/
QString QQmlExpression::sourceFile() const
{
    Q_D(const QQmlExpression);
    return d->url;
}

/*!
    Returns the source file line number for this expression.  The source location
    must have been previously set by calling setSourceLocation().
*/
int QQmlExpression::lineNumber() const
{
    Q_D(const QQmlExpression);
    return qmlConvertSourceCoordinate<quint16, int>(d->line);
}

/*!
    Returns the source file column number for this expression.  The source location
    must have been previously set by calling setSourceLocation().
*/
int QQmlExpression::columnNumber() const
{
    Q_D(const QQmlExpression);
    return qmlConvertSourceCoordinate<quint16, int>(d->column);
}

/*!
    Set the location of this expression to \a line and \a column of \a url. This information
    is used by the script engine.
*/
void QQmlExpression::setSourceLocation(const QString &url, int line, int column)
{
    Q_D(QQmlExpression);
    d->url = url;
    d->line = qmlConvertSourceCoordinate<int, quint16>(line);
    d->column = qmlConvertSourceCoordinate<int, quint16>(column);
}

/*!
    Returns the expression's scope object, if provided, otherwise 0.

    In addition to data provided by the expression's QQmlContext, the scope
    object's properties are also in scope during the expression's evaluation.
*/
QObject *QQmlExpression::scopeObject() const
{
    Q_D(const QQmlExpression);
    return d->scopeObject();
}

/*!
    Returns true if the last call to evaluate() resulted in an error,
    otherwise false.

    \sa error(), clearError()
*/
bool QQmlExpression::hasError() const
{
    Q_D(const QQmlExpression);
    return d->hasError();
}

/*!
    Clear any expression errors.  Calls to hasError() following this will
    return false.

    \sa hasError(), error()
*/
void QQmlExpression::clearError()
{
    Q_D(QQmlExpression);
    d->clearError();
}

/*!
    Return any error from the last call to evaluate().  If there was no error,
    this returns an invalid QQmlError instance.

    \sa hasError(), clearError()
*/

QQmlError QQmlExpression::error() const
{
    Q_D(const QQmlExpression);
    return d->error(engine());
}

/*!
    \fn void QQmlExpression::valueChanged()

    Emitted each time the expression value changes from the last time it was
    evaluated.  The expression must have been evaluated at least once (by
    calling QQmlExpression::evaluate()) before this signal will be emitted.
*/

void QQmlExpressionPrivate::expressionChanged()
{
    Q_Q(QQmlExpression);
    emit q->valueChanged();
}

QString QQmlExpressionPrivate::expressionIdentifier() const
{
    return QLatin1Char('"') + expression + QLatin1Char('"');
}

QT_END_NAMESPACE

#include <moc_qqmlexpression.cpp>