本文整理汇总了C++中QScriptEngine类的典型用法代码示例。如果您正苦于以下问题:C++ QScriptEngine类的具体用法?C++ QScriptEngine怎么用?C++ QScriptEngine使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QScriptEngine类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: loadPlayerScript
bool loadPlayerScript(QString path, int player, int difficulty)
{
ASSERT_OR_RETURN(false, player < MAX_PLAYERS, "Player index %d out of bounds", player);
QScriptEngine *engine = new QScriptEngine();
UDWORD size;
char *bytes = NULL;
if (!loadFile(path.toAscii().constData(), &bytes, &size))
{
debug(LOG_ERROR, "Failed to read script file \"%s\"", path.toAscii().constData());
return false;
}
QString source = QString::fromAscii(bytes, size);
free(bytes);
QScriptSyntaxCheckResult syntax = QScriptEngine::checkSyntax(source);
ASSERT_OR_RETURN(false, syntax.state() == QScriptSyntaxCheckResult::Valid, "Syntax error in %s line %d: %s",
path.toAscii().constData(), syntax.errorLineNumber(), syntax.errorMessage().toAscii().constData());
// Special functions
engine->globalObject().setProperty("setTimer", engine->newFunction(js_setTimer));
engine->globalObject().setProperty("queue", engine->newFunction(js_queue));
engine->globalObject().setProperty("removeTimer", engine->newFunction(js_removeTimer));
engine->globalObject().setProperty("include", engine->newFunction(js_include));
engine->globalObject().setProperty("bind", engine->newFunction(js_bind));
// Special global variables
//== \item[version] Current version of the game, set in \emph{major.minor} format.
engine->globalObject().setProperty("version", "3.2", QScriptValue::ReadOnly | QScriptValue::Undeletable);
//== \item[selectedPlayer] The player ontrolled by the client on which the script runs.
engine->globalObject().setProperty("selectedPlayer", selectedPlayer, QScriptValue::ReadOnly | QScriptValue::Undeletable);
//== \item[gameTime] The current game time. Updated before every invokation of a script.
engine->globalObject().setProperty("gameTime", gameTime, QScriptValue::ReadOnly | QScriptValue::Undeletable);
//== \item[difficulty] The currently set campaign difficulty, or the current AI's difficulty setting. It will be one of
//== EASY, MEDIUM, HARD or INSANE.
engine->globalObject().setProperty("difficulty", difficulty, QScriptValue::ReadOnly | QScriptValue::Undeletable);
//== \item[mapName] The name of the current map.
engine->globalObject().setProperty("mapName", game.map, QScriptValue::ReadOnly | QScriptValue::Undeletable);
//== \item[baseType] The type of base that the game starts with. It will be one of CAMP_CLEAN, CAMP_BASE or CAMP_WALLS.
engine->globalObject().setProperty("baseType", game.base, QScriptValue::ReadOnly | QScriptValue::Undeletable);
//== \item[alliancesType] The type of alliances permitted in this game. It will be one of NO_ALLIANCES, ALLIANCES or ALLIANCES_TEAMS.
engine->globalObject().setProperty("alliancesType", game.alliance, QScriptValue::ReadOnly | QScriptValue::Undeletable);
//== \item[powerType] The power level set for this game.
engine->globalObject().setProperty("powerType", game.power, QScriptValue::ReadOnly | QScriptValue::Undeletable);
//== \item[maxPlayers] The number of active players in this game.
engine->globalObject().setProperty("maxPlayers", game.maxPlayers, QScriptValue::ReadOnly | QScriptValue::Undeletable);
//== \item[scavengers] Whether or not scavengers are activated in this game.
engine->globalObject().setProperty("scavengers", game.scavengers, QScriptValue::ReadOnly | QScriptValue::Undeletable);
//== \item[mapWidth] Width of map in tiles.
engine->globalObject().setProperty("mapWidth", mapWidth, QScriptValue::ReadOnly | QScriptValue::Undeletable);
//== \item[mapHeight] Height of map in tiles.
engine->globalObject().setProperty("mapHeight", mapHeight, QScriptValue::ReadOnly | QScriptValue::Undeletable);
//== \item[scavengerPlayer] Index of scavenger player. (3.2+ only)
engine->globalObject().setProperty("scavengerPlayer", scavengerPlayer(), QScriptValue::ReadOnly | QScriptValue::Undeletable);
// Regular functions
registerFunctions(engine);
// Remember internal, reserved names
QScriptValueIterator it(engine->globalObject());
while (it.hasNext())
{
it.next();
internalNamespace.insert(it.name(), 1);
}
// We need to always save the 'me' special variable.
//== \item[me] The player the script is currently running as.
engine->globalObject().setProperty("me", player, QScriptValue::ReadOnly | QScriptValue::Undeletable);
QScriptValue result = engine->evaluate(source, path);
ASSERT_OR_RETURN(false, !engine->hasUncaughtException(), "Uncaught exception at line %d, file %s: %s",
engine->uncaughtExceptionLineNumber(), path.toAscii().constData(), result.toString().toAscii().constData());
// Register script
scripts.push_back(engine);
debug(LOG_SAVE, "Created script engine %d for player %d from %s", scripts.size() - 1, player, path.toUtf8().constData());
return true;
}
示例2: QScriptEngine
QScriptEngine * ScriptEngineWorker::createScriptEngine(bool supportThreads)
{
QScriptEngine *engine = new QScriptEngine();
QLOG_INFO() << "New script engine" << engine << ", thread:" << QThread::currentThread();
Scriptable<BatteryInterface>::registerMetatype(engine);
Scriptable<ColorSensorInterface>::registerMetatype(engine);
Scriptable<DisplayInterface>::registerMetatype(engine);
Scriptable<EncoderInterface>::registerMetatype(engine);
Scriptable<EventCodeInterface>::registerMetatype(engine);
Scriptable<EventDeviceInterface>::registerMetatype(engine);
Scriptable<EventInterface>::registerMetatype(engine);
Scriptable<GamepadInterface>::registerMetatype(engine);
Scriptable<FifoInterface>::registerMetatype(engine);
Scriptable<KeysInterface>::registerMetatype(engine);
Scriptable<LedInterface>::registerMetatype(engine);
Scriptable<LineSensorInterface>::registerMetatype(engine);
Scriptable<MailboxInterface>::registerMetatype(engine);
Scriptable<MotorInterface>::registerMetatype(engine);
Scriptable<ObjectSensorInterface>::registerMetatype(engine);
Scriptable<SensorInterface>::registerMetatype(engine);
Scriptable<SoundSensorInterface>::registerMetatype(engine);
Scriptable<QTimer>::registerMetatype(engine);
qScriptRegisterMetaType(engine, timeValToScriptValue, timeValFromScriptValue);
Scriptable<VectorSensorInterface>::registerMetatype(engine);
qScriptRegisterSequenceMetaType<QVector<int>>(engine);
qScriptRegisterSequenceMetaType<QStringList>(engine);
engine->globalObject().setProperty("brick", engine->newQObject(&mBrick));
engine->globalObject().setProperty("script", engine->newQObject(&mScriptControl));
if (mMailbox) {
engine->globalObject().setProperty("mailbox", engine->newQObject(mMailbox));
}
// Gamepad can still be accessed from script as brick.gamepad(), 'gamepad' variable is here for backwards
// compatibility.
if (mBrick.gamepad()) {
engine->globalObject().setProperty("gamepad", engine->newQObject(mBrick.gamepad()));
}
if (supportThreads) {
engine->globalObject().setProperty("Threading", engine->newQObject(&mThreading));
}
evalSystemJs(engine);
engine->setProcessEventsInterval(1);
return engine;
}
示例3: QString
/**
* Handles the loading of trashed notes
*
* @brief OwnCloudService::handleTrashedLoading
* @param data
*/
void OwnCloudService::handleTrashedLoading(QString data) {
// check if we get any data at all
if (data == "") {
if (QMessageBox::critical(
0, "ownCloud server connection error!",
"Cannot connect to the ownCloud server!<br />"
"Please check your configuration in the settings!",
"Open &settings", "&Cancel", QString::null, 0, 1) == 0) {
mainWindow->openSettingsDialog();
}
return;
}
// we have to add [], so the string can be parsed as JSON
data = QString("[") + data + QString("]");
QScriptEngine engine;
QScriptValue result = engine.evaluate(data);
// get a possible error messages
QString message = result.property(0).property("message").toString();
// check if we got an error message
if (message != "") {
if (QMessageBox::critical(
0, "ownCloud server connection error!",
"ownCloud server error: <strong>" + message + "</strong><br />"
"Please check your configuration in the settings!",
"Open &settings", "&Cancel", QString::null, 0, 1) == 0) {
mainWindow->openSettingsDialog();
}
return;
}
// get the directory to check if everything is all right
QString directory = result.property(0).property("directory").toString();
// check if we got no usefull data
if (directory == "") {
if (QMessageBox::critical(
0, "ownCloud server connection error!",
"QOwnNotes was unable to connect to your ownCloud server! "
"Please check the configuration in the settings!",
"Open &settings", "&Cancel", QString::null, 0, 1) == 0) {
mainWindow->openSettingsDialog();
}
return;
}
// get the versions
QScriptValue notes = result.property(0).property("notes");
// check if we got no usefull data
if (notes.toString() == "") {
QMessageBox::information(0, "no other version",
"There are no trashed notes on the server.");
return;
}
TrashDialog *dialog = new TrashDialog(notes, mainWindow);
dialog->exec();
}
示例4: getAndSetProperty
void tst_QScriptClass::getAndSetProperty()
{
QScriptEngine eng;
TestClass cls(&eng);
QScriptValue obj1 = eng.newObject(&cls);
QScriptValue obj2 = eng.newObject(&cls);
QScriptString foo = eng.toStringHandle("foo");
QScriptString bar = eng.toStringHandle("bar");
// should behave just like normal
for (int x = 0; x < 2; ++x) {
QScriptValue &o = (x == 0) ? obj1 : obj2;
for (int y = 0; y < 2; ++y) {
QScriptString &s = (y == 0) ? foo : bar;
// read property
cls.clearReceivedArgs();
QScriptValue ret = o.property(s);
QVERIFY(!ret.isValid());
QVERIFY(cls.lastQueryPropertyObject().strictlyEquals(o));
QVERIFY(cls.lastQueryPropertyName() == s);
QVERIFY(!cls.lastPropertyObject().isValid());
QVERIFY(!cls.lastSetPropertyObject().isValid());
QVERIFY(cls.lastQueryPropertyFlags() == QScriptClass::HandlesReadAccess);
// write property
cls.clearReceivedArgs();
QScriptValue num(&eng, 123);
o.setProperty(s, num);
QVERIFY(cls.lastQueryPropertyObject().strictlyEquals(o));
QVERIFY(cls.lastQueryPropertyName() == s);
QVERIFY(!cls.lastPropertyObject().isValid());
QVERIFY(!cls.lastSetPropertyObject().isValid());
// ### ideally, we should only test for HandlesWriteAccess in this case
QVERIFY(cls.lastQueryPropertyFlags() == (QScriptClass::HandlesReadAccess | QScriptClass::HandlesWriteAccess));
// re-read property
cls.clearReceivedArgs();
QVERIFY(o.property(s).strictlyEquals(num));
QVERIFY(!cls.lastQueryPropertyObject().isValid());
}
}
// add a custom property
QScriptString foo2 = eng.toStringHandle("foo2");
const uint foo2Id = 123;
const QScriptValue::PropertyFlags foo2Pflags = QScriptValue::Undeletable;
QScriptValue foo2Value(&eng, 456);
cls.addCustomProperty(foo2, QScriptClass::HandlesReadAccess | QScriptClass::HandlesWriteAccess,
foo2Id, foo2Pflags, foo2Value);
{
// read property
cls.clearReceivedArgs();
{
QScriptValue ret = obj1.property(foo2);
QVERIFY(ret.strictlyEquals(foo2Value));
}
QVERIFY(cls.lastQueryPropertyObject().strictlyEquals(obj1));
QVERIFY(cls.lastQueryPropertyName() == foo2);
QVERIFY(cls.lastPropertyObject().strictlyEquals(obj1));
QVERIFY(cls.lastPropertyName() == foo2);
QCOMPARE(cls.lastPropertyId(), foo2Id);
// read flags
cls.clearReceivedArgs();
QCOMPARE(obj1.propertyFlags(foo2), foo2Pflags);
QVERIFY(cls.lastQueryPropertyObject().strictlyEquals(obj1));
QVERIFY(cls.lastQueryPropertyName() == foo2);
QVERIFY(!cls.lastPropertyObject().isValid());
QVERIFY(cls.lastPropertyFlagsObject().strictlyEquals(obj1));
QVERIFY(cls.lastPropertyFlagsName() == foo2);
QCOMPARE(cls.lastPropertyFlagsId(), foo2Id);
// write property
cls.clearReceivedArgs();
QScriptValue newFoo2Value(&eng, 789);
obj1.setProperty(foo2, newFoo2Value);
QVERIFY(cls.lastQueryPropertyObject().strictlyEquals(obj1));
QVERIFY(cls.lastQueryPropertyName() == foo2);
// read property again
cls.clearReceivedArgs();
{
QScriptValue ret = obj1.property(foo2);
QVERIFY(ret.strictlyEquals(newFoo2Value));
}
QVERIFY(cls.lastQueryPropertyObject().strictlyEquals(obj1));
QVERIFY(cls.lastQueryPropertyName() == foo2);
QVERIFY(cls.lastPropertyObject().strictlyEquals(obj1));
QVERIFY(cls.lastPropertyName() == foo2);
QCOMPARE(cls.lastPropertyId(), foo2Id);
}
}
示例5: switch
/*!
Applies the given \a command to the given \a backend.
*/
QScriptDebuggerResponse QScriptDebuggerCommandExecutor::execute(
QScriptDebuggerBackend *backend,
const QScriptDebuggerCommand &command)
{
QScriptDebuggerResponse response;
switch (command.type()) {
case QScriptDebuggerCommand::None:
break;
case QScriptDebuggerCommand::Interrupt:
backend->interruptEvaluation();
break;
case QScriptDebuggerCommand::Continue:
if (backend->engine()->isEvaluating()) {
backend->continueEvalution();
response.setAsync(true);
}
break;
case QScriptDebuggerCommand::StepInto: {
QVariant attr = command.attribute(QScriptDebuggerCommand::StepCount);
int count = attr.isValid() ? attr.toInt() : 1;
backend->stepInto(count);
response.setAsync(true);
} break;
case QScriptDebuggerCommand::StepOver: {
QVariant attr = command.attribute(QScriptDebuggerCommand::StepCount);
int count = attr.isValid() ? attr.toInt() : 1;
backend->stepOver(count);
response.setAsync(true);
} break;
case QScriptDebuggerCommand::StepOut:
backend->stepOut();
response.setAsync(true);
break;
case QScriptDebuggerCommand::RunToLocation:
backend->runToLocation(command.fileName(), command.lineNumber());
response.setAsync(true);
break;
case QScriptDebuggerCommand::RunToLocationByID:
backend->runToLocation(command.scriptId(), command.lineNumber());
response.setAsync(true);
break;
case QScriptDebuggerCommand::ForceReturn: {
int contextIndex = command.contextIndex();
QScriptDebuggerValue value = command.scriptValue();
QScriptEngine *engine = backend->engine();
QScriptValue realValue = value.toScriptValue(engine);
backend->returnToCaller(contextIndex, realValue);
response.setAsync(true);
} break;
case QScriptDebuggerCommand::Resume:
backend->resume();
response.setAsync(true);
break;
case QScriptDebuggerCommand::SetBreakpoint: {
QScriptBreakpointData data = command.breakpointData();
if (!data.isValid())
data = QScriptBreakpointData(command.fileName(), command.lineNumber());
int id = backend->setBreakpoint(data);
response.setResult(id);
} break;
case QScriptDebuggerCommand::DeleteBreakpoint: {
int id = command.breakpointId();
if (!backend->deleteBreakpoint(id))
response.setError(QScriptDebuggerResponse::InvalidBreakpointID);
} break;
case QScriptDebuggerCommand::DeleteAllBreakpoints:
backend->deleteAllBreakpoints();
break;
case QScriptDebuggerCommand::GetBreakpoints: {
QScriptBreakpointMap bps = backend->breakpoints();
if (!bps.isEmpty())
response.setResult(bps);
} break;
case QScriptDebuggerCommand::GetBreakpointData: {
int id = command.breakpointId();
QScriptBreakpointData data = backend->breakpointData(id);
if (data.isValid())
response.setResult(data);
else
response.setError(QScriptDebuggerResponse::InvalidBreakpointID);
} break;
case QScriptDebuggerCommand::SetBreakpointData: {
//.........这里部分代码省略.........
示例6: initEcma
void REcmaBlock::initEcma(QScriptEngine& engine, QScriptValue* proto
)
{
bool protoCreated = false;
if(proto == NULL) {
proto = new QScriptValue(engine.newVariant(qVariantFromValue(
(RBlock*) 0)));
protoCreated = true;
}
// primary base class RObject:
QScriptValue dpt = engine.defaultPrototype(
qMetaTypeId<RObject*>());
if (dpt.isValid()) {
proto->setPrototype(dpt);
}
/*
*/
QScriptValue fun;
// toString:
REcmaHelper::registerFunction(&engine, proto, toString, "toString");
// destroy:
REcmaHelper::registerFunction(&engine, proto, destroy, "destroy");
// conversion for base class RObject
REcmaHelper::registerFunction(&engine, proto, getRObject, "getRObject");
// get class name
REcmaHelper::registerFunction(&engine, proto, getClassName, "getClassName");
// conversion to all base classes (multiple inheritance):
REcmaHelper::registerFunction(&engine, proto, getBaseClasses, "getBaseClasses");
// properties:
// methods:
REcmaHelper::registerFunction(&engine, proto, getType, "getType");
REcmaHelper::registerFunction(&engine, proto, clone, "clone");
REcmaHelper::registerFunction(&engine, proto, getName, "getName");
REcmaHelper::registerFunction(&engine, proto, setName, "setName");
REcmaHelper::registerFunction(&engine, proto, isFrozen, "isFrozen");
REcmaHelper::registerFunction(&engine, proto, setFrozen, "setFrozen");
REcmaHelper::registerFunction(&engine, proto, isAnonymous, "isAnonymous");
REcmaHelper::registerFunction(&engine, proto, setAnonymous, "setAnonymous");
REcmaHelper::registerFunction(&engine, proto, setOrigin, "setOrigin");
REcmaHelper::registerFunction(&engine, proto, getOrigin, "getOrigin");
REcmaHelper::registerFunction(&engine, proto, getProperty, "getProperty");
REcmaHelper::registerFunction(&engine, proto, setProperty, "setProperty");
REcmaHelper::registerFunction(&engine, proto, isSelectedForPropertyEditing, "isSelectedForPropertyEditing");
engine.setDefaultPrototype(
qMetaTypeId<RBlock*>(), *proto);
QScriptValue ctor = engine.newFunction(createEcma, *proto, 2);
// static methods:
REcmaHelper::registerFunction(&engine, &ctor, init, "init");
// static properties:
ctor.setProperty("PropertyCustom",
qScriptValueFromValue(&engine, RBlock::PropertyCustom),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertyName",
//.........这里部分代码省略.........
示例7: initEcma
void REcmaFileImporterAdapter::initEcma(QScriptEngine& engine, QScriptValue* proto
)
{
bool protoCreated = false;
if(proto == NULL){
proto = new QScriptValue(engine.newVariant(qVariantFromValue(
(RFileImporterAdapter*) 0)));
protoCreated = true;
}
// primary base class RFileImporter:
QScriptValue dpt = engine.defaultPrototype(
qMetaTypeId<RFileImporter*>());
if (dpt.isValid()) {
proto->setPrototype(dpt);
}
/*
*/
QScriptValue fun;
// toString:
REcmaHelper::registerFunction(&engine, proto, toString, "toString");
// destroy:
REcmaHelper::registerFunction(&engine, proto, destroy, "destroy");
// conversion for base class RFileImporter
REcmaHelper::registerFunction(&engine, proto, getRFileImporter, "getRFileImporter");
// conversion for base class RImporter
REcmaHelper::registerFunction(&engine, proto, getRImporter, "getRImporter");
// get class name
REcmaHelper::registerFunction(&engine, proto, getClassName, "getClassName");
// conversion to all base classes (multiple inheritance):
REcmaHelper::registerFunction(&engine, proto, getBaseClasses, "getBaseClasses");
// properties:
// methods:
REcmaHelper::registerFunction(&engine, proto, importFile, "importFile");
engine.setDefaultPrototype(
qMetaTypeId<RFileImporterAdapter*>(), *proto);
QScriptValue ctor = engine.newFunction(createEcma, *proto, 2);
// static methods:
// static properties:
// enum values:
// enum conversions:
// init class:
engine.globalObject().setProperty("RFileImporterAdapter",
ctor, QScriptValue::SkipInEnumeration);
if( protoCreated ){
delete proto;
}
}
示例8: parseFile
void PostalCodeModel::parseFile( const QByteArray& file )
{
QScriptValue data;
QScriptEngine engine;
// Qt requires parentheses around json code
data = engine.evaluate( "(" + QString( file ) + ")" );
// Parse if any result exists
if ( data.property( "postalCodes" ).isArray() ) {
QScriptValueIterator iterator( data.property( "postalCodes" ) );
// Add items to the list
while ( iterator.hasNext() ) {
iterator.next();
QString const placeName = QString::fromUtf8(
iterator.value().property( "placeName" ).toString().toStdString().c_str());
QString const adminName1 = QString::fromUtf8(
iterator.value().property( "adminName1" ).toString().toStdString().c_str());
QString const adminName2 = QString::fromUtf8(
iterator.value().property( "adminName2" ).toString().toStdString().c_str());
QString const adminName3 = QString::fromUtf8(
iterator.value().property( "adminName3" ).toString().toStdString().c_str());
QString const postalCode = iterator.value().property( "postalCode" ).toString();
QString const countryCode = iterator.value().property( "countryCode" ).toString();
double const longitude = iterator.value().property( "lng" ).toNumber();
double const latitude = iterator.value().property( "lat" ).toNumber();
QString const id = "postalCode_" + countryCode + postalCode;
if ( !id.isEmpty() ) {
QString tooltip;
if ( !placeName.isEmpty() ) {
tooltip += placeName + " ";
}
addLine( &tooltip, postalCode );
addLine( &tooltip, countryCode );
addLine( &tooltip, adminName1 );
addLine( &tooltip, adminName2 );
addLine( &tooltip, adminName3 );
tooltip = tooltip.trimmed();
if( !itemExists( id ) ) {
// If it does not exist, create it
GeoDataCoordinates coordinates( longitude, latitude, 0.0, GeoDataCoordinates::Degree );
PostalCodeItem *item = new PostalCodeItem( this );
item->setId( id );
item->setCoordinate( coordinates );
item->setTarget( "earth" );
item->setToolTip( tooltip );
item->setText( postalCode );
addItemToList( item );
}
}
}
}
}
示例9: init
void REcmaDimDiametricEntity::init(QScriptEngine& engine, QScriptValue* proto
)
{
bool protoCreated = false;
if(proto == NULL){
proto = new QScriptValue(engine.newVariant(qVariantFromValue(
(RDimDiametricEntity*) 0)));
protoCreated = true;
}
// primary base class RDimensionEntity:
QScriptValue dpt = engine.defaultPrototype(
qMetaTypeId<RDimensionEntity*>());
if (dpt.isValid()) {
proto->setPrototype(dpt);
}
/*
*/
QScriptValue fun;
// toString:
REcmaHelper::registerFunction(&engine, proto, toString, "toString");
// destroy:
REcmaHelper::registerFunction(&engine, proto, destroy, "destroy");
// conversion for base class RDimensionEntity
REcmaHelper::registerFunction(&engine, proto, getRDimensionEntity, "getRDimensionEntity");
// conversion for base class REntity
REcmaHelper::registerFunction(&engine, proto, getREntity, "getREntity");
// conversion for base class RObject
REcmaHelper::registerFunction(&engine, proto, getRObject, "getRObject");
// get class name
REcmaHelper::registerFunction(&engine, proto, getClassName, "getClassName");
// conversion to all base classes (multiple inheritance):
REcmaHelper::registerFunction(&engine, proto, getBaseClasses, "getBaseClasses");
// properties:
// methods:
REcmaHelper::registerFunction(&engine, proto, clone, "clone");
REcmaHelper::registerFunction(&engine, proto, getType, "getType");
REcmaHelper::registerFunction(&engine, proto, setProperty, "setProperty");
REcmaHelper::registerFunction(&engine, proto, getProperty, "getProperty");
REcmaHelper::registerFunction(&engine, proto, getData, "getData");
REcmaHelper::registerFunction(&engine, proto, setData, "setData");
REcmaHelper::registerFunction(&engine, proto, setChordPoint, "setChordPoint");
REcmaHelper::registerFunction(&engine, proto, getChordPoint, "getChordPoint");
REcmaHelper::registerFunction(&engine, proto, setFarChordPoint, "setFarChordPoint");
REcmaHelper::registerFunction(&engine, proto, getFarChordPoint, "getFarChordPoint");
engine.setDefaultPrototype(
qMetaTypeId<RDimDiametricEntity*>(), *proto);
QScriptValue ctor = engine.newFunction(create, *proto, 2);
// static methods:
REcmaHelper::registerFunction(&engine, &ctor, init, "init");
// static properties:
ctor.setProperty("PropertyCustom",
qScriptValueFromValue(&engine, RDimDiametricEntity::PropertyCustom),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertyHandle",
//.........这里部分代码省略.........
示例10: testPlayerScript
bool testPlayerScript(QString path, int player, int difficulty)
{
QScriptEngine *engine = new QScriptEngine();
QFile input(path);
input.open(QIODevice::ReadOnly);
QString source(QString::fromUtf8(input.readAll()));
input.close();
// Special functions
engine->globalObject().setProperty("setTimer", engine->newFunction(js_setTimer));
engine->globalObject().setProperty("queue", engine->newFunction(js_queue));
engine->globalObject().setProperty("removeTimer", engine->newFunction(js_removeTimer));
engine->globalObject().setProperty("include", engine->newFunction(js_include));
engine->globalObject().setProperty("bind", engine->newFunction(js_bind));
// Special global variables
engine->globalObject().setProperty("version", 1, QScriptValue::ReadOnly | QScriptValue::Undeletable);
engine->globalObject().setProperty("selectedPlayer", 0, QScriptValue::ReadOnly | QScriptValue::Undeletable);
engine->globalObject().setProperty("gameTime", 2, QScriptValue::ReadOnly | QScriptValue::Undeletable);
engine->globalObject().setProperty("difficulty", 1, QScriptValue::ReadOnly | QScriptValue::Undeletable);
engine->globalObject().setProperty("mapName", "TEST", QScriptValue::ReadOnly | QScriptValue::Undeletable);
engine->globalObject().setProperty("baseType", 1, QScriptValue::ReadOnly | QScriptValue::Undeletable);
engine->globalObject().setProperty("alliancesType", 2, QScriptValue::ReadOnly | QScriptValue::Undeletable);
engine->globalObject().setProperty("powerType", 1, QScriptValue::ReadOnly | QScriptValue::Undeletable);
engine->globalObject().setProperty("maxPlayers", CUR_PLAYERS, QScriptValue::ReadOnly | QScriptValue::Undeletable);
engine->globalObject().setProperty("scavengers", true, QScriptValue::ReadOnly | QScriptValue::Undeletable);
engine->globalObject().setProperty("mapWidth", 80, QScriptValue::ReadOnly | QScriptValue::Undeletable);
engine->globalObject().setProperty("mapHeight", 80, QScriptValue::ReadOnly | QScriptValue::Undeletable);
// Most special global
engine->globalObject().setProperty("me", player, QScriptValue::ReadOnly | QScriptValue::Undeletable);
// Register functions to the script engine here
engine->globalObject().setProperty("_", engine->newFunction(js_translate));
engine->globalObject().setProperty("label", engine->newFunction(js_label));
engine->globalObject().setProperty("enumLabels", engine->newFunction(js_enumLabels));
engine->globalObject().setProperty("enumGateways", engine->newFunction(js_enumGateways));
// horrible hacks follow -- do not rely on these being present!
engine->globalObject().setProperty("hackNetOff", engine->newFunction(js_hackNetOff));
engine->globalObject().setProperty("hackNetOn", engine->newFunction(js_hackNetOn));
engine->globalObject().setProperty("objFromId", engine->newFunction(js_objFromId));
// General functions -- geared for use in AI scripts
engine->globalObject().setProperty("debug", engine->newFunction(js_debug));
engine->globalObject().setProperty("console", engine->newFunction(js_console));
engine->globalObject().setProperty("structureIdle", engine->newFunction(js_structureIdle));
engine->globalObject().setProperty("enumStruct", engine->newFunction(js_enumStruct));
engine->globalObject().setProperty("enumStructOffWorld", engine->newFunction(js_enumStructOffWorld));
engine->globalObject().setProperty("enumDroid", engine->newFunction(js_enumDroid));
engine->globalObject().setProperty("enumGroup", engine->newFunction(js_enumGroup));
engine->globalObject().setProperty("enumFeature", engine->newFunction(js_enumFeature));
engine->globalObject().setProperty("enumBlips", engine->newFunction(js_enumBlips));
engine->globalObject().setProperty("enumResearch", engine->newFunction(js_enumResearch));
engine->globalObject().setProperty("getResearch", engine->newFunction(js_getResearch));
engine->globalObject().setProperty("pursueResearch", engine->newFunction(js_pursueResearch));
engine->globalObject().setProperty("distBetweenTwoPoints", engine->newFunction(js_distBetweenTwoPoints));
engine->globalObject().setProperty("newGroup", engine->newFunction(js_newGroup));
engine->globalObject().setProperty("groupAddArea", engine->newFunction(js_groupAddArea));
engine->globalObject().setProperty("groupAddDroid", engine->newFunction(js_groupAddDroid));
engine->globalObject().setProperty("groupSize", engine->newFunction(js_groupSize));
engine->globalObject().setProperty("orderDroidLoc", engine->newFunction(js_orderDroidLoc));
engine->globalObject().setProperty("playerPower", engine->newFunction(js_playerPower));
engine->globalObject().setProperty("isStructureAvailable", engine->newFunction(js_isStructureAvailable));
engine->globalObject().setProperty("pickStructLocation", engine->newFunction(js_pickStructLocation));
engine->globalObject().setProperty("droidCanReach", engine->newFunction(js_droidCanReach));
engine->globalObject().setProperty("orderDroidStatsLoc", engine->newFunction(js_orderDroidBuild)); // deprecated
engine->globalObject().setProperty("orderDroidBuild", engine->newFunction(js_orderDroidBuild));
engine->globalObject().setProperty("orderDroidObj", engine->newFunction(js_orderDroidObj));
engine->globalObject().setProperty("orderDroid", engine->newFunction(js_orderDroid));
engine->globalObject().setProperty("buildDroid", engine->newFunction(js_buildDroid));
engine->globalObject().setProperty("addDroid", engine->newFunction(js_addDroid));
engine->globalObject().setProperty("addFeature", engine->newFunction(js_addFeature));
engine->globalObject().setProperty("componentAvailable", engine->newFunction(js_componentAvailable));
engine->globalObject().setProperty("isVTOL", engine->newFunction(js_isVTOL));
engine->globalObject().setProperty("safeDest", engine->newFunction(js_safeDest));
engine->globalObject().setProperty("activateStructure", engine->newFunction(js_activateStructure));
engine->globalObject().setProperty("chat", engine->newFunction(js_chat));
// Functions that operate on the current player only
engine->globalObject().setProperty("centreView", engine->newFunction(js_centreView));
engine->globalObject().setProperty("playSound", engine->newFunction(js_playSound));
engine->globalObject().setProperty("gameOverMessage", engine->newFunction(js_gameOverMessage));
// Global state manipulation -- not for use with skirmish AI (unless you want it to cheat, obviously)
engine->globalObject().setProperty("setStructureLimits", engine->newFunction(js_setStructureLimits));
engine->globalObject().setProperty("applyLimitSet", engine->newFunction(js_applyLimitSet));
engine->globalObject().setProperty("setMissionTime", engine->newFunction(js_setMissionTime));
engine->globalObject().setProperty("setReinforcementTime", engine->newFunction(js_setReinforcementTime));
engine->globalObject().setProperty("completeResearch", engine->newFunction(js_completeResearch));
engine->globalObject().setProperty("enableResearch", engine->newFunction(js_enableResearch));
engine->globalObject().setProperty("setPower", engine->newFunction(js_setPower));
engine->globalObject().setProperty("setTutorialMode", engine->newFunction(js_setTutorialMode));
engine->globalObject().setProperty("setDesign", engine->newFunction(js_setDesign));
engine->globalObject().setProperty("setMiniMap", engine->newFunction(js_setMiniMap));
engine->globalObject().setProperty("addReticuleButton", engine->newFunction(js_addReticuleButton));
engine->globalObject().setProperty("removeReticuleButton", engine->newFunction(js_removeReticuleButton));
engine->globalObject().setProperty("enableStructure", engine->newFunction(js_enableStructure));
engine->globalObject().setProperty("makeComponentAvailable", engine->newFunction(js_makeComponentAvailable));
engine->globalObject().setProperty("enableComponent", engine->newFunction(js_enableComponent));
//.........这里部分代码省略.........
示例11: defined
void tst_QScriptEngineDebugger::attachAndDetach()
{
#if defined(Q_OS_WINCE) && _WIN32_WCE < 0x600
QSKIP("skipped due to high mem usage until task 261062 is fixed");
#endif
{
QScriptEngineDebugger debugger;
QCOMPARE(debugger.state(), QScriptEngineDebugger::SuspendedState);
debugger.attachTo(0);
QScriptEngine engine;
debugger.attachTo(&engine);
QCOMPARE(debugger.state(), QScriptEngineDebugger::SuspendedState);
}
{
QScriptEngineDebugger debugger;
QScriptEngine engine;
QScriptValue oldPrint = engine.globalObject().property("print");
QVERIFY(oldPrint.isFunction());
QVERIFY(!engine.globalObject().property("__FILE__").isValid());
QVERIFY(!engine.globalObject().property("__LINE__").isValid());
debugger.attachTo(&engine);
QVERIFY(engine.globalObject().property("__FILE__").isUndefined());
QVERIFY(engine.globalObject().property("__LINE__").isNumber());
QVERIFY(!engine.globalObject().property("print").strictlyEquals(oldPrint));
debugger.detach();
QVERIFY(engine.globalObject().property("print").strictlyEquals(oldPrint));
QVERIFY(!engine.globalObject().property("__FILE__").isValid());
QVERIFY(!engine.globalObject().property("__LINE__").isValid());
}
{
QScriptEngineDebugger debugger;
QScriptEngine engine;
debugger.attachTo(&engine);
debugger.detach();
QScriptEngine engine2;
debugger.attachTo(&engine2);
}
{
QScriptEngineDebugger debugger;
QScriptEngine engine;
debugger.attachTo(&engine);
debugger.detach();
QScriptEngine engine2;
debugger.attachTo(&engine2);
debugger.detach();
}
#ifndef Q_OS_WINCE // demands too much memory for WinCE
{
QScriptEngineDebugger debugger;
QScriptEngine engine;
debugger.attachTo(&engine);
QScriptEngineDebugger debugger2;
debugger2.attachTo(&engine);
}
#endif
{
QScriptEngine *engine = new QScriptEngine;
QScriptEngineDebugger debugger;
debugger.attachTo(engine);
delete engine;
QScriptEngine engine2;
debugger.attachTo(&engine2);
}
}
示例12: init
void REcmaSharedPointerLinetype::init(QScriptEngine& engine, QScriptValue* proto
)
{
bool protoCreated = false;
if(proto == NULL){
proto = new QScriptValue(engine.newVariant(qVariantFromValue(
(RLinetypePointer*) 0)));
protoCreated = true;
}
// primary base class RObject:
proto->setPrototype(engine.defaultPrototype(
qMetaTypeId<RObjectPointer>()));
/*
*/
QScriptValue fun;
// toString:
REcmaHelper::registerFunction(&engine, proto, toString, "toString");
// copy:
REcmaHelper::registerFunction(&engine, proto, copy, "copy");
// shared pointer support:
REcmaHelper::registerFunction(&engine, proto, data, "data");
REcmaHelper::registerFunction(&engine, proto, isNull, "isNull");
// destroy:
REcmaHelper::registerFunction(&engine, proto, destroy, "destroy");
// conversion for base class RObject
REcmaHelper::registerFunction(&engine, proto, getRObject, "getRObject");
// get class name
REcmaHelper::registerFunction(&engine, proto, getClassName, "getClassName");
// conversion to all base classes (multiple inheritance):
REcmaHelper::registerFunction(&engine, proto, getBaseClasses, "getBaseClasses");
// properties:
// methods:
REcmaHelper::registerFunction(&engine, proto, clone, "clone");
REcmaHelper::registerFunction(&engine, proto, getName, "getName");
REcmaHelper::registerFunction(&engine, proto, setName, "setName");
REcmaHelper::registerFunction(&engine, proto, isValid, "isValid");
REcmaHelper::registerFunction(&engine, proto, getProperty, "getProperty");
REcmaHelper::registerFunction(&engine, proto, setProperty, "setProperty");
REcmaHelper::registerFunction(&engine, proto, isSelectedForPropertyEditing, "isSelectedForPropertyEditing");
REcmaHelper::registerFunction(&engine, proto, equals, "equals");
REcmaHelper::registerFunction(&engine, proto, operator_not_assign, "operator_not_assign");
REcmaHelper::registerFunction(&engine, proto, operator_less, "operator_less");
engine.setDefaultPrototype(
qMetaTypeId<RLinetypePointer>(), *proto);
QScriptValue ctor = engine.newFunction(create, *proto, 2);
// static methods:
REcmaHelper::registerFunction(&engine, &ctor, init, "init");
REcmaHelper::registerFunction(&engine, &ctor, getList, "getList");
REcmaHelper::registerFunction(&engine, &ctor, getIcon, "getIcon");
REcmaHelper::registerFunction(&engine, &ctor, getTitle, "getTitle");
// static properties:
ctor.setProperty("PropertyName",
//.........这里部分代码省略.........
示例13: main
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
QScriptEngine eng;
ByteArrayClass *baClass = new ByteArrayClass(&eng);
eng.globalObject().setProperty("ByteArray", baClass->constructor());
qDebug() << "ba = new ByteArray(4):" << eng.evaluate("ba = new ByteArray(4)").toString();
qDebug() << "ba instanceof ByteArray:" << eng.evaluate("ba instanceof ByteArray").toBool();
qDebug() << "ba.length:" << eng.evaluate("ba.length").toNumber();
qDebug() << "ba[1] = 123; ba[1]:" << eng.evaluate("ba[1] = 123; ba[1]").toNumber();
qDebug() << "ba[7] = 224; ba.length:" << eng.evaluate("ba[7] = 224; ba.length").toNumber();
qDebug() << "for-in loop:" << eng.evaluate("result = '';\n"
"for (var p in ba) {\n"
" if (result.length > 0)\n"
" result += ', ';\n"
" result += '(' + p + ',' + ba[p] + ')';\n"
"} result").toString();
qDebug() << "ba.toBase64():" << eng.evaluate("b64 = ba.toBase64()").toString();
qDebug() << "ba.toBase64().toLatin1String():" << eng.evaluate("b64.toLatin1String()").toString();
qDebug() << "ba.valueOf():" << eng.evaluate("ba.valueOf()").toString();
qDebug() << "ba.chop(2); ba.length:" << eng.evaluate("ba.chop(2); ba.length").toNumber();
qDebug() << "ba2 = new ByteArray(ba):" << eng.evaluate("ba2 = new ByteArray(ba)").toString();
qDebug() << "ba2.equals(ba):" << eng.evaluate("ba2.equals(ba)").toBool();
qDebug() << "ba2.equals(new ByteArray()):" << eng.evaluate("ba2.equals(new ByteArray())").toBool();
return 0;
}
示例14: kDebug
void ScriptJob::run()
{
m_mutex->lock();
if ( !loadScript(&m_data.program) ) {
kDebug() << "Script could not be loaded correctly";
m_mutex->unlock();
return;
}
QScriptEngine *engine = m_engine;
ScriptObjects objects = m_objects;
m_mutex->unlock();
// Store start time of the script
QElapsedTimer timer;
timer.start();
// Add call to the appropriate function
QString functionName;
QScriptValueList arguments = QScriptValueList() << request()->toScriptValue( engine );
switch ( request()->parseMode() ) {
case ParseForDepartures:
case ParseForArrivals:
functionName = ServiceProviderScript::SCRIPT_FUNCTION_GETTIMETABLE;
break;
case ParseForJourneysByDepartureTime:
case ParseForJourneysByArrivalTime:
functionName = ServiceProviderScript::SCRIPT_FUNCTION_GETJOURNEYS;
break;
case ParseForStopSuggestions:
functionName = ServiceProviderScript::SCRIPT_FUNCTION_GETSTOPSUGGESTIONS;
break;
case ParseForAdditionalData:
functionName = ServiceProviderScript::SCRIPT_FUNCTION_GETADDITIONALDATA;
break;
default:
kDebug() << "Parse mode unsupported:" << request()->parseMode();
break;
}
if ( functionName.isEmpty() ) {
// This should never happen, therefore no i18n
handleError( "Unknown parse mode" );
return;
}
// Check if the script function is implemented
QScriptValue function = engine->globalObject().property( functionName );
if ( !function.isFunction() ) {
handleError( i18nc("@info/plain", "Function <icode>%1</icode> not implemented by "
"the script", functionName) );
return;
}
// Call script function
QScriptValue result = function.call( QScriptValue(), arguments );
if ( engine->hasUncaughtException() ) {
// TODO Get filename where the exception occured, maybe use ScriptAgent for that
handleError( i18nc("@info/plain", "Error in script function <icode>%1</icode>, "
"line %2: <message>%3</message>.",
functionName, engine->uncaughtExceptionLineNumber(),
engine->uncaughtException().toString()) );
return;
}
GlobalTimetableInfo globalInfo;
globalInfo.requestDate = QDate::currentDate();
globalInfo.delayInfoAvailable = !objects.result->isHintGiven( ResultObject::NoDelaysForStop );
// The called function returned, but asynchronous network requests may have been started.
// Wait for all network requests to finish, because slots in the script may get called
if ( !waitFor(objects.network.data(), SIGNAL(allRequestsFinished()), WaitForNetwork) ) {
return;
}
// Wait for script execution to finish
ScriptAgent agent( engine );
if ( !waitFor(&agent, SIGNAL(scriptFinished()), WaitForScriptFinish) ) {
return;
}
// Update last download URL
QMutexLocker locker( m_mutex );
m_lastUrl = objects.network->lastUrl(); // TODO Store all URLs
m_lastUserUrl = objects.network->lastUserUrl();
// Inform about script run time
DEBUG_ENGINE_JOBS( "Script finished in" << (timer.elapsed() / 1000.0)
<< "seconds: " << m_data.provider.scriptFileName() << request()->parseMode() );
// If data for the current job has already been published, do not emit
// xxxReady() with an empty resultset
if ( m_published == 0 || m_objects.result->count() > m_published ) {
const bool couldNeedForcedUpdate = m_published > 0;
const MoreItemsRequest *moreItemsRequest =
dynamic_cast< const MoreItemsRequest* >( request() );
const AbstractRequest *_request =
moreItemsRequest ? moreItemsRequest->request().data() : request();
switch ( _request->parseMode() ) {
case ParseForDepartures:
//.........这里部分代码省略.........
示例15: initEcma
// includes for base ecma wrapper classes
void REcmaFileImporterRegistry::initEcma(QScriptEngine& engine, QScriptValue* proto
)
{
bool protoCreated = false;
if(proto == NULL){
proto = new QScriptValue(engine.newVariant(qVariantFromValue(
(RFileImporterRegistry*) 0)));
protoCreated = true;
}
QScriptValue fun;
// toString:
REcmaHelper::registerFunction(&engine, proto, toString, "toString");
// destroy:
REcmaHelper::registerFunction(&engine, proto, destroy, "destroy");
// get class name
REcmaHelper::registerFunction(&engine, proto, getClassName, "getClassName");
// conversion to all base classes (multiple inheritance):
REcmaHelper::registerFunction(&engine, proto, getBaseClasses, "getBaseClasses");
// properties:
// methods:
engine.setDefaultPrototype(
qMetaTypeId<RFileImporterRegistry*>(), *proto);
QScriptValue ctor = engine.newFunction(createEcma, *proto, 2);
// static methods:
REcmaHelper::registerFunction(&engine, &ctor, registerFileImporter, "registerFileImporter");
REcmaHelper::registerFunction(&engine, &ctor, unregisterFileImporter, "unregisterFileImporter");
REcmaHelper::registerFunction(&engine, &ctor, getFileImporter, "getFileImporter");
REcmaHelper::registerFunction(&engine, &ctor, getFilterStrings, "getFilterStrings");
REcmaHelper::registerFunction(&engine, &ctor, hasFileImporter, "hasFileImporter");
REcmaHelper::registerFunction(&engine, &ctor, getFilterExtensions, "getFilterExtensions");
REcmaHelper::registerFunction(&engine, &ctor, getFilterExtensionPatterns, "getFilterExtensionPatterns");
// static properties:
// enum values:
// enum conversions:
// init class:
engine.globalObject().setProperty("RFileImporterRegistry",
ctor, QScriptValue::SkipInEnumeration);
if( protoCreated ){
delete proto;
}
}