Beispiel #1
0
int tst_Suite::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QObject::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        QString name = testNames.at(_id);
        QString path = testsDir.absoluteFilePath(name + ".js");
        QString excludeMessage;
        if (isExcludedTest(name, &excludeMessage)) {
            QTest::qSkip(excludeMessage.toLatin1(), QTest::SkipAll, path.toLatin1(), -1);
        } else {
            QScriptEngine engine;
            engine.evaluate(mjsunitContents).toString();
            if (engine.hasUncaughtException()) {
                QStringList bt = engine.uncaughtExceptionBacktrace();
                QString err = engine.uncaughtException().toString();
                qWarning("%s\n%s", qPrintable(err), qPrintable(bt.join("\n")));
            } else {
                QScriptValue fakeFail = engine.newFunction(qscript_fail);
                fakeFail.setData(engine.globalObject().property("fail"));
                engine.globalObject().setProperty("fail", fakeFail);
                QString contents = readFile(path);
                QScriptValue ret = engine.evaluate(contents);
                if (engine.hasUncaughtException()) {
                    if (!ret.isError()) {
                        Q_ASSERT(ret.instanceOf(engine.globalObject().property("MjsUnitAssertionError")));
                        QString actual = ret.property("actual").toString();
                        QString expected = ret.property("expected").toString();
                        int lineNumber = ret.property("lineNumber").toInt32();
                        QString failMessage;
                        if (isExpectedFailure(name, actual, expected, &failMessage)) {
                            QTest::qExpectFail("", failMessage.toLatin1(),
                                               QTest::Continue, path.toLatin1(),
                                               lineNumber);
                        }
#ifdef GENERATE_ADDEXPECTEDFAILURE_CODE
                        else {
                            generatedAddExpectedFailureCode.append(
                                "    addExpectedFailure(\"" + name
                                + "\", \"" + actual + "\", \"" + expected
                                + "\", willFixInNextReleaseMessage);\n");
                        }
#endif
                        QTest::qCompare(actual, expected, "actual", "expect",
                                        path.toLatin1(), lineNumber);
                    } else {
                        int lineNumber = ret.property("lineNumber").toInt32();
                        QTest::qExpectFail("", ret.toString().toLatin1(),
                                           QTest::Continue, path.toLatin1(), lineNumber);
                        QTest::qVerify(false, ret.toString().toLatin1(), "", path.toLatin1(), lineNumber);
                    }
                }
            }
        }
        _id -= testNames.size();
    }
    return _id;
}
Beispiel #2
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;
}
void tst_QScriptV8TestSuite::runTestFunction(int testIndex)
{
    QString name = testNames.at(testIndex);
    QString path = testsDir.absoluteFilePath(name + ".js");

    QString excludeMessage;
    if (isExcludedTest(name, &excludeMessage)) {
        QTest::qSkip(excludeMessage.toLatin1(), path.toLatin1(), -1);
        return;
    }

    QScriptEngine engine;
    engine.evaluate(mjsunitContents);
    if (engine.hasUncaughtException()) {
        QStringList bt = engine.uncaughtExceptionBacktrace();
        QString err = engine.uncaughtException().toString();
        qWarning("%s\n%s", qPrintable(err), qPrintable(bt.join("\n")));
    } else {
        // Prepare to intercept calls to mjsunit's fail() function.
        QScriptValue fakeFail = engine.newFunction(qscript_fail);
        fakeFail.setData(engine.globalObject().property("fail"));
        engine.globalObject().setProperty("fail", fakeFail);

        QString contents = readFile(path);
        QScriptValue ret = engine.evaluate(contents);
        if (engine.hasUncaughtException()) {
            if (!ret.isError()) {
                int lineNumber = ret.property("lineNumber").toInt32();
                QTest::qVerify(ret.instanceOf(engine.globalObject().property("MjsUnitAssertionError")),
                               ret.toString().toLatin1(),
                               "",
                               path.toLatin1(),
                               lineNumber);
                QString actual = ret.property("actual").toString();
                QString expected = ret.property("expected").toString();
                QString failMessage;
                if (shouldGenerateExpectedFailures) {
                    if (ret.property("message").isString())
                        failMessage = ret.property("message").toString();
                    addExpectedFailure(name, actual, expected, failMessage);
                } else if (isExpectedFailure(name, actual, expected, &failMessage)) {
                    QTest::qExpectFail("", failMessage.toLatin1(),
                                       QTest::Continue, path.toLatin1(),
                                       lineNumber);
                }
                QTest::qCompare(actual, expected, "actual", "expect",
                                path.toLatin1(), lineNumber);
            } else {
                int lineNumber = ret.property("lineNumber").toInt32();
                QTest::qExpectFail("", ret.toString().toLatin1(),
                                   QTest::Continue, path.toLatin1(), lineNumber);
                QTest::qVerify(false, ret.toString().toLatin1(), "", path.toLatin1(), lineNumber);
            }
        }
    }
}
QScriptValue QDeclarativeQtScriptExpression::eval(QObject *secondaryScope, bool *isUndefined)
{
    Q_ASSERT(context() && context()->engine);

    DeleteWatcher watcher(this);

    QDeclarativeEngine *engine = context()->engine;
    QDeclarativeEnginePrivate *ep = QDeclarativeEnginePrivate::get(engine);

    QScriptEngine *scriptEngine = QDeclarativeEnginePrivate::getScriptEngine(engine);

    QDeclarativeContextData *oldSharedContext = 0;
    QObject *oldSharedScope = 0;
    QObject *oldOverride = 0;
    bool isShared = (expressionFunctionMode == SharedContext);

    if (isShared) {
        oldSharedContext = ep->sharedContext;
        oldSharedScope = ep->sharedScope;
        ep->sharedContext = context();
        ep->sharedScope = scopeObject;
    } else {
        oldOverride = ep->contextClass->setOverrideObject(expressionContext, secondaryScope);
    }

    QScriptValue thisObject;
    if (evalFlags & RequiresThisObject)
        thisObject = ep->objectClass->newQObject(scopeObject);
    QScriptValue svalue = expressionFunction.call(thisObject); // This could cause this c++ object to be deleted

    if (isShared) {
        ep->sharedContext = oldSharedContext;
        ep->sharedScope = oldSharedScope;
    } else if (!watcher.wasDeleted()) {
        ep->contextClass->setOverrideObject(expressionContext, oldOverride);
    }

    if (isUndefined)
        *isUndefined = svalue.isUndefined() || scriptEngine->hasUncaughtException();

    // Handle exception
    if (scriptEngine->hasUncaughtException()) {
        if (!watcher.wasDeleted()) 
           QDeclarativeExpressionPrivate::exceptionToError(scriptEngine, error);

       scriptEngine->clearExceptions();
       return QScriptValue();
    } else {
        if (!watcher.wasDeleted())
            error = QDeclarativeError();

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

    QScriptValue result = eng.evaluate("try { eval(\"foo = 123;\\n this[is{a{syntax|error@#$%@#% \"); } 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);
}
Beispiel #6
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();
}
Beispiel #7
0
 void addObject(QObject* object, const QString& name = QString()) {
     Q_ASSERT( m_engine );
     Q_ASSERT( ! m_engine->hasUncaughtException() );
     QScriptValue global = m_engine->globalObject();
     QScriptValue value = m_engine->newQObject(object, QScriptEngine::AutoOwnership);
     global.setProperty(name.isEmpty() ? object->objectName() : name, value);
 }
Beispiel #8
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();
}
Beispiel #9
0
World *ScriptEvaluator::evaluate(const QString &script)
{
    QScriptEngine engine;

    World* world = new World();
    QScriptValue worldValue = engine.newQObject(world);
    engine.globalObject().setProperty("world", worldValue);

    QScriptValue directionalLightClass = engine.scriptValueFromQMetaObject<DirectionalLight>();
    engine.globalObject().setProperty("DirectionalLight", directionalLightClass);

    engine.evaluate(script);
    if (engine.hasUncaughtException())
    {
        QMessageBox messageBox;
        messageBox.setIcon(QMessageBox::Warning);
        messageBox.setWindowTitle("Script error");
        messageBox.setText("An error occurred while executing the script.");
        messageBox.setInformativeText(engine.uncaughtException().toString());
        messageBox.setDetailedText(engine.uncaughtExceptionBacktrace().join("\n"));
        messageBox.exec();
        return 0;
    }

    return world;
}
Beispiel #10
0
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QScriptEngine engine;
    QFile scriptFile(":/object.js");
    scriptFile.open(QFile::ReadOnly);
    engine.evaluate(scriptFile.readAll());
    scriptFile.close();

    QTextEdit editor;
    QTimer timer;
    QScriptValue constructor = engine.evaluate("Object");
    QScriptValueList arguments;
    arguments << engine.newQObject(&timer);
    arguments << engine.newQObject(&editor);
    QScriptValue object = constructor.construct(arguments);
    if (engine.hasUncaughtException()) {
        qDebug() << engine.uncaughtException().toString();
    }

    editor.show();
    timer.start(1000);

    return app.exec();
}
Beispiel #11
0
QVariant JsonTranslationService::parseJson(const QByteArray &json)
{
#if QT_VERSION < QT_VERSION_CHECK(5,0,0)
    QString js;
    js.reserve(json.size() + 2);
    js.append("(").append(QString::fromUtf8(json)).append(")");

    static QScriptEngine engine;
    if (!engine.canEvaluate(js)) {
        m_error = tr("Couldn't parse response from the server because of an error: \"%1\"")
                  .arg(tr("Can't evaluate JSON data"));
        return QVariant();
    }

    QScriptValue data = engine.evaluate(js);
    if (engine.hasUncaughtException()) {
        m_error = tr("Couldn't parse response from the server because of an error: \"%1\"")
                  .arg(engine.uncaughtException().toString());
        return QVariant();
    }

    return data.toVariant();
#else
    QJsonParseError err;
    QJsonDocument doc = QJsonDocument::fromJson(json, &err);

    if (err.error != QJsonParseError::NoError) {
        m_error = tr("Couldn't parse response from the server because of an error: \"%1\"")
                  .arg(err.errorString());
        return QVariant();
    }

    return doc.toVariant();
#endif
}
Beispiel #12
0
            bool init() {
                if( m_script->action()->hadError() )
                    m_script->action()->clearError();

                delete m_engine;
                m_engine = new QScriptEngine();

                // load the Qross QScriptExtensionPlugin plugin that provides
                // us a bridge between Qross and QtScript. See here plugin.h
                m_engine->importExtension("qross");
                if( m_engine->hasUncaughtException() ) {
                    handleException();
                    delete m_engine;
                    m_engine = 0;
                    return false;
                }

                // the Qross QScriptExtensionPlugin exports the "Qross" property.
                QScriptValue global = m_engine->globalObject();
                m_qross = global.property("Qross");
                Q_ASSERT( m_qross.isQObject() );
                Q_ASSERT( ! m_engine->hasUncaughtException() );

                // Attach our Qross::Action instance to be able to access it in
                // scripts. Just like at the Kjs-backend we publish our own
                // action as "self".
                m_self = m_engine->newQObject( m_script->action() );
                global.setProperty("self", m_self, QScriptValue::ReadOnly|QScriptValue::Undeletable);

                { // publish the global objects.
                    QHash< QString, QObject* > objects = Manager::self().objects();
                    QHash< QString, QObject* >::Iterator it(objects.begin()), end(objects.end());
                    for(; it != end; ++it)
                        global.setProperty(it.key(), m_engine->newQObject( it.value() ) );
                }

                { // publish the local objects.
                    QHash< QString, QObject* > objects = m_script->action()->objects();
                    QHash< QString, QObject* >::Iterator it(objects.begin()), end(objects.end());
                    for(; it != end; ++it) {
                        copyEnumsToProperties( it.value() );
                        global.setProperty(it.key(), m_engine->newQObject( it.value() ) );
                    }
                }

                return ! m_engine->hasUncaughtException();
            }
