aboutsummaryrefslogtreecommitdiffstats
path: root/src/qml/qml/qqmlexpression.cpp
blob: 3bc0c50ba4c10d63a1bb176d0d4ebc7d3ad2dbf3 (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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** 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 Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/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 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

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

#include "qqmlglobal_p.h"
#include "qqmlengine_p.h"
#include "qqmlcontext_p.h"
#include "qqmlrewrite_p.h"
#include "qqmlscriptstring_p.h"
#include "qqmlcompiler_p.h"

#include <QtCore/qdebug.h>

QT_BEGIN_NAMESPACE

static QQmlJavaScriptExpression::VTable QQmlExpressionPrivate_jsvtable = {
    QQmlExpressionPrivate::expressionIdentifier,
    QQmlExpressionPrivate::expressionChanged
};

QQmlExpressionPrivate::QQmlExpressionPrivate()
: QQmlJavaScriptExpression(&QQmlExpressionPrivate_jsvtable),
  expressionFunctionValid(true), expressionFunctionRewritten(false),
  line(0), column(0)
{
}

QQmlExpressionPrivate::~QQmlExpressionPrivate()
{
    qPersistentDispose(v8qmlscope);
    qPersistentDispose(v8function);
}

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

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

void QQmlExpressionPrivate::init(QQmlContextData *ctxt, const QString &expr,
                                 bool isRewritten, QObject *me, const QString &srcUrl,
                                 quint16 lineNumber, quint16 columnNumber)
{
    url = srcUrl;
    line = lineNumber;
    column = columnNumber;

    expression = expr;

    expressionFunctionValid = false;
    expressionFunctionRewritten = isRewritten;

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

void QQmlExpressionPrivate::init(QQmlContextData *ctxt, const QByteArray &expr,
                                 bool isRewritten, QObject *me, const QString &srcUrl,
                                 quint16 lineNumber, quint16 columnNumber)
{
    url = srcUrl;
    line = lineNumber;
    column = columnNumber;

    if (isRewritten) {
        expressionFunctionValid = true;
        expressionFunctionRewritten = true;
        v8function = evalFunction(ctxt, me, expr.constData(), expr.length(),
                                  srcUrl, lineNumber, &v8qmlscope);
        setUseSharedContext(false);

        expressionUtf8 = expr;
    } else {
        expression = QString::fromUtf8(expr);

        expressionFunctionValid = false;
        expressionFunctionRewritten = isRewritten;
    }

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

QQmlExpression *
QQmlExpressionPrivate::create(QQmlContextData *ctxt, QObject *object,
                              const QString &expr, bool isRewritten,
                              const QString &url, quint16 lineNumber, quint16 columnNumber)
{
    return new QQmlExpression(ctxt, object, expr, isRewritten, url, lineNumber, columnNumber,
                              *new QQmlExpressionPrivate);
}

/*!
    \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

    Note that the QtQuick 1 version is called QDeclarativeExpression.
*/

/*!
    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, 0)
{
}

/*!  \internal */
QQmlExpression::QQmlExpression(QQmlContextData *ctxt,
                                               QObject *object, const QString &expr, bool isRewritten,
                                               const QString &url, int lineNumber, int columnNumber,
                                               QQmlExpressionPrivate &dd)
: QObject(dd, 0)
{
    Q_D(QQmlExpression);
    d->init(ctxt, expr, isRewritten, object, url, qmlSourceCoordinate(lineNumber), qmlSourceCoordinate(columnNumber));
}

/*!  \internal */
QQmlExpression::QQmlExpression(QQmlContextData *ctxt,
                                               QObject *object, const QByteArray &expr,
                                               bool isRewritten,
                                               const QString &url, int lineNumber, int columnNumber,
                                               QQmlExpressionPrivate &dd)
: QObject(dd, 0)
{
    Q_D(QQmlExpression);
    d->init(ctxt, expr, isRewritten, object, url, qmlSourceCoordinate(lineNumber), qmlSourceCoordinate(columnNumber));
}

/*!
    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;

    bool defaultConstruction = true;
    QQmlContextData *evalCtxtData = QQmlContextData::get(ctxt ? ctxt : scriptPrivate->context);
    QObject *scopeObject = scope ? scope : scriptPrivate->scope;

    int id = scriptPrivate->bindingId;
    if (id >= 0) {
        QQmlContextData *ctxtdata = QQmlContextData::get(scriptPrivate->context);
        QQmlEnginePrivate *engine = QQmlEnginePrivate::get(scriptPrivate->context->engine());
        if (engine && ctxtdata && !ctxtdata->url.isEmpty()) {
            QQmlTypeData *typeData = engine->typeLoader.getType(ctxtdata->url);
            Q_ASSERT(typeData);

            if (QQmlCompiledData *cdata = typeData->compiledData()) {
                defaultConstruction = false;
                d->init(evalCtxtData, cdata->primitives.at(id), true, scopeObject,
                        cdata->name, scriptPrivate->lineNumber, scriptPrivate->columnNumber);
            }

            typeData->release();
        }
    }

    if (defaultConstruction)
        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(QQmlContextData *ctxt, QObject *scope,
                                               const QString &expression)
: QObject(*new QQmlExpressionPrivate, 0)
{
    Q_D(QQmlExpression);
    d->init(ctxt, expression, scope);
}

/*!  \internal */
QQmlExpression::QQmlExpression(QQmlContextData *ctxt, QObject *scope,
                                               const QString &expression, QQmlExpressionPrivate &dd)
: QObject(dd, 0)
{
    Q_D(QQmlExpression);
    d->init(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->context()?d->context()->engine:0;
}

/*!
    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);
    QQmlContextData *data = d->context();
    return data?data->asQQmlContext():0;
}

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

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

    d->resetNotifyOnValueChanged();
    d->expression = expression;
    d->expressionUtf8.clear();
    d->expressionFunctionValid = false;
    d->expressionFunctionRewritten = false;
    qPersistentDispose(d->v8function);
    qPersistentDispose(d->v8qmlscope);
}

// Must be called with a valid handle scope
v8::Local<v8::Value> QQmlExpressionPrivate::v8value(bool *isUndefined)
{
    if (!expressionFunctionValid) {
        bool ok = true;

        QQmlRewrite::RewriteBinding rewriteBinding;
        rewriteBinding.setName(name);
        QString code;
        if (expressionFunctionRewritten)
            code = expression;
        else
            code = rewriteBinding(expression, &ok);

        if (ok) v8function = evalFunction(context(), scopeObject(), code, url, line, &v8qmlscope);
        setUseSharedContext(false);
        expressionFunctionValid = true;
    }

    return evaluate(context(), v8function, isUndefined);
}

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

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

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

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

    {
        v8::HandleScope handle_scope;
        v8::Context::Scope context_scope(ep->v8engine()->context());
        v8::Local<v8::Value> result = v8value(isUndefined);
        rv = ep->v8engine()->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 qmlSourceCoordinate(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 qmlSourceCoordinate(d->column);
}

/*!
    Set the location of this expression to \a line 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 = qmlSourceCoordinate(line);
    d->column = qmlSourceCoordinate(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(QQmlJavaScriptExpression *e)
{
    QQmlExpressionPrivate *This = static_cast<QQmlExpressionPrivate *>(e);
    This->expressionChanged();
}

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

QString QQmlExpressionPrivate::expressionIdentifier(QQmlJavaScriptExpression *e)
{
    QQmlExpressionPrivate *This = static_cast<QQmlExpressionPrivate *>(e);
    return QLatin1Char('"') + This->expression + QLatin1Char('"');
}

QT_END_NAMESPACE

#include <moc_qqmlexpression.cpp>