Example #1
0
int main(int argc, char **argv)
{
	QCoreApplication app(argc, argv);
	
	if ( argc < 3 )
	{
		qDebug("not enough arguments");
		return 1;
	}
	
	QFile f(argv[1]);
	
	if ( !f.open(QFile::ReadOnly | QFile::Text) )
	{
		qDebug("Unable to open assembler script file.");
		return 1;
	}
	
	QScriptEngine engine;
	QScriptValue v = engine.evaluate(QString::fromLocal8Bit(f.readAll()), f.fileName(), 1);
	
	if ( engine.hasUncaughtException() )
	{
		qDebug("Uncaught exception while loading assembler script at line %i: %s",
				engine.uncaughtExceptionLineNumber(),
				qPrintable(engine.uncaughtException().toString())
			);
		
		return 2;
	}
	
	f.close();
	f.setFileName(argv[2]);
	
	if ( !f.open(QFile::ReadOnly | QFile::Text) )
	{
		qDebug("Unable to open source file.");
		return 1;
	}
	
	engine.globalObject().setProperty("source", engine.newVariant(QString::fromLocal8Bit(f.readAll())));
	engine.globalObject().setProperty("reloc", engine.newVariant(argc > 3 ? QString::fromLocal8Bit(argv[3]) : "0x0000"));
	
	QScriptValue r = engine.evaluate("assemble(source, reloc)");
	
	if ( engine.hasUncaughtException() )
	{
		qDebug("Uncaught exception while assembling file at line %i: %s",
				engine.uncaughtExceptionLineNumber(),
				qPrintable(engine.uncaughtException().toString())
			);
		
		return 3;
	}
	
	qDebug("%s", qPrintable(r.toString()));
	
	return 0;
}
Example #2
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QString fileName = "load.qs";

    QFile scriptFile(fileName);
    if (!scriptFile.open(QIODevice::ReadOnly))
    {
        // handle error
        qDebug()<<"File open error";
    }
    else
    {
        QFileInfo info(scriptFile);
        qDebug()<< "File Path" + info.absoluteFilePath();
    }
    QTextStream stream(&scriptFile);
    QString contents = stream.readAll();
    scriptFile.close();
    ScriptFunctions functions;
    QScriptEngine myEngine;
    QScriptValue scriptFunctions = myEngine.newQObject(&functions);
    myEngine.globalObject().setProperty("nativeFunctions", scriptFunctions);
    myEngine.globalObject().setProperty("load", myEngine.newFunction(loadScripts, /*length=*/1));


    QScriptValue result = myEngine.evaluate(contents, fileName);
     if (myEngine.hasUncaughtException()) {
         int line = myEngine.uncaughtExceptionLineNumber();
         qDebug() << "uncaught exception at line" << line << ":" << result.toString();
     }

    return a.exec();
}
Example #3
0
int main(int argc, char **argv)
{
	Q_INIT_RESOURCE(rtfedit);
	
    QApplication app(argc, argv);
    QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
    QScriptEngine engine;

    QFile scriptFile(":/rtfedit.js");
    scriptFile.open(QIODevice::ReadOnly);
    engine.evaluate(QObject::tr(scriptFile.readAll()));
    scriptFile.close();

    RTFUiLoader loader;
    QFile uiFile(":/rtfedit.ui");
    uiFile.open(QIODevice::ReadOnly);
    QWidget *ui = loader.load(&uiFile);
    uiFile.close();

    QScriptValue func = engine.evaluate("RTF");
    QScriptValue scriptUi = engine.newQObject(ui);
    QScriptValue table = func.construct(QScriptValueList() << scriptUi);
    if(engine.hasUncaughtException()) {
    	QScriptValue value = engine.uncaughtException();
    	QString lineNumber = QString("\nLine Number:%1\n").arg(engine.uncaughtExceptionLineNumber());
    	QStringList btList = engine.uncaughtExceptionBacktrace();
    	QString trace;
    	for(short i=0; i<btList.size(); ++i)
    		trace += btList.at(i);
    	QMessageBox::information(NULL, QObject::tr("Exception"), value.toString() + lineNumber + trace );
    }

    ui->show();
    return app.exec();
}
Example #4
0
void ShellController::printUncaughtException(const QScriptValue &exception) {
    QScriptEngine *eng = engine();
    QString message = QString::fromLatin1("Uncaught exception: %1. Line: %2")
              .arg(exception.toString())
              .arg(eng->uncaughtExceptionLineNumber());
    QStringList backtrace = eng->uncaughtExceptionBacktrace();
    foreach (QString b, backtrace) {
        message.append(QString::fromLatin1("\n    at %1").arg(b));
    }
Example #5
0
 void handleException() {
     Q_ASSERT( m_engine );
     Q_ASSERT( m_engine->hasUncaughtException() );
     const QString err = m_engine->uncaughtException().toString();
     const int linenr = m_engine->uncaughtExceptionLineNumber();
     const QString trace = m_engine->uncaughtExceptionBacktrace().join("\n");
     qrossdebug( QString("%1, line:%2, backtrace:\n%3").arg(err).arg(linenr).arg(trace) );
     m_script->action()->setError(err, trace, linenr);
     m_engine->clearExceptions();
 }
Example #6
0
bool HttpDaemon::Private::initialize()
{
  QScriptEngine engine;
   
  QFile file(configScript);
  if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
    qDebug() << file.errorString();
    return false;
  }

  QTextStream stream (&file);

  auto globalObject = engine.globalObject();
  auto configObject = engine.newObject();
  auto typesObject  = engine.newObject();
  auto actionObject = engine.newObject();
  auto handlerObject= engine.newObject();
  auto addTypeFn    = engine.newFunction(addType);
  auto setPortFn    = engine.newFunction(setPort);
  auto addReqHdrFn  = engine.newFunction(addRequestHeader);
  auto setDocRootFn = engine.newFunction(setDocumentRoot);
  auto setServNamFn = engine.newFunction(setServerName);
  auto setServAdmFn = engine.newFunction(setServerAdmin);
  auto setErrLogFn  = engine.newFunction(setErrorLog);
  auto actionFn     = engine.newFunction(action);
  auto addHandlerFn = engine.newFunction(addHandler);
  
  configObject.setProperty(settings_types, typesObject);
  configObject.setProperty(settings_action, actionObject);
  configObject.setProperty(settings_handler, handlerObject);
  globalObject.setProperty(settings_conf, configObject);
  configObject.setProperty("action", actionFn);
  configObject.setProperty("addHandler", addHandlerFn);
  configObject.setProperty("addType", addTypeFn);
  configObject.setProperty("setListenPort", setPortFn);
  configObject.setProperty("addRequestHeader", addReqHdrFn);
  configObject.setProperty("setDocumentRoot", setDocRootFn);
  configObject.setProperty("setServerName", setServNamFn);
  configObject.setProperty("setServerAdmin", setServAdmFn);
  configObject.setProperty("setErrorLog", setErrLogFn);
  
  auto const program = stream.readAll();
  auto const result = engine.evaluate(program, file.fileName(), 1);
  if (engine.hasUncaughtException()) {
    auto line = engine.uncaughtExceptionLineNumber();
    qDebug() << "uncaught exception at line" << line << ":" << result.toString();
    return false;
  }
  auto configValue = engine.evaluate("(function(){return (JSON.stringify(configure));})();");
  serverSettings = QJsonDocument::fromJson(configValue.toString().toLocal8Bit());
  //  qDebug () << serverSettings.toJson();
  return true;
}
Example #7
0
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());
	// Remember internal, reserved names
	QScriptValueIterator it(engine->globalObject());
	while (it.hasNext())
	{
		it.next();
		internalNamespace.insert(it.name(), 1);
	}
	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());
	// 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("me", player, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("selectedPlayer", selectedPlayer, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("gameTime", gameTime, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("difficulty", difficulty, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("mapName", game.map, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("baseType", game.base, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("alliancesType", game.alliance, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("powerType", game.power, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("maxPlayers", game.maxPlayers, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("scavengers", game.scavengers, QScriptValue::ReadOnly | QScriptValue::Undeletable);

	// Regular functions
	registerFunctions(engine);

	// Register script
	scripts.push_back(engine);

	return true;
}
void tst_QScriptContext::lineNumber()
{
    QScriptEngine eng;

    QScriptValue result = eng.evaluate("try { eval(\"foo = 123;\\n this[is{a{syntax|[email protected]#$%@#% \"); } catch (e) { e.lineNumber; }", "foo.qs", 123);
    QVERIFY(!eng.hasUncaughtException());
    QVERIFY(result.isNumber());
    QCOMPARE(result.toInt32(), 2);

    result = eng.evaluate("foo = 123;\n bar = 42\n0 = 0");
    QVERIFY(eng.hasUncaughtException());
    QCOMPARE(eng.uncaughtExceptionLineNumber(), 3);
    QCOMPARE(result.property("lineNumber").toInt32(), 3);
}
Example #9
0
void readFile(QScriptEngine& engine, const QString& fileName) {
	QString scriptFileName(QString("/home/mrz/zen/javascript/") + fileName);
	QFile scriptFile(scriptFileName);
	if ( scriptFile.open(QIODevice::ReadOnly) ) {
		QScriptValue result = engine.evaluate(scriptFile.readAll());
		scriptFile.close();
		if ( engine.hasUncaughtException() ) {
			qDebug() << "Error in file " << fileName;
			qDebug() << "Line: " << engine.uncaughtExceptionLineNumber();
			qDebug() << engine.uncaughtExceptionBacktrace();
		}
	}
	else {
		qDebug() << "Failed to open file " << fileName;
	}
}
Example #10
0
static bool hadUncaughtExceptions(QScriptEngine& engine, const QString& fileName) {
    if (engine.hasUncaughtException()) {
        const auto backtrace = engine.uncaughtExceptionBacktrace();
        const auto exception = engine.uncaughtException().toString();
        const auto line = QString::number(engine.uncaughtExceptionLineNumber());
        engine.clearExceptions();

        auto message = QString("[UncaughtException] %1 in %2:%3").arg(exception, fileName, line);
        if (!backtrace.empty()) {
            static const auto lineSeparator = "\n    ";
            message += QString("\n[Backtrace]%1%2").arg(lineSeparator, backtrace.join(lineSeparator));
        }
        qWarning() << qPrintable(message);
        return true;
    }
    return false;
}
Example #11
0
int main(int argc, char *argv[])
{

    if(argc<3)
    {
    	printf("%s file.ui file.js\n",argv[0]);
    	return 0;
    }

    QApplication app(argc, argv);

    QScriptEngine engine;

	QUiLoader loader;
	QFile file(argv[1]);
     	file.open(QFile::ReadOnly);

     	QWidget *formWidget = loader.load(&file);
     	file.close();

    QScriptValue scriptWidget = engine.newQObject(formWidget);
    engine.globalObject().setProperty("widget", scriptWidget);
    
    QFile ifile(argv[2]);
    ifile.open(QFile::ReadOnly);
    QByteArray code=ifile.readAll();
    ifile.close();

	if( !engine.canEvaluate(code) )
	{
		printf("Error\n");
		return 1;
	}

    engine.evaluate("widget.show()");
    QScriptValue result = engine.evaluate(code);
    
    if (engine.hasUncaughtException())
    {
         int line = engine.uncaughtExceptionLineNumber();
         qDebug() << "uncaught exception at line" << line << ":" << result.toString();
    }

    return app.exec();
}
Example #12
0
int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);

    QScriptEngine engine;

    QFile f(app.applicationDirPath() + "/calculator.js");
    f.open(QFile::ReadOnly);

    QString theProgram = QTextStream(&f).readAll();
    theProgram += "calculate('1/0');";

    qDebug() << engine.evaluate(theProgram, "calculator.js").toNumber();

    qDebug() << "Error?" << engine.hasUncaughtException();
    qDebug() << engine.uncaughtException().property("message").toString();
    qDebug() << "On line number" << engine.uncaughtExceptionLineNumber();
    qDebug() << "Backtrace: " << engine.uncaughtExceptionBacktrace();
}
void DroneshareUploadDialog::vehicleQueryComplete(const QString &jsonResponse)
{
    QLOG_DEBUG() << "droneshare: Vehicle Query Complete"/* << jsonResponse*/;

    QScriptSyntaxCheckResult syntaxCheck = QScriptEngine::checkSyntax(jsonResponse);
    QScriptEngine engine;
    QScriptValue result = engine.evaluate("("+jsonResponse+")");

    if (engine.hasUncaughtException()){
        QLOG_ERROR() << "Error evaluating version object";
        QLOG_ERROR() << "Error @line#" << engine.uncaughtExceptionLineNumber();
        QLOG_ERROR() << "Backtrace:" << engine.uncaughtExceptionBacktrace();
        QLOG_ERROR() << "Syntax Check:" << syntaxCheck.errorMessage();
        QLOG_ERROR() << "Syntax Check line:" << syntaxCheck.errorLineNumber()
                     << " col:" << syntaxCheck.errorColumnNumber();
        return;
    }
    ui->statusLabel->setText("Vehicle Query Complete.");
    QMap<QString,QString> vehicleList;

    QScriptValue entries = result.property("vehicles");
    QScriptValueIterator it(entries);
    while (it.hasNext()){
        it.next();
        QScriptValue entry = it.value();
        QString uuid = entry.property("uuid").toString();
        QString name = entry.property("name").toString();
        vehicleList.insert(name,uuid);
    }

    bool ok = false;
    QString item = QInputDialog::getItem(this, tr("Vehicle Selection"),tr("vehicle"),vehicleList.keys(),1,
                                                          false, &ok, Qt::Dialog, Qt::ImhNone);
    if (ok){
        startLogUpload(vehicleList.value(item));
    }

    m_droneshareQuery->deleteLater();
    m_droneshareQuery = NULL;
}
Example #14
0
int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);
    QTextStream err(stderr);

    QStringList arguments = app.arguments();
    if( arguments.length() < 2 )
    {
        err << QString("USAGE: %1 <script>\n").arg(arguments[0]);

        return 1;
    }

    QScriptEngine engine;
    
    engine.globalObject().setProperty("createServer", engine.newFunction(createServer));

    QFile file(arguments[1]);
    if( !file.open(QFile::ReadOnly) )
    {
        err << QString("Error opening %1: %2\n").arg(arguments[1]).arg(file.errorString());
        return 2;
    }

    QTextStream reader(&file);
    engine.evaluate(reader.readAll(), arguments[1]);

    if( engine.hasUncaughtException() )
    {
        err << "Exception\n";
        err << engine.uncaughtException().property("message").toString() << "\n";
        err << "On line number " << engine.uncaughtExceptionLineNumber() << "\n";
        err << "Backtrace:\n";
        foreach(QString s, engine.uncaughtExceptionBacktrace())
            err << "    " << s << "\n";
        return 3;
    }

    app.exec();
}
Example #15
0
File: main.cpp Project: BGmot/Qt
int main(int argc, char **argv)
{
    Q_INIT_RESOURCE(defaultprototypes);

    QApplication app(argc, argv);
//! [1]
    QScriptEngine engine;

    ListWidgetItemPrototype lwiProto;
    engine.setDefaultPrototype(qMetaTypeId<QListWidgetItem*>(),
                               engine.newQObject(&lwiProto));

    ListWidgetPrototype lwProto;
    engine.setDefaultPrototype(qMetaTypeId<QListWidget*>(),
                               engine.newQObject(&lwProto));
//! [1]

//! [2]
    QListWidget listWidget;
    engine.globalObject().setProperty("listWidget",
                                      engine.newQObject(&listWidget));
//! [2]

    QFile file(":/code.js");
    file.open(QIODevice::ReadOnly);
    QScriptValue result = engine.evaluate(file.readAll());
    file.close();
    if (engine.hasUncaughtException()) {
        int lineNo = engine.uncaughtExceptionLineNumber();
        qWarning() << "line" << lineNo << ":" << result.toString();
    }

#if defined(Q_OS_SYMBIAN)
    listWidget.showMaximized();
#else
    listWidget.show();
#endif
    return app.exec();
}
Example #16
0
Graph * JSONGraphReader::ReadGraph(const QString & filename, Graph * graph){
    QFile file( filename );
    if ( file.open(  QIODevice::ReadOnly ) ) {

        QTextStream stream( &file );
        stream.setCodec("utf-8");
        QString str = stream.readAll();
        QScriptValue sc;
        QScriptEngine engine;
        sc = engine.evaluate("("+ str +")");
        if(engine.hasUncaughtException()){
            QMessageBox::warning(0,"Warning", "Warning\nException on line:"+QString(engine.uncaughtExceptionLineNumber())
                                 +"\n"+engine.uncaughtExceptionBacktrace().join("\n"));
            return 0;
        }
        if( !graph )
            graph = new Graph;

        LoadVers(graph, sc);
        LoadEdges(graph, sc);
        GraphInfo * gi;
        graph->setInfo( m_infoReader->ReadGraphInfo( sc ));
//        }catch(ReaderError & e){
//            qDebug()<<e.message();
//            return 0;
//        }
        //graph->setInfo( gi );
//        qDebug()<<gi->name();
//        graph->setInfo( gi );
        file.close();

        return graph;
    }


    return 0;
}
void DroneshareUploadDialog::uploadFailed(const QString& jsonResponse, const QString& errorString)
{
    QLOG_DEBUG() << "droneshare: upload failed: " << errorString
                    << "JSON response:" << jsonResponse;
    m_droneshareUpload->deleteLater();
    m_droneshareUpload = NULL;

    QScriptSyntaxCheckResult syntaxCheck = QScriptEngine::checkSyntax(jsonResponse);
    QScriptEngine engine;
    QScriptValue result = engine.evaluate("("+jsonResponse+")");

    if (engine.hasUncaughtException()){
        QLOG_ERROR() << "Error evaluating version object";
        QLOG_ERROR() << "Error @line#" << engine.uncaughtExceptionLineNumber();
        QLOG_ERROR() << "Backtrace:" << engine.uncaughtExceptionBacktrace();
        QLOG_ERROR() << "Syntax Check:" << syntaxCheck.errorMessage();
        QLOG_ERROR() << "Syntax Check line:" << syntaxCheck.errorLineNumber()
                     << " col:" << syntaxCheck.errorColumnNumber();
        return;
    }

    QString message = result.property("message").toString();
    ui->statusLabel->setText(tr("Upload Failed!\n%1").arg(message));
}
void DroneshareUploadDialog::uploadComplete(const QString& jsonResponse)
{
    QLOG_DEBUG() << "droneshare: upload success: " << jsonResponse;
    m_droneshareUpload->deleteLater();
    m_droneshareUpload = NULL;

    QScriptSyntaxCheckResult syntaxCheck = QScriptEngine::checkSyntax(jsonResponse);
    QScriptEngine engine;
    QScriptValue result = engine.evaluate("("+jsonResponse+")");

    if (engine.hasUncaughtException()){
        QLOG_ERROR() << "Error evaluating version object";
        QLOG_ERROR() << "Error @line#" << engine.uncaughtExceptionLineNumber();
        QLOG_ERROR() << "Backtrace:" << engine.uncaughtExceptionBacktrace();
        QLOG_ERROR() << "Syntax Check:" << syntaxCheck.errorMessage();
        QLOG_ERROR() << "Syntax Check line:" << syntaxCheck.errorLineNumber()
                     << " col:" << syntaxCheck.errorColumnNumber();
        return;
    }

    QString viewURL = result.property(0).property("viewURL").toString();
    ui->statusLabel->setOpenExternalLinks(true);
    ui->statusLabel->setText(tr("<html><head/><body><p>Upload Suceeded!<br><a href=\"%1\"><span style=\" text-decoration: underline; color:#0000ff;\">Click to view on Droneshare</span></a></p></body></html>").arg(viewURL));
}
Example #19
0
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());

	// We also need to save the special 'scriptName' variable.
	//== \item[scriptName] Base name of the script that is running.
	QFileInfo basename(path);
	engine->globalObject().setProperty("scriptName", basename.baseName(), QScriptValue::ReadOnly | QScriptValue::Undeletable);

	// 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;
}
Example #20
0
bool DSO::addCustomFile(const QString &fileName)
{
  m_lastCustomError = "";

  SkFile file(fileName);

  if (!file.open(SkFile::ReadOnly | SkFile::Text))
  {
    m_lastCustomError = tr("File not found!");
    return false;
  }

  QString code;

  do
  {
    if (file.atEnd())
    {
      break;
    }
    QString line = file.readLine();

    if (line.simplified() == "*DATA")
    {
      break;
    }

    code += line;
  } while (true);

  QScriptEngine engine;

  scriptNewTypes.clear();

  engine.globalObject().setProperty("AUTHOR", "");
  engine.globalObject().setProperty("EPOCH", 2000);
  engine.globalObject().setProperty("DESCRIPTION", "");

  engine.globalObject().setProperty("POINT_SOURCE", 0);
  engine.globalObject().setProperty("CIRCLE", 1);
  engine.globalObject().setProperty("CROSS", 2);
  engine.globalObject().setProperty("RECTANGLE", 3);

  QScriptValue fun = engine.newFunction(DEFINE_CUSTOM_OBJECT, 3);
  engine.globalObject().setProperty("DEFINE_CUSTOM_OBJECT", fun);

  QScriptValue result = engine.evaluate(code);
  if (engine.hasUncaughtException())
  {
    int line = engine.uncaughtExceptionLineNumber();
    m_lastCustomError = QString("uncaught exception at line ") + line + " : " + result.toString();
    return false;
  }

  QString author;
  QString description;
  double epoch;

  int nameOffset = 0; // TODO: dat globalne

  QScriptValueIterator it(engine.globalObject());
  while (it.hasNext())
  {
    it.next();

    if (it.name() == "AUTHOR")
    {
      author = it.value().toString();
    }
    else
    if (it.name() == "DESCRIPTION")
    {
      description = it.value().toString();
    }
    else
    if (it.name() == "EPOCH")
    {
      epoch = it.value().toNumber();
    }
  }

  do
  {
    if (file.atEnd())
    {
      break;
    }
    QString line = file.readLine().simplified();

    if (line.startsWith("//"))
    {
      continue;
    }

    if (line.size() == 0)
    {
      continue;
    }

    QStringList list = line.split("|");

    //qDebug() << line << list.count();

    if (list.count() != 10)
    {
      m_lastCustomError = "Invalid record";
      return false;
    }

    QString type = list[0].simplified();
    QString name1 = list[1].simplified();
    QString name2 = list[2].simplified();
    double ra = parseRA(list[3]);
    double dec = parseDec(list[4]);
    double sizeA = parseSize(list[5]);
    double sizeB = parseSize(list[6]);
    double mag = list[7].simplified().toDouble();
    double pa = list[8].simplified().toDouble();
    QString cls = list[9].simplified();

    dso_t dso;

    if (qIsNaN(ra) || qIsNaN(dec))
    {
      m_lastCustomError = "Invalid RA/Dec value";
      return false;
    }

    m_namesMap[USER_OFFSET + nameOffset].append(name1);
    m_namesMap[USER_OFFSET + nameOffset].append(name2);
    nameOffset++;

    dso.cataloque = 0; // TODO: dodelat
    dso.galType = 0; // TODO: dodelat
    dso.mag = SkMath::isNear(mag, 0) ?  NO_DSO_MAG : (short)(mag * 100.);
    dso.nameOffs = USER_OFFSET + nameOffset;
    dso.pa = pa; //TODO: bez PA
    dso.rd.ra = SkMath::toRad(ra);
    dso.rd.dec = SkMath::toRad(dec); //TODO:epoch
    dso.shape = NO_DSO_SHAPE;
    dso.sx = sizeA;
    dso.sy = sizeB;
    dso.type = DSOT_CUSTOM_FLAG; // TODO: user types

    qDebug() << line;
    qDebug() << type << name1 << name2 << ra << dec << sizeA << sizeB << mag << pa << cls;
  } while (true);

  return true;
}
Example #21
0
void Agent::run() {
    NodeList* nodeList = NodeList::getInstance();
    nodeList->setOwnerType(NODE_TYPE_AGENT);
    
    const char AGENT_NODE_TYPES_OF_INTEREST[2] = { NODE_TYPE_VOXEL_SERVER, NODE_TYPE_AUDIO_MIXER };
    
    nodeList->setNodeTypesOfInterest(AGENT_NODE_TYPES_OF_INTEREST, sizeof(AGENT_NODE_TYPES_OF_INTEREST));

    nodeList->getNodeSocket()->setBlocking(false);
    
    // figure out the URL for the script for this agent assignment
    QString scriptURLString("http://%1:8080/assignment/%2");
    scriptURLString = scriptURLString.arg(NodeList::getInstance()->getDomainIP().toString(),
                                          uuidStringWithoutCurlyBraces(_uuid));
    
    // setup curl for script download
    CURLcode curlResult;
    
    CURL* curlHandle = curl_easy_init();
    
    // tell curl which file to grab
    curl_easy_setopt(curlHandle, CURLOPT_URL, scriptURLString.toStdString().c_str());
    
    // send the data to the WriteMemoryCallback function
    curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, writeScriptDataToString);
    
    QString scriptContents;
    
    // pass the scriptContents QString to append data to
    curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, (void *)&scriptContents);
    
    // send a user agent since some servers will require it
    curl_easy_setopt(curlHandle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
    
    // make sure CURL fails on a 400 code
    curl_easy_setopt(curlHandle, CURLOPT_FAILONERROR, true);
    
    qDebug() << "Downloading script at" << scriptURLString << "\n";
    
    // blocking get for JS file
    curlResult = curl_easy_perform(curlHandle);
  
    if (curlResult == CURLE_OK) {
        // cleanup curl
        curl_easy_cleanup(curlHandle);
        curl_global_cleanup();
        
        QScriptEngine engine;
        
        // register meta-type for glm::vec3 conversions
        qScriptRegisterMetaType(&engine, vec3toScriptValue, vec3FromScriptValue);
        
        QScriptValue agentValue = engine.newQObject(this);
        engine.globalObject().setProperty("Agent", agentValue);
        
        VoxelScriptingInterface voxelScripter;
        QScriptValue voxelScripterValue =  engine.newQObject(&voxelScripter);
        engine.globalObject().setProperty("Voxels", voxelScripterValue);
        
        QScriptValue treeScaleValue = engine.newVariant(QVariant(TREE_SCALE));
        engine.globalObject().setProperty("TREE_SCALE", treeScaleValue);

        // let the VoxelPacketSender know how frequently we plan to call it
        voxelScripter.getVoxelPacketSender()->setProcessCallIntervalHint(INJECT_INTERVAL_USECS);
        
        // hook in a constructor for audio injectorss
        AudioInjector scriptedAudioInjector(BUFFER_LENGTH_SAMPLES_PER_CHANNEL);
        QScriptValue audioInjectorValue = engine.newQObject(&scriptedAudioInjector);
        engine.globalObject().setProperty("AudioInjector", audioInjectorValue);
        
        qDebug() << "Downloaded script:" << scriptContents << "\n";
        QScriptValue result = engine.evaluate(scriptContents);
        qDebug() << "Evaluated script.\n";
        
        if (engine.hasUncaughtException()) {
            int line = engine.uncaughtExceptionLineNumber();
            qDebug() << "Uncaught exception at line" << line << ":" << result.toString() << "\n";
        }
        
        timeval startTime;
        gettimeofday(&startTime, NULL);
        
        timeval lastDomainServerCheckIn = {};
        
        sockaddr_in senderAddress;
        unsigned char receivedData[MAX_PACKET_SIZE];
        ssize_t receivedBytes;
        
        int thisFrame = 0;
        
        NodeList::getInstance()->startSilentNodeRemovalThread();
        
        while (!_shouldStop) {
            
            // if we're not hearing from the domain-server we should stop running
            if (NodeList::getInstance()->getNumNoReplyDomainCheckIns() == MAX_SILENT_DOMAIN_SERVER_CHECK_INS) {
                break;
            }
            
            // send a check in packet to the domain server if DOMAIN_SERVER_CHECK_IN_USECS has elapsed
            if (usecTimestampNow() - usecTimestamp(&lastDomainServerCheckIn) >= DOMAIN_SERVER_CHECK_IN_USECS) {
                gettimeofday(&lastDomainServerCheckIn, NULL);
                NodeList::getInstance()->sendDomainServerCheckIn();
            }
            
            // find the audio-mixer in the NodeList so we can inject audio at it
            Node* audioMixer = NodeList::getInstance()->soloNodeOfType(NODE_TYPE_AUDIO_MIXER);
            
        
            if (audioMixer && audioMixer->getActiveSocket()) {
                emit willSendAudioDataCallback();
            }
            
            int usecToSleep = usecTimestamp(&startTime) + (thisFrame++ * INJECT_INTERVAL_USECS) - usecTimestampNow();
            if (usecToSleep > 0) {
                usleep(usecToSleep);
            }
            
            if (audioMixer && audioMixer->getActiveSocket() && scriptedAudioInjector.hasSamplesToInject()) {
                // we have an audio mixer and samples to inject, send those off
                scriptedAudioInjector.injectAudio(NodeList::getInstance()->getNodeSocket(), audioMixer->getActiveSocket());
                
                // clear out the audio injector so that it doesn't re-send what we just sent
                scriptedAudioInjector.clear();
            }
        
            if (audioMixer && !audioMixer->getActiveSocket()) {
                // don't have an active socket for the audio-mixer, ping it now
                NodeList::getInstance()->pingPublicAndLocalSocketsForInactiveNode(audioMixer);
            }
            
            if (voxelScripter.getVoxelPacketSender()->voxelServersExist()) {
                // allow the scripter's call back to setup visual data
                emit willSendVisualDataCallback();
                
                // release the queue of edit voxel messages.
                voxelScripter.getVoxelPacketSender()->releaseQueuedMessages();
                
                // since we're in non-threaded mode, call process so that the packets are sent
                voxelScripter.getVoxelPacketSender()->process();

            }            
            
            if (engine.hasUncaughtException()) {
                int line = engine.uncaughtExceptionLineNumber();
                qDebug() << "Uncaught exception at line" << line << ":" << engine.uncaughtException().toString() << "\n";
            }

            while (NodeList::getInstance()->getNodeSocket()->receive((sockaddr*) &senderAddress, receivedData, &receivedBytes)
                   && packetVersionMatch(receivedData)) {
                if (receivedData[0] == PACKET_TYPE_VOXEL_JURISDICTION) {
                    voxelScripter.getJurisdictionListener()->queueReceivedPacket((sockaddr&) senderAddress,
                                                                                 receivedData,
                                                                                 receivedBytes);
                } else {
                    NodeList::getInstance()->processNodeData((sockaddr*) &senderAddress, receivedData, receivedBytes);
                }
            }
        }
    
        NodeList::getInstance()->stopSilentNodeRemovalThread(); 
        
    } else {
        // error in curl_easy_perform
        qDebug() << "curl_easy_perform for JS failed:" << curl_easy_strerror(curlResult) << "\n";
        
        // cleanup curl
        curl_easy_cleanup(curlHandle);
        curl_global_cleanup();
    }
}
Example #22
0
void TextImportDialog::doImport()
{
	// Get settings from UI
	
	QString fileName;
	QString pastedTempfile;
	
	if(m_ui->tabWidget->currentIndex() == 1)
	{
		// copy/paste buffer
		QString text = m_ui->plainTextEdit->toPlainText();
	
		pastedTempfile = tr("%1/dviz-textimportdialog-pasted.txt").arg(QDir::tempPath());
		
		QFile file(pastedTempfile);
		if(!file.open(QIODevice::WriteOnly))
		{
			QMessageBox::critical(this,tr("Can't Wriite Temp File"),QString(tr("Unable to write temp file %1")).arg(pastedTempfile));
			return;
		}
	
		QTextStream stream(&file);
		stream << text;
		file.close();
		
		fileName = pastedTempfile;
		
		qDebug() << "Wrote temp file: "<<pastedTempfile;
	}
	else
	{
		fileName = m_ui->filename->text();
		AppSettings::setPreviousPath("textimport",fileName);
	}
	
	// Store the originally-given file for the group name later
	QString originalFileName = fileName;
	
	bool isPlainText = m_ui->fmtPlain->isChecked();
	QSettings().setValue("textimport/plaintext",isPlainText);
	
	QString scriptFilename = m_ui->scriptFile->text();
	AppSettings::setPreviousPath("script",scriptFilename);
	
	QString preprocFilename = m_ui->preprocFile->text();
	AppSettings::setPreviousPath("preproc",preprocFilename);
	
	
	// Setup progress dialog
	QProgressDialog progress(QString(tr("Loading %1...")).arg(fileName),"",0,0);
	progress.setWindowModality(Qt::WindowModal);
	progress.setCancelButton(0); // hide cancel button
	progress.setWindowIcon(QIcon(":/data/icon-d.png"));
	progress.setWindowTitle(QString(tr("Loading %1")).arg(fileName));
	progress.show();
	m_progress = &progress;
	QApplication::processEvents();
	
	
	
	qDebug() << "TextImportDialog::doImport(): Start, file:"<<fileName<<", isPLain? "<<isPlainText<<", script:"<<scriptFilename<<", preproc:"<<preprocFilename;
	
	QString tempFilename;
	if(!preprocFilename.isEmpty())
	{
		tempFilename = tr("%1/dviz-textimportdialog-temp.txt").arg(QDir::tempPath());
		
		QProcess proc;
		proc.start(preprocFilename, QStringList() << fileName << tempFilename);
		
		bool result = proc.waitForFinished();
		if(!result)
		{
			QMessageBox::critical(this,tr("Pre-Processor Problem"),QString(tr("Preproc %1 didn't finish properly. Check the console - not sure why.")).arg(fileName));
			return;
		}
		
		fileName = tempFilename;
		qDebug() << "TextImportDialog::doImport(): Preprocessor completed, using preproc temp file: "<<tempFilename;
	}
	
	// Load text file
	QFile file(fileName);
	if(!file.open(QIODevice::ReadOnly))
	{
		QMessageBox::critical(this,tr("Can't Read File"),QString(tr("Unable to open %1")).arg(fileName));
		return;
	}

	QTextStream stream(&file);
	QString fileContents = stream.readAll();
	
	if(!tempFilename.isEmpty())
		file.remove(); // file is closed before it is removed
		
	// Remove the paste buffer
	//if(!pastedTempfile.isEmpty())
	//	QFile(pastedTempfile).remove();
		
	// Load script file
	QScriptEngine scriptEngine;
	if(!scriptFilename.isEmpty())
	{
		// For debug output
		static_currentScriptFile = scriptFilename;
		 
		// Install some custom functions for the script
		QScriptValue fDebug        = scriptEngine.newFunction(TextImportDialog_script_qDebug);
		QScriptValue fFindTextItem = scriptEngine.newFunction(TextImportDialog_script_findTextItem);
		QScriptValue fChangeFntSz  = scriptEngine.newFunction(TextImportDialog_script_changeFontSize);
		QScriptValue fFindFntSz    = scriptEngine.newFunction(TextImportDialog_script_findFontSize);
		QScriptValue fCntrTextBox  = scriptEngine.newFunction(TextImportDialog_script_intelligentCenterTextbox);
		QScriptValue fFileList     = scriptEngine.newFunction(TextImportDialog_script_getFileList);
		QScriptValue fChangeBg     = scriptEngine.newFunction(TextImportDialog_script_changeSlideBackground);
		QScriptValue fGuessTimeout = scriptEngine.newFunction(TextImportDialog_script_guessSlideTimeout);
		
		scriptEngine.globalObject().setProperty("debug",          fDebug);
		scriptEngine.globalObject().setProperty("findTextItem",   fFindTextItem);
		scriptEngine.globalObject().setProperty("changeFontSize", fChangeFntSz);
		scriptEngine.globalObject().setProperty("findFontSize",   fFindFntSz);
		scriptEngine.globalObject().setProperty("intelligentCenterTextbox", fCntrTextBox);
		scriptEngine.globalObject().setProperty("getFileList",    fFileList);
		scriptEngine.globalObject().setProperty("changeSlideBackground", fChangeBg);
		scriptEngine.globalObject().setProperty("guessSlideTimeout", fGuessTimeout);
		
		scriptEngine.globalObject().setProperty("InPrimaryGroup", true);
	
		QScriptValue scriptBibleBrowser = scriptEngine.newQObject(MainWindow::mw()->bibleBrowser());
		scriptEngine.globalObject().setProperty("BibleBrowser", scriptBibleBrowser);
		
 		// Read the file
		QFile scriptFile(scriptFilename);
		if(!scriptFile.open(QIODevice::ReadOnly))
		{
			QMessageBox::critical(this,tr("Can't Read Script"),QString(tr("Unable to open script %1")).arg(fileName));
			return;
		}
		
		// Evaulate the contents of the file
		QTextStream stream(&scriptFile);
		QString contents = stream.readAll();
		scriptFile.close();
		QScriptValue scriptResult = scriptEngine.evaluate(contents, fileName);
		
		// Alert user of syntax error in script
		if (scriptEngine.hasUncaughtException()) 
		{
			int line = scriptEngine.uncaughtExceptionLineNumber();
			//qDebug() << "uncaught exception at line" << line << ":" << result.toString();
			QMessageBox::critical(this,tr("Script Exception"),QString(tr("Uncaught Exception in file %1, line %2: \n\t%3\n\nImport canceled. Please fix script and try again."))
				.arg(scriptFilename)
				.arg(line)
				.arg(scriptResult.toString()));
			return;
		}
	}
	
	// Generate the slides and set the group title
	qDebug() << "TextImportDialog::doImport(): Creating template and slides for primary group";
	SlideGroup *templateGroup = getTemplate();
	SlideGroup *group = generateSlideGroup(templateGroup, fileContents, isPlainText, scriptEngine, scriptFilename);
	if(!group)
	{
		// script error or other error, cancel import
		return;
	}
	
	
	// Apply group title using the original file name, just in case we used a pre-processor
	if(group->groupTitle().isEmpty())
		group->setGroupTitle(AbstractItem::guessTitle(QFileInfo(originalFileName).baseName()));
	
	
	qDebug() << "TextImportDialog::doImport(): Checking for alternate groups";
	
	// Set a flag so scripts can respond differently for alternate groups
	if(!scriptFilename.isEmpty())
		scriptEngine.globalObject().setProperty("InPrimaryGroup", false);
	
	// Create alternate groups for outputs if present in template
	QList<Output*> allOut = AppSettings::outputs();
	foreach(Output *out, allOut)
	{
		SlideGroup *outputTemplate = templateGroup->altGroupForOutput(out);
		if(outputTemplate)
		{
			SlideGroup *existingAlt = group->altGroupForOutput(out);
			
			qDebug() << "TextImportDialog::doImport(): [prep] Creating alternate group from template for output: "<<out->name()<<", existingAlt: "<<existingAlt;
			
			SlideGroup *altGroup = generateSlideGroup(outputTemplate, fileContents, isPlainText, scriptEngine, scriptFilename, existingAlt, group);
			if(!altGroup)
			{
				// script error or other error, cancel import
				delete group;
				return;
			}
			
			altGroup->setGroupTitle(tr("Alternate %1 for %2").arg(group->groupTitle()).arg(out->name()));
			
			group->setAltGroupForOutput(out, altGroup);
		}
	}
Example #23
0
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();
	QScriptSyntaxCheckResult syntax = QScriptEngine::checkSyntax(source);
	if (syntax.state() != QScriptSyntaxCheckResult::Valid)
	{
		fprintf(stderr, "Syntax error in %s line %d: %s\n", path.toAscii().constData(), syntax.errorLineNumber(), syntax.errorMessage().toAscii().constData());
		return false;
	}
	QScriptValue result = engine->evaluate(source, path);
	if (engine->hasUncaughtException())
	{
		int line = engine->uncaughtExceptionLineNumber();
		fprintf(stderr, "Uncaught exception at line %d, file %s: %s\n", line, path.toAscii().constData(), result.toString().toAscii().constData());
		return false;
	}
	// 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));

	// Special global variables
	engine->globalObject().setProperty("me", player, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("gameTime", 2, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("difficulty", difficulty, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("mapName", "Test", QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("baseType", CAMP_BASE, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("alliancesType", ALLIANCES_TEAMS, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("powerType", LEV_MED, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("maxPlayers", 4, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("scavengers", true, QScriptValue::ReadOnly | QScriptValue::Undeletable);

	engine->globalObject().setProperty("_", engine->newFunction(js_translate));

	// 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("buildDroid", engine->newFunction(js_buildDroid));
	engine->globalObject().setProperty("enumStruct", engine->newFunction(js_enumStruct));
	engine->globalObject().setProperty("enumDroid", engine->newFunction(js_enumDroid));
	engine->globalObject().setProperty("enumGroup", engine->newFunction(js_enumGroup));
	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));

	// 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("addReticuleButton", engine->newFunction(js_addReticuleButton));
	engine->globalObject().setProperty("enableStructure", engine->newFunction(js_enableStructure));
	engine->globalObject().setProperty("makeComponentAvailable", engine->newFunction(js_makeComponentAvailable));
	engine->globalObject().setProperty("enableComponent", engine->newFunction(js_enableComponent));
	engine->globalObject().setProperty("allianceExistsBetween", engine->newFunction(js_allianceExistsBetween));

	// Set some useful constants
	engine->globalObject().setProperty("DORDER_ATTACK", 0, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DORDER_MOVE", 0, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DORDER_SCOUT", 0, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DORDER_BUILD", 0, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("mapWidth", 64, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("mapHeight", 64, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("COMMAND", 0, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("OPTIONS", 0, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("BUILD", 0, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("MANUFACTURE", 0, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("RESEARCH", 0, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("INTELMAP", 0, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DESIGN", 0, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("CANCEL", 0, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("CAMP_CLEAN", CAMP_CLEAN, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("CAMP_BASE", CAMP_BASE, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("CAMP_WALLS", CAMP_WALLS, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("NO_ALLIANCES", NO_ALLIANCES, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("ALLIANCES", ALLIANCES, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("ALLIANCES_TEAMS", ALLIANCES_TEAMS, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("BEING_BUILT", SS_BEING_BUILT, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("BUILT", SS_BUILT, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("BEING_DEMOLISHED", SS_BEING_DEMOLISHED, QScriptValue::ReadOnly | QScriptValue::Undeletable);

	// Call init
	callFunction(engine, "eventGameInit", QScriptValueList());

	// Now set gameTime to something proper
	engine->globalObject().setProperty("gameTime", 10101, QScriptValue::ReadOnly | QScriptValue::Undeletable);

	callFunction(engine, "eventStartLevel", QScriptValueList());

	// Call other events
	{
		QScriptValueList args;
		args += convDroid(engine);
		args += convStructure(engine);
		callFunction(engine, "eventDroidBuilt", args);
	}
	{
		QScriptValueList args;
		args += convStructure(engine);
		args += convObj(engine);
		callFunction(engine, "eventStructureAttacked", args);
	}

	// Now test timers
	// TODO -- implement object parameters
	QMutableListIterator<timerNode> iter(timers);
	while (iter.hasNext())
	{
		timerNode node = iter.next();
		callFunction(node.engine, node.function, QScriptValueList());
	}

	// Clean up
	delete engine;
	timers.clear();

	return true;
}
Example #24
0
void setup::setCurrentIndex(XTreeWidgetItem* item)
{
  QString uiName = item->data(0, Xt::RawRole).toString();
  QString label = "<span style=\" font-size:14pt; font-weight:600;\">%1</span></p></body></html>";

  if (_itemMap.contains(uiName) && _itemMap.value(uiName).index >= 0)
  {
    _stack->setCurrentIndex(_itemMap.value(uiName).index);
    _stackLit->setText(label.arg(item->text(0)));
    return;
  }
  else if (_itemMap.contains(uiName) && !item->isDisabled())
  {
    // First look for a class...
    QWidget *w = xtGetScreen(uiName, this);

    if (w)
      _itemMap[uiName].implementation = w;
    else
    {
      // No class, so look for an extension
      XSqlQuery screenq;
      screenq.prepare("SELECT * "
                      "  FROM uiform "
                      " WHERE((uiform_name=:uiform_name)"
                      "   AND (uiform_enabled))"
                      " ORDER BY uiform_order DESC"
                      " LIMIT 1;");
      screenq.bindValue(":uiform_name", uiName);
      screenq.exec();
      if (screenq.first())
      {     
        QUiLoader loader;
        QByteArray ba = screenq.value("uiform_source").toByteArray();
        QBuffer uiFile(&ba);
        if (!uiFile.open(QIODevice::ReadOnly))
          QMessageBox::critical(0, tr("Could not load UI"),
                                tr("<p>There was an error loading the UI Form "
                                   "from the database."));
        w = loader.load(&uiFile);
        w->setObjectName(uiName);
        uiFile.close();

        // Load scripts if applicable
        XSqlQuery scriptq;
        scriptq.prepare("SELECT script_source, script_order"
                        "  FROM script"
                        " WHERE((script_name=:script_name)"
                        "   AND (script_enabled))"
                        " ORDER BY script_order;");
        scriptq.bindValue(":script_name", uiName);
        scriptq.exec();

        QScriptEngine* engine = new QScriptEngine();
        if (_preferences->boolean("EnableScriptDebug"))
        {
          QScriptEngineDebugger* debugger = new QScriptEngineDebugger(this);
          debugger->attachTo(engine);
        }
        omfgThis->loadScriptGlobals(engine);
        QScriptValue mywindow = engine->newQObject(w);
        engine->globalObject().setProperty("mywindow", mywindow);

        while(scriptq.next())
        {
          QString script = scriptHandleIncludes(scriptq.value("script_source").toString());
          QScriptValue result = engine->evaluate(script, uiName);
          if (engine->hasUncaughtException())
          {
            int line = engine->uncaughtExceptionLineNumber();
            qDebug() << "uncaught exception at line" << line << ":" << result.toString();
          }
        }
        _itemMap[uiName].implementation = engine;
      }
    }

    if (w)
    {
      // Hide buttons out of context here
      QWidget* close = w->findChild<QWidget*>("_close");
      if (close)
        close->hide();
      QWidget* buttons = w->findChild<QDialogButtonBox*>();
      if (buttons)
        buttons->hide();

      //Set mode if applicable
      int mode = _itemMap.value(uiName).mode;
      if (mode && w->inherits("XDialog"))
      {
        XWidget* x = dynamic_cast<XWidget*>(w);
        ParameterList params;
        if (mode == cEdit)
          params.append("mode", "edit");
        else if (mode == cView)
          params.append("mode", "view");
        if (x)
          x->set(params);
      }

      int idx = _stack->count();
      _itemMap[uiName].index = idx;
      _stack->addWidget(w);
      _stack->setCurrentIndex(idx);

      _stackLit->setText(label.arg(item->text(0)));
      return;
    }
  }

  // Nothing here so try the next one
  XTreeWidgetItem* next = dynamic_cast<XTreeWidgetItem*>(_tree->itemBelow(item));
  if (next)
    setCurrentIndex(next);
}
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:
            emit departuresReady( m_objects.result->data().mid(m_published),
                    m_objects.result->features(), m_objects.result->hints(),
                    m_objects.network->lastUserUrl(), globalInfo,
                    *dynamic_cast<const DepartureRequest*>(_request),
                    couldNeedForcedUpdate );
            break;
        case ParseForArrivals: {
            emit arrivalsReady( m_objects.result->data().mid(m_published),
                    m_objects.result->features(), m_objects.result->hints(),
                    m_objects.network->lastUserUrl(), globalInfo,
                    *dynamic_cast< const ArrivalRequest* >(_request),
                    couldNeedForcedUpdate );
            break;
        }
        case ParseForJourneysByDepartureTime:
        case ParseForJourneysByArrivalTime:
            emit journeysReady( m_objects.result->data().mid(m_published),
                    m_objects.result->features(), m_objects.result->hints(),
                    m_objects.network->lastUserUrl(), globalInfo,
                    *dynamic_cast<const JourneyRequest*>(_request),
                    couldNeedForcedUpdate );
            break;
        case ParseForStopSuggestions:
            emit stopSuggestionsReady( m_objects.result->data().mid(m_published),
                    m_objects.result->features(), m_objects.result->hints(),
                    m_objects.network->lastUserUrl(), globalInfo,
                    *dynamic_cast<const StopSuggestionRequest*>(_request),
                    couldNeedForcedUpdate );
            break;

        case ParseForAdditionalData: {
            const QList< TimetableData > data = m_objects.result->data();
            if ( data.isEmpty() ) {
                handleError( i18nc("@info/plain", "Did not find any additional data.") );
                return;
            } else if ( data.count() > 1 ) {
                kWarning() << "The script added more than one result set, only the first gets used";
            }
            emit additionalDataReady( data.first(), m_objects.result->features(),
                    m_objects.result->hints(), m_objects.network->lastUserUrl(), globalInfo,
                    *dynamic_cast<const AdditionalDataRequest*>(_request),
                    couldNeedForcedUpdate );
            break;
        }

        default:
            kDebug() << "Parse mode unsupported:" << _request->parseMode();
            break;
        }
    }

    // Check for exceptions
    if ( m_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, m_engine->uncaughtExceptionLineNumber(),
                            m_engine->uncaughtException().toString()) );
        return;
    }

    // Cleanup
    m_engine->deleteLater();
    m_engine = 0;
    m_objects.storage->checkLifetime();
    m_objects.clear();
}
Example #26
0
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));
	engine->globalObject().setProperty("enableTemplate", engine->newFunction(js_enableTemplate));
	engine->globalObject().setProperty("allianceExistsBetween", engine->newFunction(js_allianceExistsBetween));
	engine->globalObject().setProperty("removeStruct", engine->newFunction(js_removeStruct));
	engine->globalObject().setProperty("removeObject", engine->newFunction(js_removeObject));
	engine->globalObject().setProperty("setScrollParams", engine->newFunction(js_setScrollParams));
	engine->globalObject().setProperty("addStructure", engine->newFunction(js_addStructure));
	engine->globalObject().setProperty("loadLevel", engine->newFunction(js_loadLevel));
	engine->globalObject().setProperty("setDroidExperience", engine->newFunction(js_setDroidExperience));
	engine->globalObject().setProperty("setNoGoArea", engine->newFunction(js_setNoGoArea));
	engine->globalObject().setProperty("setAlliance", engine->newFunction(js_setAlliance));
	engine->globalObject().setProperty("setAssemblyPoint", engine->newFunction(js_setAssemblyPoint));

	// Set some useful constants
	engine->globalObject().setProperty("DORDER_ATTACK", 0, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DORDER_MOVE", 1, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DORDER_SCOUT", 2, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DORDER_BUILD", 2, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DORDER_HELPBUILD", 3, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DORDER_LINEBUILD", 4, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DORDER_REPAIR", 5, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DORDER_RETREAT", 6, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DORDER_PATROL", 7, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DORDER_DEMOLISH", 8, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DORDER_EMBARK", 9, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DORDER_DISEMBARK", 10, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DORDER_FIRESUPPORT", 11, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DORDER_HOLD", 12, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DORDER_RTR", 13, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DORDER_RTB", 14, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DORDER_STOP", 15, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DORDER_REARM", 16, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("COMMAND", 0, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("BUILD", 1, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("MANUFACTURE", 2, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("RESEARCH", 3, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("INTELMAP", 4, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DESIGN", 5, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("CANCEL", 6, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("CAMP_CLEAN", 0, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("CAMP_BASE", 1, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("CAMP_WALLS", 2, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("NO_ALLIANCES", 0, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("ALLIANCES", 1, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("ALLIANCES_TEAMS", 2, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("BEING_BUILT", SS_BEING_BUILT, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("BUILT", SS_BUILT, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("BEING_DEMOLISHED", SS_BEING_DEMOLISHED, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DROID_CONSTRUCT", 0, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DROID_WEAPON", 1, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DROID_PERSON", 2, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DROID_REPAIR", 3, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DROID_SENSOR", 4, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DROID_ECM", 5, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DROID_CYBORG", 6, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DROID_TRANSPORTER", 7, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DROID_COMMAND", 8, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("HQ", 0, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("FACTORY", 1, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("POWER_GEN", 2, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("RESOURCE_EXTRACTOR", 3, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DEFENSE", 4, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("LASSAT", 5, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("WALL", 6, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("RESEARCH_LAB", 7, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("REPAIR_FACILITY", 8, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("CYBORG_FACTORY", 9, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("VTOL_FACTORY", 10, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("REARM_PAD", 11, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("SAT_UPLINK", 12, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("GATE", 13, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("COMMAND_CONTROL", 14, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("EASY", 0, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("MEDIUM", 1, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("HARD", 2, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("INSANE", 3, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("STRUCTURE", OBJ_STRUCTURE, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("DROID", OBJ_DROID, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("FEATURE", OBJ_FEATURE, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("POSITION", POSITION, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("AREA", AREA, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("ALL_PLAYERS", -1, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("ALLIES", -2, QScriptValue::ReadOnly | QScriptValue::Undeletable);

	QScriptValue playerData = engine->newArray(CUR_PLAYERS);
	for (int i = 0; i < CUR_PLAYERS; i++)
	{
		QScriptValue vector = engine->newObject();
		vector.setProperty("difficulty", 0, QScriptValue::ReadOnly | QScriptValue::Undeletable);
		vector.setProperty("colour", 0, QScriptValue::ReadOnly | QScriptValue::Undeletable);
		vector.setProperty("position", i, QScriptValue::ReadOnly | QScriptValue::Undeletable);
		vector.setProperty("team", i, QScriptValue::ReadOnly | QScriptValue::Undeletable);
		vector.setProperty("isAI", i != 0, QScriptValue::ReadOnly | QScriptValue::Undeletable);
		vector.setProperty("isHuman", i == 0, QScriptValue::ReadOnly | QScriptValue::Undeletable);
		playerData.setProperty(i, vector, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	}
	engine->globalObject().setProperty("playerData", playerData, QScriptValue::ReadOnly | QScriptValue::Undeletable);

	// Static map knowledge about start positions
	//== \item[derrickPositions] An array of derrick starting positions on the current map. Each item in the array is an
	//== object containing the x and y variables for a derrick.
	//== \item[startPositions] An array of player start positions on the current map. Each item in the array is an
	//== object containing the x and y variables for a player start position.
	QScriptValue startPositions = engine->newArray(CUR_PLAYERS);
	for (int i = 0; i < CUR_PLAYERS; i++)
	{
		QScriptValue vector = engine->newObject();
		vector.setProperty("x", 40, QScriptValue::ReadOnly | QScriptValue::Undeletable);
		vector.setProperty("y", 40, QScriptValue::ReadOnly | QScriptValue::Undeletable);
		startPositions.setProperty(i, vector, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	}
	QScriptValue derrickPositions = engine->newArray(6);
	for (int i = 0; i < 6; i++)
	{
		QScriptValue vector = engine->newObject();
		vector.setProperty("x", 40, QScriptValue::ReadOnly | QScriptValue::Undeletable);
		vector.setProperty("y", 40, QScriptValue::ReadOnly | QScriptValue::Undeletable);
		derrickPositions.setProperty(i, vector, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	}
	engine->globalObject().setProperty("derrickPositions", derrickPositions, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("startPositions", startPositions, QScriptValue::ReadOnly | QScriptValue::Undeletable);

	QScriptSyntaxCheckResult syntax = QScriptEngine::checkSyntax(source);
	if (syntax.state() != QScriptSyntaxCheckResult::Valid)
	{
		qFatal("Syntax error in %s line %d: %s", path.toUtf8().constData(), syntax.errorLineNumber(), syntax.errorMessage().toUtf8().constData());
		return false;
	}
	QScriptValue result = engine->evaluate(source, path);
	if (engine->hasUncaughtException())
	{
		int line = engine->uncaughtExceptionLineNumber();
		qFatal("Uncaught exception at line %d, file %s: %s", line, path.toUtf8().constData(), result.toString().toUtf8().constData());
		return false;
	}

	// Call init
	callFunction(engine, "eventGameInit", QScriptValueList());

	// Now set gameTime to something proper
	engine->globalObject().setProperty("gameTime", 10101, QScriptValue::ReadOnly | QScriptValue::Undeletable);

	callFunction(engine, "eventStartLevel", QScriptValueList());
	callFunction(engine, "eventLaunchTransporter", QScriptValueList());
	callFunction(engine, "eventReinforcementsArrived", QScriptValueList());
	callFunction(engine, "eventMissionTimeout", QScriptValueList());
	callFunction(engine, "eventVideoDone", QScriptValueList());

	// Call other events
	{
		QScriptValueList args;
		args += convDroid(engine);
		args += convStructure(engine);
		callFunction(engine, "eventDroidBuilt", args);
	}
	{
		QScriptValueList args;
		args += convStructure(engine);
		args += convObj(engine);
		callFunction(engine, "eventStructureAttacked", args);
	}
	{
		QScriptValueList args;
		args += convResearch(engine);
		args += convStructure(engine);
		callFunction(engine, "eventResearched", args);
	}
	{
		QScriptValueList args;
		args += convObj(engine);
		args += convObj(engine);
		callFunction(engine, "eventAttacked", args);
	}
	{
		QScriptValueList args;
		args += convStructure(engine);
		args += convDroid(engine);
		callFunction(engine, "eventStructureBuilt", args);
	}
	{
		QScriptValueList args;
		args += convDroid(engine);
		callFunction(engine, "eventDroidIdle", args);
	}
	{
		QScriptValueList args;
		args += QScriptValue(0);
		args += QScriptValue(1);
		args += QScriptValue("message");
		callFunction(engine, "eventChat", args);
	}
	{
		QScriptValueList args;
		args += convObj(engine);
		args += convObj(engine);
		callFunction(engine, "eventObjectSeen", args);
	}

	// Now test timers
	// TODO -- implement object parameters
	for (int i = 0; i < timers.size(); ++i)
	{
		timerNode node = timers.at(i);
		callFunction(node.engine, node.function, QScriptValueList(), true);
	}

	// Clean up
	delete engine;
	timers.clear();
	return true;
}