Beispiel #13
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();
 }
Beispiel #14
0
JsonValue *JsonValue::create(const QString &s, JsonMemoryPool *pool)
{
    QScriptEngine engine;
    QScriptValue jsonParser = engine.evaluate(QLatin1String("JSON.parse"));
    QScriptValue value = jsonParser.call(QScriptValue(), QScriptValueList() << s);
    if (engine.hasUncaughtException() || !value.isValid())
        return 0;

    return build(value.toVariant(), pool);
}
Beispiel #15
0
            void connectFunctions(ChildrenInterface* children) {
                Q_ASSERT( m_engine );
                Q_ASSERT( ! m_engine->hasUncaughtException() );
                QString eval;
                QScriptValue global = m_engine->globalObject();
                QHashIterator< QString, ChildrenInterface::Options > it( children->objectOptions() );
                while(it.hasNext()) {
                    it.next();
                    if( it.value() & ChildrenInterface::AutoConnectSignals ) {
                        QObject* sender = children->object(it.key());
                        if( ! sender )
                            continue;
                        QScriptValue obj = m_engine->globalObject().property(it.key());
                        if( ! obj.isQObject() )
                            continue;
                        const QMetaObject* mo = sender->metaObject();
                        const int count = mo->methodCount();
                        for(int i = 0; i < count; ++i) {
                            QMetaMethod mm = mo->method(i);
#if QT_VERSION < 0x050000
                            const QString signature = mm.signature();
#else
                            const QString signature = mm.methodSignature();
#endif
                            const QString name = signature.left(signature.indexOf('('));
                            if( mm.methodType() == QMetaMethod::Signal ) {
                                QScriptValue func = global.property(name);
                                if( ! func.isFunction() ) {
                                    //qrossdebug( QString("EcmaScript::connectFunctions No function to connect with %1.%2").arg(it.key()).arg(name) );
                                    continue;
                                }
                                qrossdebug( QString("EcmaScript::connectFunctions Connecting with %1.%2").arg(it.key()).arg(name) );
                                eval += QString("try { %1.%2.connect(%3); } catch(e) { print(e); }\n").arg(it.key()).arg(name).arg(name);
                            }
                        }
                    }
                }
                Q_ASSERT( ! m_engine->hasUncaughtException() );
                if( ! eval.isNull() ) {
                    m_engine->evaluate(eval);
                    Q_ASSERT( ! m_engine->hasUncaughtException() );
                }
            }
