source: branches/4.5.1/src/script/qscriptengine.cpp

Last change on this file was 2, checked in by Dmitry A. Kuminov, 16 years ago

Initially imported qt-all-opensource-src-4.5.1 from Trolltech.

File size: 61.2 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
4** Contact: Qt Software Information ([email protected])
5**
6** This file is part of the QtScript module of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial Usage
10** Licensees holding valid Qt Commercial licenses may use this file in
11** accordance with the Qt Commercial License Agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and Nokia.
14**
15** GNU Lesser General Public License Usage
16** Alternatively, this file may be used under the terms of the GNU Lesser
17** General Public License version 2.1 as published by the Free Software
18** Foundation and appearing in the file LICENSE.LGPL included in the
19** packaging of this file. Please review the following information to
20** ensure the GNU Lesser General Public License version 2.1 requirements
21** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
22**
23** In addition, as a special exception, Nokia gives you certain
24** additional rights. These rights are described in the Nokia Qt LGPL
25** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
26** package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you are unsure which license is appropriate for your use, please
37** contact the sales department at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include "qscriptengine.h"
43
44#ifndef QT_NO_SCRIPT
45
46#include "qscriptengine_p.h"
47#include "qscriptvalueimpl_p.h"
48#include "qscriptcontext_p.h"
49#include "qscriptmember_p.h"
50#include "qscriptobject_p.h"
51#include "qscriptsyntaxcheckresult_p.h"
52
53QT_BEGIN_NAMESPACE
54
55/*!
56 \since 4.3
57 \class QScriptEngine
58 \reentrant
59
60 \brief The QScriptEngine class provides an environment for evaluating Qt Script code.
61
62 \ingroup script
63 \mainclass
64
65 See the \l{QtScript} documentation for information about the Qt Script language,
66 and how to get started with scripting your C++ application.
67
68 \section1 Evaluating Scripts
69
70 Use evaluate() to evaluate script code; this is the C++ equivalent
71 of the built-in script function \c{eval()}.
72
73 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 0
74
75 evaluate() returns a QScriptValue that holds the result of the
76 evaluation. The QScriptValue class provides functions for converting
77 the result to various C++ types (e.g. QScriptValue::toString()
78 and QScriptValue::toNumber()).
79
80 The following code snippet shows how a script function can be
81 defined and then invoked from C++ using QScriptValue::call():
82
83 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 1
84
85 As can be seen from the above snippets, a script is provided to the
86 engine in the form of a string. One common way of loading scripts is
87 by reading the contents of a file and passing it to evaluate():
88
89 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 2
90
91 Here we pass the name of the file as the second argument to
92 evaluate(). This does not affect evaluation in any way; the second
93 argument is a general-purpose string that is used to identify the
94 script for debugging purposes (for example, our filename will now
95 show up in any uncaughtExceptionBacktrace() involving the script).
96
97 \section1 Engine Configuration
98
99 The globalObject() function returns the \bold {Global Object}
100 associated with the script engine. Properties of the Global Object
101 are accessible from any script code (i.e. they are global
102 variables). Typically, before evaluating "user" scripts, you will
103 want to configure a script engine by adding one or more properties
104 to the Global Object:
105
106 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 3
107
108 Adding custom properties to the scripting environment is one of the
109 standard means of providing a scripting API that is specific to your
110 application. Usually these custom properties are objects created by
111 the newQObject() or newObject() functions, or constructor functions
112 created by newFunction().
113
114 \section1 Script Exceptions
115
116 evaluate() can throw a script exception (e.g. due to a syntax
117 error); in that case, the return value is the value that was thrown
118 (typically an \c{Error} object). You can check whether the
119 evaluation caused an exception by calling hasUncaughtException(). In
120 that case, you can call toString() on the error object to obtain an
121 error message. The current uncaught exception is also available
122 through uncaughtException(). You can obtain a human-readable
123 backtrace of the exception with uncaughtExceptionBacktrace().
124 Calling clearExceptions() will cause any uncaught exceptions to be
125 cleared.
126
127 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 4
128
129 The checkSyntax() function can be used to determine whether code can be
130 usefully passed to evaluate().
131
132 \section1 Script Object Creation
133
134 Use newObject() to create a standard Qt Script object; this is the
135 C++ equivalent of the script statement \c{new Object()}. You can use
136 the object-specific functionality in QScriptValue to manipulate the
137 script object (e.g. QScriptValue::setProperty()). Similarly, use
138 newArray() to create a Qt Script array object. Use newDate() to
139 create a \c{Date} object, and newRegExp() to create a \c{RegExp}
140 object.
141
142 \section1 QObject Integration
143
144 Use newQObject() to wrap a QObject (or subclass)
145 pointer. newQObject() returns a proxy script object; properties,
146 children, and signals and slots of the QObject are available as
147 properties of the proxy object. No binding code is needed because it
148 is done dynamically using the Qt meta object system.
149
150 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 5
151
152 Use qScriptConnect() to connect a C++ signal to a script function;
153 this is the Qt Script equivalent of QObject::connect(). When a
154 script function is invoked in response to a C++ signal, it can cause
155 a script exception; you can connect to the signalHandlerException()
156 signal to catch such an exception.
157
158 Use newQMetaObject() to wrap a QMetaObject; this gives you a "script
159 representation" of a QObject-based class. newQMetaObject() returns a
160 proxy script object; enum values of the class are available as
161 properties of the proxy object. You can also specify a function that
162 will be used to construct objects of the class (e.g. when the
163 constructor is invoked from a script). For classes that have a
164 "standard" Qt constructor, Qt Script can provide a default script
165 constructor for you; see scriptValueFromQMetaObject().
166
167 See the \l{QtScript} documentation for more information on
168 the QObject integration.
169
170 \section1 Support for Custom C++ Types
171
172 Use newVariant() to wrap a QVariant. This can be used to store
173 values of custom (non-QObject) C++ types that have been registered
174 with the Qt meta-type system. To make such types scriptable, you
175 typically associate a prototype (delegate) object with the C++ type
176 by calling setDefaultPrototype(); the prototype object defines the
177 scripting API for the C++ type. Unlike the QObject integration,
178 there is no automatic binding possible here; i.e. you have to create
179 the scripting API yourself, for example by using the QScriptable
180 class.
181
182 Use fromScriptValue() to cast from a QScriptValue to another type,
183 and toScriptValue() to create a QScriptValue from another value.
184 You can specify how the conversion of C++ types is to be performed
185 with qScriptRegisterMetaType() and qScriptRegisterSequenceMetaType().
186 By default, Qt Script will use QVariant to store values of custom
187 types.
188
189 \section1 Importing Extensions
190
191 Use importExtension() to import plugin-based extensions into the
192 engine. Call availableExtensions() to obtain a list naming all the
193 available extensions, and importedExtensions() to obtain a list
194 naming only those extensions that have been imported.
195
196 Call pushContext() to open up a new variable scope, and popContext()
197 to close the current scope. This is useful if you are implementing
198 an extension that evaluates script code containing temporary
199 variable definitions (e.g. \c{var foo = 123;}) that are safe to
200 discard when evaluation has completed.
201
202 \section1 Native Functions
203
204 Use newFunction() to wrap native (C++) functions, including
205 constructors for your own custom types, so that these can be invoked
206 from script code. Such functions must have the signature
207 QScriptEngine::FunctionSignature. You may then pass the function as
208 argument to newFunction(). Here is an example of a function that
209 returns the sum of its first two arguments:
210
211 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 6
212
213 To expose this function to script code, you can set it as a property
214 of the Global Object:
215
216 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 7
217
218 Once this is done, script code can call your function in the exact
219 same manner as a "normal" script function:
220
221 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 8
222
223 \section1 Long-running Scripts
224
225 If you need to evaluate possibly long-running scripts from the main
226 (GUI) thread, you should first call setProcessEventsInterval() to
227 make sure that the GUI stays responsive. You can abort a currently
228 running script by calling abortEvaluation(). You can determine
229 whether an engine is currently running a script by calling
230 isEvaluating().
231
232 \section1 Core Debugging/Tracing Facilities
233
234 Since Qt 4.4, you can be notified of events pertaining to script
235 execution (e.g. script function calls and statement execution)
236 through the QScriptEngineAgent interface; see the setAgent()
237 function. This can be used to implement debugging and profiling of a
238 QScriptEngine.
239
240 \sa QScriptValue, QScriptContext, QScriptEngineAgent
241
242*/
243
244/*!
245 \enum QScriptEngine::ValueOwnership
246
247 This enum specifies the ownership when wrapping a C++ value, e.g. by using newQObject().
248
249 \value QtOwnership The standard Qt ownership rules apply, i.e. the associated object will never be explicitly deleted by the script engine. This is the default. (QObject ownership is explained in \l{Object Trees and Object Ownership}.)
250 \value ScriptOwnership The value is owned by the script environment. The associated data will be deleted when appropriate (i.e. after the garbage collector has discovered that there are no more live references to the value).
251 \value AutoOwnership If the associated object has a parent, the Qt ownership rules apply (QtOwnership); otherwise, the object is owned by the script environment (ScriptOwnership).
252*/
253
254/*!
255 \enum QScriptEngine::QObjectWrapOption
256
257 These flags specify options when wrapping a QObject pointer with newQObject().
258
259 \value ExcludeChildObjects The script object will not expose child objects as properties.
260 \value ExcludeSuperClassMethods The script object will not expose signals and slots inherited from the superclass.
261 \value ExcludeSuperClassProperties The script object will not expose properties inherited from the superclass.
262 \value ExcludeSuperClassContents Shorthand form for ExcludeSuperClassMethods | ExcludeSuperClassProperties
263 \value ExcludeDeleteLater The script object will not expose the QObject::deleteLater() slot.
264 \value AutoCreateDynamicProperties Properties that don't already exist in the QObject will be created as dynamic properties of that object, rather than as properties of the script object.
265 \value PreferExistingWrapperObject If a wrapper object with the requested configuration already exists, return that object.
266 \value SkipMethodsInEnumeration Don't include methods (signals and slots) when enumerating the object's properties.
267*/
268
269#ifdef QT_NO_QOBJECT
270
271QScriptEngine::QScriptEngine()
272 : d_ptr(new QScriptEnginePrivate)
273{
274 d_ptr->q_ptr = this;
275 d_ptr->init();
276}
277
278/*! \internal
279*/
280QScriptEngine::QScriptEngine(QScriptEnginePrivate &dd)
281 : d_ptr(&dd)
282{
283 d_ptr->q_ptr = this;
284 d_ptr->init();
285}
286#else
287
288/*!
289 Constructs a QScriptEngine object.
290
291 The globalObject() is initialized to have properties as described in
292 \l{ECMA-262}, Section 15.1.
293*/
294QScriptEngine::QScriptEngine()
295 : QObject(*new QScriptEnginePrivate, 0)
296{
297 Q_D(QScriptEngine);
298 d->init();
299}
300
301/*!
302 Constructs a QScriptEngine object with the given \a parent.
303
304 The globalObject() is initialized to have properties as described in
305 \l{ECMA-262}, Section 15.1.
306*/
307
308QScriptEngine::QScriptEngine(QObject *parent)
309 : QObject(*new QScriptEnginePrivate, parent)
310{
311 Q_D(QScriptEngine);
312 d->init();
313}
314
315/*! \internal
316*/
317QScriptEngine::QScriptEngine(QScriptEnginePrivate &dd, QObject *parent)
318 : QObject(dd, parent)
319{
320 Q_D(QScriptEngine);
321 d->init();
322}
323#endif
324
325/*!
326 Destroys this QScriptEngine.
327*/
328QScriptEngine::~QScriptEngine()
329{
330 Q_D(QScriptEngine);
331 d->m_frameRepository.release(currentContext());
332 d->objectAllocator.destruct();
333#ifdef QT_NO_QOBJECT
334 delete d_ptr;
335 d_ptr = 0;
336#endif
337}
338
339/*!
340 Returns this engine's Global Object.
341
342 By default, the Global Object contains the built-in objects that are
343 part of \l{ECMA-262}, such as Math, Date and String. Additionally,
344 you can set properties of the Global Object to make your own
345 extensions available to all script code. Non-local variables in
346 script code will be created as properties of the Global Object, as
347 well as local variables in global code.
348*/
349QScriptValue QScriptEngine::globalObject() const
350{
351 Q_D(const QScriptEngine);
352 return const_cast<QScriptEnginePrivate*>(d)->toPublic(d->m_globalObject);
353}
354
355/*!
356 \since 4.5
357
358 Sets this engine's Global Object to be the given \a object.
359 If \a object is not a valid script object, this function does
360 nothing.
361
362 When setting a custom global object, you may want to use
363 QScriptValueIterator to copy the properties of the standard Global
364 Object; alternatively, you can set the internal prototype of your
365 custom object to be the original Global Object.
366*/
367void QScriptEngine::setGlobalObject(const QScriptValue &object)
368{
369 Q_D(QScriptEngine);
370 if (!object.isObject())
371 return;
372 QScriptValueImpl objectImpl = d->toImpl(object);
373
374 // update properties of the global context
375 QScriptValueImpl old = d->m_globalObject;
376 QScriptContextPrivate *ctx = d->currentContext();
377 while (ctx->parentContext() != 0)
378 ctx = ctx->parentContext();
379 if (QScriptEnginePrivate::strictlyEquals(ctx->m_thisObject, old))
380 ctx->m_thisObject = objectImpl;
381 if (QScriptEnginePrivate::strictlyEquals(ctx->m_activation, old))
382 ctx->m_activation = objectImpl;
383 if (QScriptEnginePrivate::strictlyEquals(ctx->m_scopeChain, old))
384 ctx->m_scopeChain = objectImpl;
385
386 d->m_globalObject = objectImpl;
387}
388
389/*!
390 Returns a QScriptValue of the primitive type Null.
391
392 \sa undefinedValue()
393*/
394QScriptValue QScriptEngine::nullValue()
395{
396 Q_D(QScriptEngine);
397 return d->toPublic(d->nullValue());
398}
399
400/*!
401 Returns a QScriptValue of the primitive type Undefined.
402
403 \sa nullValue()
404*/
405QScriptValue QScriptEngine::undefinedValue()
406{
407 Q_D(QScriptEngine);
408 return d->toPublic(d->undefinedValue());
409}
410
411/*!
412 Creates a constructor function from \a fun, with the given \a length.
413 The \c{prototype} property of the resulting function is set to be the
414 given \a prototype. The \c{constructor} property of \a prototype is
415 set to be the resulting function.
416
417 When a function is called as a constructor (e.g. \c{new Foo()}), the
418 `this' object associated with the function call is the new object
419 that the function is expected to initialize; the prototype of this
420 default constructed object will be the function's public
421 \c{prototype} property. If you always want the function to behave as
422 a constructor (e.g. \c{Foo()} should also create a new object), or
423 if you need to create your own object rather than using the default
424 `this' object, you should make sure that the prototype of your
425 object is set correctly; either by setting it manually, or, when
426 wrapping a custom type, by having registered the defaultPrototype()
427 of that type. Example:
428
429 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 9
430
431 To wrap a custom type and provide a constructor for it, you'd typically
432 do something like this:
433
434 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 10
435*/
436QScriptValue QScriptEngine::newFunction(QScriptEngine::FunctionSignature fun,
437 const QScriptValue &prototype,
438 int length)
439{
440 Q_D(QScriptEngine);
441 QScriptValueImpl v = d->createFunction(new QScript::CFunction(fun, length));
442 QScriptValueImpl proto = d->toImpl(prototype);
443 v.setProperty(d->idTable()->id_prototype, proto,
444 QScriptValue::Undeletable);
445 proto.setProperty(d->idTable()->id_constructor, v,
446 QScriptValue::Undeletable
447 | QScriptValue::SkipInEnumeration);
448 return d->toPublic(v);
449}
450
451#ifndef QT_NO_REGEXP
452/*!
453 Creates a QtScript object of class RegExp with the given
454 \a regexp.
455
456 \sa QScriptValue::toRegExp()
457*/
458QScriptValue QScriptEngine::newRegExp(const QRegExp &regexp)
459{
460 Q_D(QScriptEngine);
461 QScriptValueImpl v;
462 d->regexpConstructor->newRegExp(&v, regexp);
463 return d->toPublic(v);
464}
465
466#endif // QT_NO_REGEXP
467
468/*!
469 Creates a QtScript object holding the given variant \a value.
470
471 If a default prototype has been registered with the meta type id of
472 \a value, then the prototype of the created object will be that
473 prototype; otherwise, the prototype will be the Object prototype
474 object.
475
476 \sa setDefaultPrototype(), QScriptValue::toVariant()
477*/
478QScriptValue QScriptEngine::newVariant(const QVariant &value)
479{
480 Q_D(QScriptEngine);
481 QScriptValueImpl result;
482 d->newVariant(&result, value);
483 return d->toPublic(result);
484}
485
486/*!
487 \since 4.4
488 \overload
489
490 Initializes the given Qt Script \a object to hold the given variant
491 \a value, and returns the \a object.
492
493 This function enables you to "promote" a plain Qt Script object
494 (created by the newObject() function) to a variant, or to replace
495 the variant contained inside an object previously created by the
496 newVariant() function.
497
498 The prototype() of the \a object will remain unchanged.
499
500 If \a object is not an object, this function behaves like the normal
501 newVariant(), i.e. it creates a new script object and returns it.
502
503 This function is useful when you want to provide a script
504 constructor for a C++ type. If your constructor is invoked in a
505 \c{new} expression (QScriptContext::isCalledAsConstructor() returns
506 true), you can pass QScriptContext::thisObject() (the default
507 constructed script object) to this function to initialize the new
508 object.
509*/
510QScriptValue QScriptEngine::newVariant(const QScriptValue &object,
511 const QVariant &value)
512{
513 Q_D(QScriptEngine);
514 QScriptValuePrivate *p = QScriptValuePrivate::get(object);
515 if (!p || !p->value.isObject())
516 return newVariant(value);
517 if (p->value.isVariant())
518 p->value.setVariantValue(value);
519 else
520 d->newVariant(&p->value, value, /*setDefaultPrototype=*/false);
521 return object;
522}
523
524#ifndef QT_NO_QOBJECT
525/*!
526 Creates a QtScript object that wraps the given QObject \a
527 object, using the given \a ownership. The given \a options control
528 various aspects of the interaction with the resulting script object.
529
530 Signals and slots, properties and children of \a object are
531 available as properties of the created QScriptValue. For more
532 information, see the \l{QtScript} documentation.
533
534 If \a object is a null pointer, this function returns nullValue().
535
536 If a default prototype has been registered for the \a object's class
537 (or its superclass, recursively), the prototype of the new script
538 object will be set to be that default prototype.
539
540 If the given \a object is deleted outside of QtScript's control, any
541 attempt to access the deleted QObject's members through the QtScript
542 wrapper object (either by script code or C++) will result in a
543 script exception.
544
545 \sa QScriptValue::toQObject()
546*/
547QScriptValue QScriptEngine::newQObject(QObject *object, ValueOwnership ownership,
548 const QObjectWrapOptions &options)
549{
550 Q_D(QScriptEngine);
551 QScriptValueImpl result;
552 d->newQObject(&result, object, ownership, options);
553 return d->toPublic(result);
554}
555
556/*!
557 \since 4.4
558 \overload
559
560 Initializes the given \a scriptObject to hold the given \a qtObject,
561 and returns the \a scriptObject.
562
563 This function enables you to "promote" a plain Qt Script object
564 (created by the newObject() function) to a QObject proxy, or to
565 replace the QObject contained inside an object previously created by
566 the newQObject() function.
567
568 The prototype() of the \a scriptObject will remain unchanged.
569
570 If \a scriptObject is not an object, this function behaves like the
571 normal newQObject(), i.e. it creates a new script object and returns
572 it.
573
574 This function is useful when you want to provide a script
575 constructor for a QObject-based class. If your constructor is
576 invoked in a \c{new} expression
577 (QScriptContext::isCalledAsConstructor() returns true), you can pass
578 QScriptContext::thisObject() (the default constructed script object)
579 to this function to initialize the new object.
580*/
581QScriptValue QScriptEngine::newQObject(const QScriptValue &scriptObject,
582 QObject *qtObject,
583 ValueOwnership ownership,
584 const QObjectWrapOptions &options)
585{
586 Q_D(QScriptEngine);
587 QScriptValuePrivate *p = QScriptValuePrivate::get(scriptObject);
588 if (!p || !p->value.isObject())
589 return newQObject(qtObject, ownership, options);
590 if (p->value.isVariant()) {
591 QScript::ExtQObject::Instance *data;
592 data = d->qobjectConstructor->get(p->value);
593 Q_ASSERT(data != 0);
594 data->value = qtObject;
595 data->ownership = ownership;
596 data->options = options;
597 } else {
598 d->newQObject(&p->value, qtObject, ownership, options,
599 /*setDefaultPrototype=*/false);
600 }
601 return scriptObject;
602}
603
604#endif // QT_NO_QOBJECT
605
606/*!
607 Creates a QtScript object of class Object.
608
609 The prototype of the created object will be the Object
610 prototype object.
611
612 \sa newArray(), QScriptValue::setProperty()
613*/
614QScriptValue QScriptEngine::newObject()
615{
616 Q_D(QScriptEngine);
617 QScriptValueImpl v;
618 d->newObject(&v, d->objectConstructor->publicPrototype);
619 return d->toPublic(v);
620}
621
622/*!
623 \since 4.4
624 \overload
625
626 Creates a QtScript Object of the given class, \a scriptClass.
627
628 The prototype of the created object will be the Object
629 prototype object.
630
631 \a data, if specified, is set as the internal data of the
632 new object (using QScriptValue::setData()).
633
634 \sa QScriptValue::scriptClass()
635*/
636QScriptValue QScriptEngine::newObject(QScriptClass *scriptClass,
637 const QScriptValue &data)
638{
639 Q_D(QScriptEngine);
640 return d->toPublic(d->newObject(scriptClass, d->toImpl(data)));
641}
642
643/*!
644 \internal
645*/
646QScriptValue QScriptEngine::newActivationObject()
647{
648 Q_D(QScriptEngine);
649 QScriptValueImpl v;
650 d->newActivation(&v);
651 return d->toPublic(v);
652}
653
654/*!
655 Creates a QScriptValue that wraps a native (C++) function. \a fun
656 must be a C++ function with signature QScriptEngine::FunctionSignature. \a
657 length is the number of arguments that \a fun expects; this becomes
658 the \c{length} property of the created QScriptValue.
659
660 Note that \a length only gives an indication of the number of
661 arguments that the function expects; an actual invocation of a
662 function can include any number of arguments. You can check the
663 \l{QScriptContext::argumentCount()}{argumentCount()} of the
664 QScriptContext associated with the invocation to determine the
665 actual number of arguments passed.
666
667 A \c{prototype} property is automatically created for the resulting
668 function object, to provide for the possibility that the function
669 will be used as a constructor.
670
671 By combining newFunction() and the property flags
672 QScriptValue::PropertyGetter and QScriptValue::PropertySetter, you
673 can create script object properties that behave like normal
674 properties in script code, but are in fact accessed through
675 functions (analogous to how properties work in \l{Qt's Property
676 System}). Example:
677
678 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 11
679
680 When the property \c{foo} of the script object is subsequently
681 accessed in script code, \c{getSetFoo()} will be invoked to handle
682 the access. In this particular case, we chose to store the "real"
683 value of \c{foo} as a property of the accessor function itself; you
684 are of course free to do whatever you like in this function.
685
686 In the above example, a single native function was used to handle
687 both reads and writes to the property; the argument count is used to
688 determine if we are handling a read or write. You can also use two
689 separate functions; just specify the relevant flag
690 (QScriptValue::PropertyGetter or QScriptValue::PropertySetter) when
691 setting the property, e.g.:
692
693 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 12
694
695 \sa QScriptValue::call()
696*/
697QScriptValue QScriptEngine::newFunction(QScriptEngine::FunctionSignature fun, int length)
698{
699 Q_D(QScriptEngine);
700 QScriptValueImpl v = d->createFunction(new QScript::CFunction(fun, length));
701 QScriptValueImpl prototype = d->newObject();
702 v.setProperty(d->idTable()->id_prototype, prototype, QScriptValue::Undeletable);
703 prototype.setProperty(d->idTable()->id_constructor, v,
704 QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
705 return d->toPublic(v);
706}
707
708/*!
709 \internal
710 \since 4.4
711*/
712QScriptValue QScriptEngine::newFunction(QScriptEngine::FunctionWithArgSignature fun, void *arg)
713{
714 Q_D(QScriptEngine);
715 QScriptValueImpl v = d->createFunction(new QScript::C3Function(fun, arg, /*length=*/0));
716 QScriptValueImpl prototype = d->newObject();
717 v.setProperty(d->idTable()->id_prototype, prototype, QScriptValue::Undeletable);
718 prototype.setProperty(d->idTable()->id_constructor, v,
719 QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
720 return d->toPublic(v);
721}
722
723/*!
724 Creates a QtScript object of class Array with the given \a length.
725
726 \sa newObject()
727*/
728QScriptValue QScriptEngine::newArray(uint length)
729{
730 Q_D(QScriptEngine);
731 QScriptValueImpl v;
732 QScript::Array a(d);
733 a.resize(length);
734 d->newArray(&v, a);
735 return d->toPublic(v);
736}
737
738/*!
739 Creates a QtScript object of class RegExp with the given
740 \a pattern and \a flags.
741
742 The legal flags are 'g' (global), 'i' (ignore case), and 'm'
743 (multiline).
744*/
745QScriptValue QScriptEngine::newRegExp(const QString &pattern, const QString &flags)
746{
747 Q_D(QScriptEngine);
748 int bitflags = 0;
749 for (int i = 0; i < flags.size(); ++i)
750 bitflags |= QScript::Ecma::RegExp::flagFromChar(flags.at(i));
751 QScriptValueImpl v;
752 d->regexpConstructor->newRegExp(&v, pattern, bitflags);
753 return d->toPublic(v);
754}
755
756/*!
757 Creates a QtScript object of class Date with the given
758 \a value (the number of milliseconds since 01 January 1970,
759 UTC).
760*/
761QScriptValue QScriptEngine::newDate(qsreal value)
762{
763 Q_D(QScriptEngine);
764 QScriptValueImpl v;
765 d->dateConstructor->newDate(&v, value);
766 return d->toPublic(v);
767}
768
769/*!
770 Creates a QtScript object of class Date from the given \a value.
771
772 \sa QScriptValue::toDateTime()
773*/
774QScriptValue QScriptEngine::newDate(const QDateTime &value)
775{
776 Q_D(QScriptEngine);
777 QScriptValueImpl v;
778 d->dateConstructor->newDate(&v, value);
779 return d->toPublic(v);
780}
781
782#ifndef QT_NO_QOBJECT
783/*!
784 Creates a QtScript object that represents a QObject class, using the
785 the given \a metaObject and constructor \a ctor.
786
787 Enums of \a metaObject (declared with Q_ENUMS) are available as
788 properties of the created QScriptValue. When the class is called as
789 a function, \a ctor will be called to create a new instance of the
790 class.
791
792 Example:
793
794 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 27
795
796 \sa newQObject(), scriptValueFromQMetaObject()
797*/
798QScriptValue QScriptEngine::newQMetaObject(
799 const QMetaObject *metaObject, const QScriptValue &ctor)
800{
801 Q_D(QScriptEngine);
802 QScriptValueImpl v;
803 d->qmetaObjectConstructor->newQMetaObject(&v, metaObject, d->toImpl(ctor));
804 return d->toPublic(v);
805}
806
807/*!
808 \fn QScriptValue QScriptEngine::scriptValueFromQMetaObject()
809
810 Creates a QScriptValue that represents the Qt class \c{T}.
811
812 This function is used in combination with one of the
813 Q_SCRIPT_DECLARE_QMETAOBJECT() macro. Example:
814
815 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 13
816
817 \warning This function is not available with MSVC 6. Use
818 qScriptValueFromQMetaObject() instead if you need to support that version
819 of the compiler.
820
821 \sa QScriptEngine::newQMetaObject()
822*/
823
824/*!
825 \fn QScriptValue qScriptValueFromQMetaObject(QScriptEngine *engine)
826 \since 4.3
827 \relates QScriptEngine
828
829 Uses \a engine to create a QScriptValue that represents the Qt class
830 \c{T}.
831
832 This function is equivalent to
833 QScriptEngine::scriptValueFromQMetaObject(). It is provided as a
834 work-around for MSVC 6, which doesn't support member template
835 functions.
836
837 \sa QScriptEngine::newQMetaObject()
838*/
839#endif // QT_NO_QOBJECT
840
841/*!
842 \obsolete
843
844 Returns true if \a program can be evaluated; i.e. the code is
845 sufficient to determine whether it appears to be a syntactically
846 correct program, or contains a syntax error.
847
848 This function returns false if \a program is incomplete; i.e. the
849 input is syntactically correct up to the point where the input is
850 terminated.
851
852 Note that this function only does a static check of \a program;
853 e.g. it does not check whether references to variables are
854 valid, and so on.
855
856 A typical usage of canEvaluate() is to implement an interactive
857 interpreter for QtScript. The user is repeatedly queried for
858 individual lines of code; the lines are concatened internally, and
859 only when canEvaluate() returns true for the resulting program is it
860 passed to evaluate().
861
862 The following are some examples to illustrate the behavior of
863 canEvaluate(). (Note that all example inputs are assumed to have an
864 explicit newline as their last character, since otherwise the
865 QtScript parser would automatically insert a semi-colon character at
866 the end of the input, and this could cause canEvaluate() to produce
867 different results.)
868
869 Given the input
870 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 14
871 canEvaluate() will return true, since the program appears to be complete.
872
873 Given the input
874 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 15
875 canEvaluate() will return false, since the if-statement is not complete,
876 but is syntactically correct so far.
877
878 Given the input
879 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 16
880 canEvaluate() will return true, but evaluate() will throw a
881 SyntaxError given the same input.
882
883 Given the input
884 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 17
885 canEvaluate() will return true, even though the code is clearly not
886 syntactically valid QtScript code. evaluate() will throw a
887 SyntaxError when this code is evaluated.
888
889 Given the input
890 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 18
891 canEvaluate() will return true, but evaluate() will throw a
892 ReferenceError if \c{foo} is not defined in the script
893 environment.
894
895 \sa evaluate(), checkSyntax()
896*/
897bool QScriptEngine::canEvaluate(const QString &program) const
898{
899 return QScriptEnginePrivate::canEvaluate(program);
900}
901
902/*!
903 \since 4.5
904
905 Checks the syntax of the given \a program. Returns a
906 QScriptSyntaxCheckResult object that contains the result of the check.
907*/
908QScriptSyntaxCheckResult QScriptEngine::checkSyntax(const QString &program)
909{
910 return QScriptEnginePrivate::checkSyntax(program);
911}
912
913/*!
914 Evaluates \a program, using \a lineNumber as the base line number,
915 and returns the result of the evaluation.
916
917 The script code will be evaluated in the current context.
918
919 The evaluation of \a program can cause an exception in the
920 engine; in this case the return value will be the exception
921 that was thrown (typically an \c{Error} object). You can call
922 hasUncaughtException() to determine if an exception occurred in
923 the last call to evaluate().
924
925 \a lineNumber is used to specify a starting line number for \a
926 program; line number information reported by the engine that pertain
927 to this evaluation (e.g. uncaughtExceptionLineNumber()) will be
928 based on this argument. For example, if \a program consists of two
929 lines of code, and the statement on the second line causes a script
930 exception, uncaughtExceptionLineNumber() would return the given \a
931 lineNumber plus one. When no starting line number is specified, line
932 numbers will be 1-based.
933
934 \a fileName is used for error reporting. For example in error objects
935 the file name is accessible through the "fileName" property if it's
936 provided with this function.
937
938 \sa canEvaluate(), hasUncaughtException(), isEvaluating(), abortEvaluation()
939*/
940QScriptValue QScriptEngine::evaluate(const QString &program, const QString &fileName, int lineNumber)
941{
942 Q_D(QScriptEngine);
943 QScriptContextPrivate *ctx_p = d->currentContext();
944 d->evaluate(ctx_p, program, lineNumber, fileName);
945 return d->toPublic(ctx_p->m_result);
946}
947
948/*!
949 Returns the current context.
950
951 The current context is typically accessed to retrieve the arguments
952 and `this' object in native functions; for convenience, it is
953 available as the first argument in QScriptEngine::FunctionSignature.
954*/
955QScriptContext *QScriptEngine::currentContext() const
956{
957 Q_D(const QScriptEngine);
958 return QScriptContextPrivate::get(d->currentContext());
959}
960
961/*!
962 Enters a new execution context and returns the associated
963 QScriptContext object.
964
965 Once you are done with the context, you should call popContext() to
966 restore the old context.
967
968 By default, the `this' object of the new context is the Global Object.
969 The context's \l{QScriptContext::callee()}{callee}() will be invalid.
970
971 This function is useful when you want to evaluate script code
972 as if it were the body of a function. You can use the context's
973 \l{QScriptContext::activationObject()}{activationObject}() to initialize
974 local variables that will be available to scripts. Example:
975
976 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 19
977
978 In the above example, the new variable "tmp" defined in the script
979 will be local to the context; in other words, the script doesn't
980 have any effect on the global environment.
981
982 \sa popContext()
983*/
984QScriptContext *QScriptEngine::pushContext()
985{
986 Q_D(QScriptEngine);
987 QScriptContextPrivate *ctx_p = d->pushContext();
988 ctx_p->setThisObject(d->globalObject());
989 QScriptValueImpl activation;
990 d->newActivation(&activation);
991 activation.setScope(d->globalObject());
992 ctx_p->setActivationObject(activation);
993 return QScriptContextPrivate::get(ctx_p);
994}
995
996/*!
997 Pops the current execution context and restores the previous one.
998 This function must be used in conjunction with pushContext().
999
1000 \sa pushContext()
1001*/
1002void QScriptEngine::popContext()
1003{
1004 Q_D(QScriptEngine);
1005 if (d->currentContext() && d->currentContext()->parentContext())
1006 d->popContext();
1007}
1008
1009/*!
1010 Returns true if the last script evaluation resulted in an uncaught
1011 exception; otherwise returns false.
1012
1013 The exception state is cleared when evaluate() is called.
1014
1015 \sa uncaughtException(), uncaughtExceptionLineNumber(),
1016 uncaughtExceptionBacktrace()
1017*/
1018bool QScriptEngine::hasUncaughtException() const
1019{
1020 Q_D(const QScriptEngine);
1021 return d->hasUncaughtException();
1022}
1023
1024/*!
1025 Returns the current uncaught exception, or an invalid QScriptValue
1026 if there is no uncaught exception.
1027
1028 The exception value is typically an \c{Error} object; in that case,
1029 you can call toString() on the return value to obtain an error
1030 message.
1031
1032 \sa hasUncaughtException(), uncaughtExceptionLineNumber(),
1033 uncaughtExceptionBacktrace()
1034*/
1035QScriptValue QScriptEngine::uncaughtException() const
1036{
1037 Q_D(const QScriptEngine);
1038 return const_cast<QScriptEnginePrivate*>(d)->toPublic(d->uncaughtException());
1039}
1040
1041/*!
1042 Returns the line number where the last uncaught exception occurred.
1043
1044 Line numbers are 1-based, unless a different base was specified as
1045 the second argument to evaluate().
1046
1047 \sa hasUncaughtException(), uncaughtExceptionBacktrace()
1048*/
1049int QScriptEngine::uncaughtExceptionLineNumber() const
1050{
1051 return QScriptContextPrivate::get(currentContext())->errorLineNumber;
1052}
1053
1054/*!
1055 Returns a human-readable backtrace of the last uncaught exception.
1056
1057 Each line is of the form \c{<function-name>(<arguments>)@<file-name>:<line-number>}.
1058
1059 \sa uncaughtException()
1060*/
1061QStringList QScriptEngine::uncaughtExceptionBacktrace() const
1062{
1063 Q_D(const QScriptEngine);
1064 return d->uncaughtExceptionBacktrace();
1065}
1066
1067/*!
1068 \since 4.4
1069
1070 Clears any uncaught exceptions in this engine.
1071
1072 \sa hasUncaughtException()
1073*/
1074void QScriptEngine::clearExceptions()
1075{
1076 Q_D(QScriptEngine);
1077 d->clearExceptions();
1078}
1079
1080/*!
1081 Returns the default prototype associated with the given \a metaTypeId,
1082 or an invalid QScriptValue if no default prototype has been set.
1083
1084 \sa setDefaultPrototype()
1085*/
1086QScriptValue QScriptEngine::defaultPrototype(int metaTypeId) const
1087{
1088 Q_D(const QScriptEngine);
1089 return const_cast<QScriptEnginePrivate*>(d)->toPublic(d->defaultPrototype(metaTypeId));
1090}
1091
1092/*!
1093 Sets the default prototype of the C++ type identified by the given
1094 \a metaTypeId to \a prototype.
1095
1096 The default prototype provides a script interface for values of
1097 type \a metaTypeId when a value of that type is accessed from script
1098 code. Whenever the script engine (implicitly or explicitly) creates
1099 a QScriptValue from a value of type \a metaTypeId, the default
1100 prototype will be set as the QScriptValue's prototype.
1101
1102 The \a prototype object itself may be constructed using one of two
1103 principal techniques; the simplest is to subclass QScriptable, which
1104 enables you to define the scripting API of the type through QObject
1105 properties and slots. Another possibility is to create a script
1106 object by calling newObject(), and populate the object with the
1107 desired properties (e.g. native functions wrapped with
1108 newFunction()).
1109
1110 \sa defaultPrototype(), qScriptRegisterMetaType(), QScriptable, {Default Prototypes Example}
1111*/
1112void QScriptEngine::setDefaultPrototype(int metaTypeId, const QScriptValue &prototype)
1113{
1114 Q_D(QScriptEngine);
1115 d->setDefaultPrototype(metaTypeId, d->toImpl(prototype));
1116}
1117
1118/*!
1119 \typedef QScriptEngine::FunctionSignature
1120 \relates QScriptEngine
1121
1122 The function signature \c{QScriptValue f(QScriptContext *, QScriptEngine *)}.
1123
1124 A function with such a signature can be passed to
1125 QScriptEngine::newFunction() to wrap the function.
1126*/
1127
1128/*!
1129 \typedef QScriptEngine::FunctionWithArgSignature
1130 \relates QScriptEngine
1131
1132 The function signature \c{QScriptValue f(QScriptContext *, QScriptEngine *, void *)}.
1133
1134 A function with such a signature can be passed to
1135 QScriptEngine::newFunction() to wrap the function.
1136*/
1137
1138/*!
1139 \typedef QScriptEngine::MarshalFunction
1140 \internal
1141*/
1142
1143/*!
1144 \typedef QScriptEngine::DemarshalFunction
1145 \internal
1146*/
1147
1148/*!
1149 \internal
1150*/
1151QScriptValue QScriptEngine::create(int type, const void *ptr)
1152{
1153 Q_D(QScriptEngine);
1154 return d->toPublic(d->create(type, ptr));
1155}
1156
1157/*!
1158 \internal
1159*/
1160bool QScriptEngine::convert(const QScriptValue &value, int type, void *ptr)
1161{
1162 Q_D(QScriptEngine);
1163 return QScriptEnginePrivate::convert(d->toImpl(value), type, ptr, d);
1164}
1165
1166/*!
1167 \internal
1168*/
1169bool QScriptEngine::convertV2(const QScriptValue &value, int type, void *ptr)
1170{
1171 QScriptValueImpl impl = QScriptValuePrivate::valueOf(value);
1172 QScriptEnginePrivate *eng_p = QScriptEnginePrivate::get(value.engine());
1173 return QScriptEnginePrivate::convert(impl, type, ptr, eng_p);
1174}
1175
1176/*!
1177 \internal
1178*/
1179void QScriptEngine::registerCustomType(int type, MarshalFunction mf,
1180 DemarshalFunction df,
1181 const QScriptValue &prototype)
1182{
1183 Q_D(QScriptEngine);
1184 QScriptCustomTypeInfo info = d->m_customTypes.value(type);
1185 info.marshal = mf;
1186 info.demarshal = df;
1187 info.prototype = d->toImpl(prototype);
1188 d->m_customTypes.insert(type, info);
1189}
1190
1191/*!
1192 \since 4.5
1193
1194 Installs translator functions on the given \a object, or on the Global
1195 Object if no object is specified.
1196
1197 The relation between Qt Script translator functions and C++ translator
1198 functions is described in the following table:
1199
1200 \table
1201 \header \o Script Function \o Corresponding C++ Function
1202 \row \o qsTr() \o QObject::tr()
1203 \row \o QT_TR_NOOP() \o QT_TR_NOOP()
1204 \row \o qsTranslate() \o QCoreApplication::translate()
1205 \row \o QT_TRANSLATE_NOOP() \o QT_TRANSLATE_NOOP()
1206 \endtable
1207
1208 \sa {Internationalization with Qt}
1209*/
1210void QScriptEngine::installTranslatorFunctions(const QScriptValue &object)
1211{
1212 Q_D(QScriptEngine);
1213 QScriptValue target = object.isObject() ? object : globalObject();
1214 QScriptValueImpl impl = QScriptValuePrivate::valueOf(target);
1215 d->installTranslatorFunctions(impl);
1216}
1217
1218/*!
1219 Imports the given \a extension into this QScriptEngine. Returns
1220 undefinedValue() if the extension was successfully imported. You
1221 can call hasUncaughtException() to check if an error occurred; in
1222 that case, the return value is the value that was thrown by the
1223 exception (usually an \c{Error} object).
1224
1225 QScriptEngine ensures that a particular extension is only imported
1226 once; subsequent calls to importExtension() with the same extension
1227 name will do nothing and return undefinedValue().
1228
1229 \sa availableExtensions(), QScriptExtensionPlugin, {Creating QtScript Extensions}
1230*/
1231QScriptValue QScriptEngine::importExtension(const QString &extension)
1232{
1233 Q_D(QScriptEngine);
1234 return d->toPublic(d->importExtension(extension));
1235}
1236
1237/*!
1238 \since 4.4
1239
1240 Returns a list naming the available extensions that can be
1241 imported using the importExtension() function. This list includes
1242 extensions that have been imported.
1243
1244 \sa importExtension(), importedExtensions()
1245*/
1246QStringList QScriptEngine::availableExtensions() const
1247{
1248 Q_D(const QScriptEngine);
1249 return d->availableExtensions();
1250}
1251
1252/*!
1253 \since 4.4
1254
1255 Returns a list naming the extensions that have been imported
1256 using the importExtension() function.
1257
1258 \sa availableExtensions()
1259*/
1260QStringList QScriptEngine::importedExtensions() const
1261{
1262 Q_D(const QScriptEngine);
1263 return d->importedExtensions();
1264}
1265
1266/*! \fn QScriptValue QScriptEngine::toScriptValue(const T &value)
1267
1268 Creates a QScriptValue with the given \a value.
1269
1270 Note that the template type \c{T} must be known to QMetaType.
1271
1272 See \l{Conversion Between QtScript and C++ Types} for a
1273 description of the built-in type conversion provided by
1274 QtScript. By default, the types that are not specially handled by
1275 QtScript are represented as QVariants (e.g. the \a value is passed
1276 to newVariant()); you can change this behavior by installing your
1277 own type conversion functions with qScriptRegisterMetaType().
1278
1279 \warning This function is not available with MSVC 6. Use
1280 qScriptValueFromValue() instead if you need to support that
1281 version of the compiler.
1282
1283 \sa fromScriptValue(), qScriptRegisterMetaType()
1284*/
1285
1286/*! \fn T QScriptEngine::fromScriptValue(const QScriptValue &value)
1287
1288 Returns the given \a value converted to the template type \c{T}.
1289
1290 Note that \c{T} must be known to QMetaType.
1291
1292 See \l{Conversion Between QtScript and C++ Types} for a
1293 description of the built-in type conversion provided by
1294 QtScript.
1295
1296 \warning This function is not available with MSVC 6. Use
1297 qScriptValueToValue() or qscriptvalue_cast() instead if you need
1298 to support that version of the compiler.
1299
1300 \sa toScriptValue(), qScriptRegisterMetaType()
1301*/
1302
1303/*!
1304 \fn QScriptValue qScriptValueFromValue(QScriptEngine *engine, const T &value)
1305 \since 4.3
1306 \relates QScriptEngine
1307
1308 Creates a QScriptValue using the given \a engine with the given \a
1309 value of template type \c{T}.
1310
1311 This function is equivalent to QScriptEngine::toScriptValue().
1312 It is provided as a work-around for MSVC 6, which doesn't support
1313 member template functions.
1314
1315 \sa qScriptValueToValue()
1316*/
1317
1318/*!
1319 \fn T qScriptValueToValue<T>(const QScriptValue &value)
1320 \since 4.3
1321 \relates QScriptEngine
1322
1323 Returns the given \a value converted to the template type \c{T}.
1324
1325 This function is equivalent to QScriptEngine::fromScriptValue().
1326 It is provided as a work-around for MSVC 6, which doesn't
1327 support member template functions.
1328
1329 \sa qScriptValueFromValue()
1330*/
1331
1332/*!
1333 \fn QScriptValue qScriptValueFromSequence(QScriptEngine *engine, const Container &container)
1334 \since 4.3
1335 \relates QScriptEngine
1336
1337 Creates an array in the form of a QScriptValue using the given \a engine
1338 with the given \a container of template type \c{Container}.
1339
1340 The \c Container type must provide a \c const_iterator class to enable the
1341 contents of the container to be copied into the array.
1342
1343 Additionally, the type of each element in the sequence should be suitable
1344 for conversion to a QScriptValue.
1345 See \l{QtScript Module#Conversion Between QtScript and C++ Types}
1346 {Conversion Between QtScript and C++ Types} for more information about the
1347 restrictions on types that can be used with QScriptValue.
1348
1349 \sa qScriptValueFromValue()
1350*/
1351
1352/*!
1353 \fn void qScriptValueToSequence(const QScriptValue &value, Container &container)
1354 \since 4.3
1355 \relates QScriptEngine
1356
1357 Copies the elements in the sequence specified by \a value to the given
1358 \a container of template type \c{Container}.
1359
1360 The \a value used is typically an array, but any container can be copied
1361 as long as it provides a \c length property describing how many elements
1362 it contains.
1363
1364 Additionally, the type of each element in the sequence must be suitable
1365 for conversion to a C++ type from a QScriptValue.
1366 See \l{QtScript Module#Conversion Between QtScript and C++ Types}
1367 {Conversion Between QtScript and C++ Types} for more information about the
1368 restrictions on types that can be used with QScriptValue.
1369
1370 \sa qscriptvalue_cast()
1371*/
1372
1373/*!
1374 \fn T qscriptvalue_cast<T>(const QScriptValue &value)
1375 \since 4.3
1376 \relates QScriptValue
1377
1378 Returns the given \a value converted to the template type \c{T}.
1379
1380 \sa qScriptRegisterMetaType(), QScriptEngine::toScriptValue()
1381*/
1382
1383/*! \fn int qScriptRegisterMetaType(
1384 QScriptEngine *engine,
1385 QScriptValue (*toScriptValue)(QScriptEngine *, const T &t),
1386 void (*fromScriptValue)(const QScriptValue &, T &t),
1387 const QScriptValue &prototype = QScriptValue())
1388 \relates QScriptEngine
1389
1390 Registers the type \c{T} in the given \a engine. \a toScriptValue must
1391 be a function that will convert from a value of type \c{T} to a
1392 QScriptValue, and \a fromScriptValue a function that does the
1393 opposite. \a prototype, if valid, is the prototype that's set on
1394 QScriptValues returned by \a toScriptValue.
1395
1396 Returns the internal ID used by QMetaType.
1397
1398 You only need to call this function if you want to provide custom
1399 conversion of values of type \c{T}, i.e. if the default
1400 QVariant-based representation and conversion is not
1401 appropriate. (Note that custom QObject-derived types also fall in
1402 this category; e.g. for a QObject-derived class called MyObject,
1403 you probably want to define conversion functions for MyObject*
1404 that utilize QScriptEngine::newQObject() and
1405 QScriptValue::toQObject().)
1406
1407 If you only want to define a common script interface for values of
1408 type \c{T}, and don't care how those values are represented
1409 (i.e. storing them in QVariants is fine), use
1410 \l{QScriptEngine::setDefaultPrototype()}{setDefaultPrototype}()
1411 instead; this will minimize conversion costs.
1412
1413 You need to declare the custom type first with
1414 Q_DECLARE_METATYPE().
1415
1416 After a type has been registered, you can convert from a
1417 QScriptValue to that type using
1418 \l{QScriptEngine::fromScriptValue()}{fromScriptValue}(), and
1419 create a QScriptValue from a value of that type using
1420 \l{QScriptEngine::toScriptValue()}{toScriptValue}(). The engine
1421 will take care of calling the proper conversion function when
1422 calling C++ slots, and when getting or setting a C++ property;
1423 i.e. the custom type may be used seamlessly on both the C++ side
1424 and the script side.
1425
1426 The following is an example of how to use this function. We will
1427 specify custom conversion of our type \c{MyStruct}. Here's the C++
1428 type:
1429
1430 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 20
1431
1432 We must declare it so that the type will be known to QMetaType:
1433
1434 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 21
1435
1436 Next, the \c{MyStruct} conversion functions. We represent the
1437 \c{MyStruct} value as a script object and just copy the properties:
1438
1439 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 22
1440
1441 Now we can register \c{MyStruct} with the engine:
1442 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 23
1443
1444 Working with \c{MyStruct} values is now easy:
1445 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 24
1446
1447 If you want to be able to construct values of your custom type
1448 from script code, you have to register a constructor function for
1449 the type. For example:
1450
1451 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 25
1452
1453 \sa qScriptRegisterSequenceMetaType(), qRegisterMetaType()
1454*/
1455
1456/*!
1457 \macro Q_SCRIPT_DECLARE_QMETAOBJECT(QMetaObject, ArgType)
1458 \since 4.3
1459 \relates QScriptEngine
1460
1461 Declares the given \a QMetaObject. Used in combination with
1462 QScriptEngine::scriptValueFromQMetaObject() to make enums and
1463 instantiation of \a QMetaObject available to script code. The
1464 constructor generated by this macro takes a single argument of
1465 type \a ArgType; typically the argument is the parent type of the
1466 new instance, in which case \a ArgType is \c{QWidget*} or
1467 \c{QObject*}. Objects created by the constructor will have
1468 QScriptEngine::AutoOwnership ownership.
1469*/
1470
1471/*! \fn int qScriptRegisterSequenceMetaType(
1472 QScriptEngine *engine,
1473 const QScriptValue &prototype = QScriptValue())
1474 \relates QScriptEngine
1475
1476 Registers the sequence type \c{T} in the given \a engine. This
1477 function provides conversion functions that convert between \c{T}
1478 and Qt Script \c{Array} objects. \c{T} must provide a
1479 const_iterator class and begin(), end() and push_back()
1480 functions. If \a prototype is valid, it will be set as the
1481 prototype of \c{Array} objects due to conversion from \c{T};
1482 otherwise, the standard \c{Array} prototype will be used.
1483
1484 Returns the internal ID used by QMetaType.
1485
1486 You need to declare the container type first with
1487 Q_DECLARE_METATYPE(). If the element type isn't a standard Qt/C++
1488 type, it must be declared using Q_DECLARE_METATYPE() as well.
1489 Example:
1490
1491 \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 26
1492
1493 \sa qScriptRegisterMetaType()
1494*/
1495
1496/*!
1497 Runs the garbage collector.
1498
1499 The garbage collector will attempt to reclaim memory by locating and
1500 disposing of objects that are no longer reachable in the script
1501 environment.
1502
1503 Normally you don't need to call this function; the garbage collector
1504 will automatically be invoked when the QScriptEngine decides that
1505 it's wise to do so (i.e. when a certain number of new objects have
1506 been created). However, you can call this function to explicitly
1507 request that garbage collection should be performed as soon as
1508 possible.
1509*/
1510void QScriptEngine::collectGarbage()
1511{
1512 Q_D(QScriptEngine);
1513 d->gc();
1514}
1515
1516/*!
1517
1518 Sets the interval between calls to QCoreApplication::processEvents
1519 to \a interval milliseconds.
1520
1521 While the interpreter is running, all event processing is by default
1522 blocked. This means for instance that the gui will not be updated
1523 and timers will not be fired. To allow event processing during
1524 interpreter execution one can specify the processing interval to be
1525 a positive value, indicating the number of milliseconds between each
1526 time QCoreApplication::processEvents() is called.
1527
1528 The default value is -1, which disables event processing during
1529 interpreter execution.
1530
1531 You can use QCoreApplication::postEvent() to post an event that
1532 performs custom processing at the next interval. For example, you
1533 could keep track of the total running time of the script and call
1534 abortEvaluation() when you detect that the script has been running
1535 for a long time without completing.
1536
1537 \sa processEventsInterval()
1538*/
1539void QScriptEngine::setProcessEventsInterval(int interval)
1540{
1541 Q_D(QScriptEngine);
1542 d->m_processEventsInterval = interval;
1543}
1544
1545/*!
1546
1547 Returns the interval in milliseconds between calls to
1548 QCoreApplication::processEvents() while the interpreter is running.
1549
1550 \sa setProcessEventsInterval()
1551*/
1552int QScriptEngine::processEventsInterval() const
1553{
1554 Q_D(const QScriptEngine);
1555 return d->m_processEventsInterval;
1556}
1557
1558/*!
1559 \since 4.4
1560
1561 Returns true if this engine is currently evaluating a script,
1562 otherwise returns false.
1563
1564 \sa evaluate(), abortEvaluation()
1565*/
1566bool QScriptEngine::isEvaluating() const
1567{
1568 Q_D(const QScriptEngine);
1569 return d->m_evaluating;
1570}
1571
1572/*!
1573 \since 4.4
1574
1575 Aborts any script evaluation currently taking place in this engine.
1576 The given \a result is passed back as the result of the evaluation
1577 (i.e. it is returned from the call to evaluate() being aborted).
1578
1579 If the engine isn't evaluating a script (i.e. isEvaluating() returns
1580 false), this function does nothing.
1581
1582 Call this function if you need to abort a running script for some
1583 reason, e.g. when you have detected that the script has been
1584 running for several seconds without completing.
1585
1586 \sa evaluate(), isEvaluating(), setProcessEventsInterval()
1587*/
1588void QScriptEngine::abortEvaluation(const QScriptValue &result)
1589{
1590 Q_D(QScriptEngine);
1591 d->abortEvaluation(d->toImpl(result));
1592}
1593
1594#ifndef QT_NO_QOBJECT
1595
1596/*!
1597 \since 4.4
1598 \relates QScriptEngine
1599
1600 Creates a connection from the \a signal in the \a sender to the
1601 given \a function. If \a receiver is an object, it will act as the
1602 `this' object when the signal handler function is invoked. Returns
1603 true if the connection succeeds; otherwise returns false.
1604
1605 \sa qScriptDisconnect(), QScriptEngine::signalHandlerException()
1606*/
1607bool qScriptConnect(QObject *sender, const char *signal,
1608 const QScriptValue &receiver, const QScriptValue &function)
1609{
1610 if (!sender || !signal)
1611 return false;
1612 if (!function.isFunction())
1613 return false;
1614 if (receiver.isObject() && (receiver.engine() != function.engine()))
1615 return false;
1616 QScriptEnginePrivate *eng_p = QScriptEnginePrivate::get(function.engine());
1617 return eng_p->scriptConnect(sender, signal,
1618 eng_p->toImpl(receiver),
1619 eng_p->toImpl(function));
1620}
1621
1622/*!
1623 \since 4.4
1624 \relates QScriptEngine
1625
1626 Disconnects the \a signal in the \a sender from the given (\a
1627 receiver, \a function) pair. Returns true if the connection is
1628 successfully broken; otherwise returns false.
1629
1630 \sa qScriptConnect()
1631*/
1632bool qScriptDisconnect(QObject *sender, const char *signal,
1633 const QScriptValue &receiver, const QScriptValue &function)
1634{
1635 if (!sender || !signal)
1636 return false;
1637 if (!function.isFunction())
1638 return false;
1639 if (receiver.isObject() && (receiver.engine() != function.engine()))
1640 return false;
1641 QScriptEnginePrivate *eng_p = QScriptEnginePrivate::get(function.engine());
1642 return eng_p->scriptDisconnect(sender, signal,
1643 eng_p->toImpl(receiver),
1644 eng_p->toImpl(function));
1645}
1646
1647/*!
1648 \since 4.4
1649 \fn void QScriptEngine::signalHandlerException(const QScriptValue &exception)
1650
1651 This signal is emitted when a script function connected to a signal causes
1652 an \a exception.
1653
1654 \sa qScriptConnect()
1655*/
1656
1657QT_BEGIN_INCLUDE_NAMESPACE
1658#include "moc_qscriptengine.cpp"
1659QT_END_INCLUDE_NAMESPACE
1660
1661#endif // QT_NO_QOBJECT
1662
1663/*!
1664 \since 4.4
1665
1666 Installs the given \a agent on this engine. The agent will be
1667 notified of various events pertaining to script execution. This is
1668 useful when you want to find out exactly what the engine is doing,
1669 e.g. when evaluate() is called. The agent interface is the basis of
1670 tools like debuggers and profilers.
1671
1672 The engine maintains ownership of the \a agent.
1673
1674 Calling this function will replace the existing agent, if any.
1675
1676 \sa agent()
1677*/
1678void QScriptEngine::setAgent(QScriptEngineAgent *agent)
1679{
1680 Q_D(QScriptEngine);
1681 d->setAgent(agent);
1682}
1683
1684/*!
1685 \since 4.4
1686
1687 Returns the agent currently installed on this engine, or 0 if no
1688 agent is installed.
1689
1690 \sa setAgent()
1691*/
1692QScriptEngineAgent *QScriptEngine::agent() const
1693{
1694 Q_D(const QScriptEngine);
1695 return d->agent();
1696}
1697
1698/*!
1699 \since 4.4
1700
1701 Returns a handle that represents the given string, \a str.
1702
1703 QScriptString can be used to quickly look up properties, and
1704 compare property names, of script objects.
1705
1706 \sa QScriptValue::property()
1707*/
1708QScriptString QScriptEngine::toStringHandle(const QString &str)
1709{
1710 Q_D(QScriptEngine);
1711 return d->internedString(str);
1712}
1713
1714/*!
1715 \since 4.5
1716
1717 Converts the given \a value to an object, if such a conversion is
1718 possible; otherwise returns an invalid QScriptValue. The conversion
1719 is performed according to the following table:
1720
1721 \table
1722 \header \o Input Type \o Result
1723 \row \o Undefined \o An invalid QScriptValue.
1724 \row \o Null \o An invalid QScriptValue.
1725 \row \o Boolean \o A new Boolean object whose internal value is set to the value of the boolean.
1726 \row \o Number \o A new Number object whose internal value is set to the value of the number.
1727 \row \o String \o A new String object whose internal value is set to the value of the string.
1728 \row \o Object \o The result is the object itself (no conversion).
1729 \endtable
1730
1731 \sa newObject()
1732*/
1733QScriptValue QScriptEngine::toObject(const QScriptValue &value)
1734{
1735 Q_D(QScriptEngine);
1736 return d->toPublic(d->toObject(d->toImpl(value)));
1737}
1738
1739/*!
1740 \internal
1741
1742 Returns the object with the given \a id, or an invalid
1743 QScriptValue if there is no object with that id.
1744
1745 \sa QScriptValue::objectId()
1746*/
1747QScriptValue QScriptEngine::objectById(qint64 id) const
1748{
1749 Q_D(const QScriptEngine);
1750 return const_cast<QScriptEnginePrivate*>(d)->toPublic(d->objectById(id));
1751}
1752
1753/*!
1754 \since 4.5
1755 \class QScriptSyntaxCheckResult
1756
1757 \brief The QScriptSyntaxCheckResult class provides the result of a script syntax check.
1758
1759 \ingroup script
1760 \mainclass
1761
1762 QScriptSyntaxCheckResult is returned by QScriptEngine::checkSyntax() to
1763 provide information about the syntactical (in)correctness of a script.
1764*/
1765
1766/*!
1767 \enum QScriptSyntaxCheckResult::State
1768
1769 This enum specifies the state of a syntax check.
1770
1771 \value Error The program contains a syntax error.
1772 \value Intermediate The program is incomplete.
1773 \value Valid The program is a syntactically correct Qt Script program.
1774*/
1775
1776/*!
1777 Constructs a new QScriptSyntaxCheckResult from the \a other result.
1778*/
1779QScriptSyntaxCheckResult::QScriptSyntaxCheckResult(const QScriptSyntaxCheckResult &other)
1780 : d_ptr(other.d_ptr)
1781{
1782 if (d_ptr)
1783 d_ptr->ref.ref();
1784}
1785
1786/*!
1787 \internal
1788*/
1789QScriptSyntaxCheckResult::QScriptSyntaxCheckResult(QScriptSyntaxCheckResultPrivate *d)
1790 : d_ptr(d)
1791{
1792 if (d_ptr)
1793 d_ptr->ref.ref();
1794}
1795
1796/*!
1797 \internal
1798*/
1799QScriptSyntaxCheckResult::QScriptSyntaxCheckResult()
1800 : d_ptr(0)
1801{
1802}
1803
1804/*!
1805 Destroys this QScriptSyntaxCheckResult.
1806*/
1807QScriptSyntaxCheckResult::~QScriptSyntaxCheckResult()
1808{
1809 if (d_ptr && !d_ptr->ref.deref()) {
1810 delete d_ptr;
1811 d_ptr = 0;
1812 }
1813}
1814
1815/*!
1816 Returns the state of this QScriptSyntaxCheckResult.
1817*/
1818QScriptSyntaxCheckResult::State QScriptSyntaxCheckResult::state() const
1819{
1820 Q_D(const QScriptSyntaxCheckResult);
1821 return d->state;
1822}
1823
1824/*!
1825 Returns the error line number of this QScriptSyntaxCheckResult, or -1 if
1826 there is no error.
1827
1828 \sa state(), errorMessage()
1829*/
1830int QScriptSyntaxCheckResult::errorLineNumber() const
1831{
1832 Q_D(const QScriptSyntaxCheckResult);
1833 return d->errorLineNumber;
1834}
1835
1836/*!
1837 Returns the error column number of this QScriptSyntaxCheckResult, or -1 if
1838 there is no error.
1839
1840 \sa state(), errorLineNumber()
1841*/
1842int QScriptSyntaxCheckResult::errorColumnNumber() const
1843{
1844 Q_D(const QScriptSyntaxCheckResult);
1845 return d->errorColumnNumber;
1846}
1847
1848/*!
1849 Returns the error message of this QScriptSyntaxCheckResult, or an empty
1850 string if there is no error.
1851
1852 \sa state(), errorLineNumber()
1853*/
1854QString QScriptSyntaxCheckResult::errorMessage() const
1855{
1856 Q_D(const QScriptSyntaxCheckResult);
1857 return d->errorMessage;
1858}
1859
1860/*!
1861 Assigns the \a other result to this QScriptSyntaxCheckResult, and returns a
1862 reference to this QScriptSyntaxCheckResult.
1863*/
1864QScriptSyntaxCheckResult &QScriptSyntaxCheckResult::operator=(const QScriptSyntaxCheckResult &other)
1865{
1866 if (d_ptr == other.d_ptr)
1867 return *this;
1868 if (d_ptr && !d_ptr->ref.deref()) {
1869 delete d_ptr;
1870 d_ptr = 0;
1871 }
1872 d_ptr = other.d_ptr;
1873 if (d_ptr)
1874 d_ptr->ref.ref();
1875 return *this;
1876}
1877
1878QT_END_NAMESPACE
1879
1880#endif // QT_NO_SCRIPT
Note: See TracBrowser for help on using the repository browser.