Beispiel #16
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;
}
void tst_QScriptContext::argumentsObjectInNative()
{
    {
        QScriptEngine eng;
        QScriptValue fun = eng.newFunction(argumentsObjectInNative_test1);
        QScriptValueList args;
        args << QScriptValue(&eng, 123.0);
        args << QScriptValue(&eng, QString::fromLatin1("456"));
        QScriptValue result = fun.call(eng.undefinedValue(), args);
        QVERIFY(!eng.hasUncaughtException());
        QCOMPARE(result.toString(), QString::fromLatin1("success"));
    }
    {
        QScriptEngine eng;
        QScriptValue fun = eng.newFunction(argumentsObjectInNative_test1);
        eng.globalObject().setProperty("func", fun);
        QScriptValue result = eng.evaluate("func(123.0 , 456);");
        QVERIFY(!eng.hasUncaughtException());
        QCOMPARE(result.toString(), QString::fromLatin1("success"));
    }
}
Beispiel #18
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::throwValue()
{
    QScriptEngine eng;

    QScriptValue fun = eng.newFunction(throw_value);
    eng.globalObject().setProperty("throw_value", fun);

    {
        QScriptValue result = eng.evaluate("throw_value(123)");
        QCOMPARE(result.isError(), false);
        QCOMPARE(result.toNumber(), 123.0);
        QCOMPARE(eng.hasUncaughtException(), true);
    }
}
Beispiel #20
0
int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);

    QScriptEngine engine;
    const QString theProgram = 
        "Math.log(25);"
    ;

    QScriptValue v = false;
    qDebug() << "Valid?" << v.isValid();
    engine.setGlobalObject(v);
    qDebug() << engine.evaluate(theProgram).toString();
    qDebug() << engine.hasUncaughtException();
}
Beispiel #21
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;
	}
}
Beispiel #22
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;
}
Beispiel #23
0
void FormulaDialog::accept()
{
    QScriptEngine eng;

    QString exp = ui->formula->text();
    exp.replace("%1", "%%1");
    exp.replace("%n", "%1");

    eng.evaluate(exp.arg(10));
    if(eng.hasUncaughtException())
    {
        Utils::showErrorBox(tr("There is an error in the formula, following exception was thrown:\n\n%1")
                            .arg(eng.uncaughtException().toString()));
        return;
    }
    QDialog::accept();
}
Beispiel #24
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();
}
void tst_QScriptContext::backtrace()
{
    QFETCH(QString, code);
    QFETCH(QStringList, expectedbacktrace);

    QScriptEngine eng;
    eng.globalObject().setProperty("bt", eng.newFunction(getBacktrace));
    eng.globalObject().setProperty("custom_eval", eng.newFunction(custom_eval));
    eng.globalObject().setProperty("custom_call", eng.newFunction(custom_call));
    eng.globalObject().setProperty("native_recurse", eng.newFunction(native_recurse));

    QString fileName = "testfile";
    QScriptValue ret = eng.evaluate(code, fileName);
    QVERIFY(!eng.hasUncaughtException());
    QVERIFY(ret.isArray());
    QStringList slist = qscriptvalue_cast<QStringList>(ret);
    QCOMPARE(slist, expectedbacktrace);
}
Beispiel #26
0
void ScriptForm::accept()
{
    m_script = textEdit->toPlainText();
    QScriptEngine javaScriptParser;
    int errorLineNumber = 0;
    QString errorMessage;
#if QT_VERSION >= 0x040500
    QScriptSyntaxCheckResult syntaxResult =
            javaScriptParser.checkSyntax(m_script);
    if (syntaxResult.state() != QScriptSyntaxCheckResult::Valid) {
        errorLineNumber = syntaxResult.errorLineNumber();
        errorMessage = syntaxResult.errorMessage();
        if (errorMessage.isEmpty())
            errorMessage = tr("Syntax Error");
    }
#else
    QScriptValue value(&javaScriptParser, 0);
    javaScriptParser.globalObject().setProperty("cellRow", value);
    javaScriptParser.globalObject().setProperty("cellColumn", value);
    javaScriptParser.globalObject().setProperty("cellValue", value);
    QScriptValue result = javaScriptParser.evaluate(m_script);
    if (javaScriptParser.hasUncaughtException()) {
        errorLineNumber = javaScriptParser
                .uncaughtExceptionLineNumber();
        errorMessage = javaScriptParser.uncaughtException()
                .toString();
    }
#endif
    if (!errorMessage.isEmpty()) {
        AQP::warning(this, tr("Error"),
                tr("Invalid script on line %1:\n%2")
                   .arg(errorLineNumber).arg(errorMessage));
        QTextCursor cursor = textEdit->textCursor();
        cursor.clearSelection();
        cursor.movePosition(QTextCursor::Start);
        cursor.movePosition(QTextCursor::Down,
                QTextCursor::MoveAnchor, errorLineNumber - 1);
        cursor.select(QTextCursor::LineUnderCursor);
        textEdit->setTextCursor(cursor);
    }
    else
        QDialog::accept();
}
Beispiel #27
0
bool JSScript::execute(TWScriptAPI *tw) const
{
	QFile scriptFile(m_Filename);
	if (!scriptFile.open(QIODevice::ReadOnly)) {
		// handle error
		return false;
	}
	QTextStream stream(&scriptFile);
	stream.setCodec(m_Codec);
	QString contents = stream.readAll();
	scriptFile.close();
	
	QScriptEngine engine;
	QScriptValue twObject = engine.newQObject(tw);
	engine.globalObject().setProperty("TW", twObject);
	
	QScriptValue val;

#if QT_VERSION >= 0x040500
	QSETTINGS_OBJECT(settings);
	if (settings.value("scriptDebugger", false).toBool()) {
		QScriptEngineDebugger debugger;
		debugger.attachTo(&engine);
		val = engine.evaluate(contents, m_Filename);
	}
	else {
		val = engine.evaluate(contents, m_Filename);
	}
#else
	val = engine.evaluate(contents, m_Filename);
#endif

	if (engine.hasUncaughtException()) {
		tw->SetResult(engine.uncaughtException().toString());
		return false;
	}
	else {
		if (!val.isUndefined()) {
			tw->SetResult(convertValue(val));
		}
		return true;
	}
}
Beispiel #28
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();
}
Beispiel #29
0
Address AddressValidator::toAddress( const QString& string, AddressType* addressType) const
{
    Address address;

    QString expression = string.trimmed();

    if( addressType )
    {
        const AddressType type =
            expression.startsWith(QLatin1Char('+')) ? RelativeForwards :
            expression.startsWith(QLatin1Char('-')) ? RelativeBackwards :
            /* else */                   AbsoluteAddress;

        if( type != AbsoluteAddress )
            expression.remove( 0, 1 );

        *addressType = type;
    }

    if( mCodecId == ExpressionCoding )
    {
        QScriptEngine evaluator;
        QScriptValue value = evaluator.evaluate( expression );
        address = value.toInt32();
        qCDebug(LOG_KASTEN_OKTETA_GUI) << "expression " << expression << " evaluated to: " << address;

        if( evaluator.hasUncaughtException() )
        {
            qCWarning(LOG_KASTEN_OKTETA_GUI) << "evaluation error: " << evaluator.uncaughtExceptionBacktrace();
            if( addressType )
                *addressType = InvalidAddressType;
        }
    }
    else
    {
        const bool isHexadecimal = ( mCodecId == HexadecimalCoding );
        const int base = isHexadecimal ? 16 : 10;
        address = expression.toInt( 0, base );
    }

    return address;
}
Beispiel #30
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();
}