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(); }
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(); }
int main(int argc, char *argv[]) { Q_INIT_RESOURCE(tetrix); //! [1] QApplication app(argc, argv); QScriptEngine engine; QScriptValue Qt = engine.newQMetaObject(QtMetaObject::get()); Qt.setProperty("App", engine.newQObject(&app)); engine.globalObject().setProperty("Qt", Qt); //! [1] #ifndef QT_NO_SCRIPTTOOLS QScriptEngineDebugger debugger; debugger.attachTo(&engine); QMainWindow *debugWindow = debugger.standardWindow(); debugWindow->resize(1024, 640); #endif //! [2] evaluateFile(engine, ":/tetrixpiece.js"); evaluateFile(engine, ":/tetrixboard.js"); evaluateFile(engine, ":/tetrixwindow.js"); //! [2] //! [3] TetrixUiLoader loader; QFile uiFile(":/tetrixwindow.ui"); uiFile.open(QIODevice::ReadOnly); QWidget *ui = loader.load(&uiFile); uiFile.close(); QScriptValue ctor = engine.evaluate("TetrixWindow"); QScriptValue scriptUi = engine.newQObject(ui, QScriptEngine::ScriptOwnership); QScriptValue tetrix = ctor.construct(QScriptValueList() << scriptUi); //! [3] QPushButton *debugButton = qFindChild<QPushButton*>(ui, "debugButton"); #ifndef QT_NO_SCRIPTTOOLS QObject::connect(debugButton, SIGNAL(clicked()), debugger.action(QScriptEngineDebugger::InterruptAction), SIGNAL(triggered())); QObject::connect(debugButton, SIGNAL(clicked()), debugWindow, SLOT(show())); #else debugButton->hide(); #endif //! [4] ui->resize(550, 370); ui->show(); qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); return app.exec(); //! [4] }
void CodeClass::throwError(QScriptContext *context, QScriptEngine *engine, const QString &errorType, const QString &message, const QString &parent) { QScriptValue errorTypeValue = engine->globalObject().property(errorType); if(!errorTypeValue.isValid()) { errorTypeValue = engine->newFunction(emptyFunction); engine->globalObject().setProperty(errorType, errorTypeValue); errorTypeValue.setProperty("prototype", engine->globalObject().property(parent).construct()); } QScriptValue thrownError = errorTypeValue.construct(); thrownError.setProperty("message", message); thrownError.setProperty("name", errorType); context->throwValue(thrownError); }
QScriptValue EntityTreeRenderer::loadEntityScript(EntityItem* entity) { if (!entity) { return QScriptValue(); // no entity... } EntityItemID entityID = entity->getEntityItemID(); if (_entityScripts.contains(entityID)) { EntityScriptDetails details = _entityScripts[entityID]; // check to make sure our script text hasn't changed on us since we last loaded it if (details.scriptText == entity->getScript()) { return details.scriptObject; // previously loaded } // if we got here, then we previously loaded a script, but the entity's script value // has changed and so we need to reload it. _entityScripts.remove(entityID); } if (entity->getScript().isEmpty()) { return QScriptValue(); // no script } QString scriptContents = loadScriptContents(entity->getScript()); QScriptSyntaxCheckResult syntaxCheck = QScriptEngine::checkSyntax(scriptContents); if (syntaxCheck.state() != QScriptSyntaxCheckResult::Valid) { qDebug() << "EntityTreeRenderer::loadEntityScript() entity:" << entityID; qDebug() << " " << syntaxCheck.errorMessage() << ":" << syntaxCheck.errorLineNumber() << syntaxCheck.errorColumnNumber(); qDebug() << " SCRIPT:" << entity->getScript(); return QScriptValue(); // invalid script } QScriptValue entityScriptConstructor = _entitiesScriptEngine->evaluate(scriptContents); if (!entityScriptConstructor.isFunction()) { qDebug() << "EntityTreeRenderer::loadEntityScript() entity:" << entityID; qDebug() << " NOT CONSTRUCTOR"; qDebug() << " SCRIPT:" << entity->getScript(); return QScriptValue(); // invalid script } QScriptValue entityScriptObject = entityScriptConstructor.construct(); EntityScriptDetails newDetails = { entity->getScript(), entityScriptObject }; _entityScripts[entityID] = newDetails; return entityScriptObject; // newly constructed }
int main(int argc, char **argv) { Q_INIT_RESOURCE(calculator); QApplication app(argc, argv); //! [0a] QScriptEngine engine; //! [0a] #if !defined(QT_NO_SCRIPTTOOLS) QScriptEngineDebugger debugger; debugger.attachTo(&engine); QMainWindow *debugWindow = debugger.standardWindow(); debugWindow->resize(1024, 640); #endif //! [0b] QString scriptFileName(":/calculator.js"); QFile scriptFile(scriptFileName); scriptFile.open(QIODevice::ReadOnly); engine.evaluate(scriptFile.readAll(), scriptFileName); scriptFile.close(); //! [0b] //! [1] QUiLoader loader; QFile uiFile(":/calculator.ui"); uiFile.open(QIODevice::ReadOnly); QWidget *ui = loader.load(&uiFile); uiFile.close(); //! [1] //! [2] QScriptValue ctor = engine.evaluate("Calculator"); QScriptValue scriptUi = engine.newQObject(ui, QScriptEngine::ScriptOwnership); QScriptValue calc = ctor.construct(QScriptValueList() << scriptUi); //! [2] #if !defined(QT_NO_SCRIPTTOOLS) QLineEdit *display = qFindChild<QLineEdit*>(ui, "display"); QObject::connect(display, SIGNAL(returnPressed()), debugWindow, SLOT(show())); #endif //! [3] ui->show(); return app.exec(); //! [3] }
void tst_QScriptContext::calledAsConstructor() { QScriptEngine eng; QScriptValue fun1 = eng.newFunction(storeCalledAsConstructor); { fun1.call(); QVERIFY(!fun1.property("calledAsConstructor").toBool()); fun1.construct(); QVERIFY(fun1.property("calledAsConstructor").toBool()); } { QScriptValue fun = eng.newFunction(storeCalledAsConstructorV2, (void*)0); fun.call(); QVERIFY(!fun.property("calledAsConstructor").toBool()); fun.construct(); QVERIFY(fun.property("calledAsConstructor").toBool()); } { eng.globalObject().setProperty("fun1", fun1); eng.evaluate("fun1();"); QVERIFY(!fun1.property("calledAsConstructor").toBool()); eng.evaluate("new fun1();"); QVERIFY(fun1.property("calledAsConstructor").toBool()); } { QScriptValue fun3 = eng.newFunction(storeCalledAsConstructorV3); eng.globalObject().setProperty("fun3", fun3); eng.evaluate("function test() { fun3() }"); eng.evaluate("test();"); QVERIFY(!fun3.property("calledAsConstructor").toBool()); eng.evaluate("new test();"); if (qt_script_isJITEnabled()) QEXPECT_FAIL("", "QTBUG-6132: calledAsConstructor is not correctly set for JS functions when JIT is enabled", Continue); QVERIFY(fun3.property("calledAsConstructor").toBool()); } }
QScriptValue EntityTreeRenderer::loadEntityScript(EntityItem* entity) { if (!entity) { return QScriptValue(); // no entity... } // NOTE: we keep local variables for the entityID and the script because // below in loadScriptContents() it's possible for us to execute the // application event loop, which may cause our entity to be deleted on // us. We don't really need access the entity after this point, can // can accomplish all we need to here with just the script "text" and the ID. EntityItemID entityID = entity->getEntityItemID(); QString entityScript = entity->getScript(); if (_entityScripts.contains(entityID)) { EntityScriptDetails details = _entityScripts[entityID]; // check to make sure our script text hasn't changed on us since we last loaded it if (details.scriptText == entityScript) { return details.scriptObject; // previously loaded } // if we got here, then we previously loaded a script, but the entity's script value // has changed and so we need to reload it. _entityScripts.remove(entityID); } if (entityScript.isEmpty()) { return QScriptValue(); // no script } bool isURL = false; // loadScriptContents() will tell us if this is a URL or just text. QString scriptContents = loadScriptContents(entityScript, isURL); QScriptSyntaxCheckResult syntaxCheck = QScriptEngine::checkSyntax(scriptContents); if (syntaxCheck.state() != QScriptSyntaxCheckResult::Valid) { qDebug() << "EntityTreeRenderer::loadEntityScript() entity:" << entityID; qDebug() << " " << syntaxCheck.errorMessage() << ":" << syntaxCheck.errorLineNumber() << syntaxCheck.errorColumnNumber(); qDebug() << " SCRIPT:" << entityScript; return QScriptValue(); // invalid script } if (isURL) { _entitiesScriptEngine->setParentURL(entity->getScript()); } QScriptValue entityScriptConstructor = _sandboxScriptEngine->evaluate(scriptContents); if (!entityScriptConstructor.isFunction()) { qDebug() << "EntityTreeRenderer::loadEntityScript() entity:" << entityID; qDebug() << " NOT CONSTRUCTOR"; qDebug() << " SCRIPT:" << entityScript; return QScriptValue(); // invalid script } else { entityScriptConstructor = _entitiesScriptEngine->evaluate(scriptContents); } QScriptValue entityScriptObject = entityScriptConstructor.construct(); EntityScriptDetails newDetails = { entityScript, entityScriptObject }; _entityScripts[entityID] = newDetails; if (isURL) { _entitiesScriptEngine->setParentURL(""); } return entityScriptObject; // newly constructed }
void tst_QScriptClass::extension() { QScriptEngine eng; { TestClass cls(&eng); cls.setCallableMode(TestClass::NotCallable); QVERIFY(!cls.supportsExtension(QScriptClass::Callable)); QVERIFY(!cls.supportsExtension(QScriptClass::HasInstance)); QScriptValue obj = eng.newObject(&cls); QVERIFY(!obj.call().isValid()); QCOMPARE((int)cls.lastExtensionType(), -1); QVERIFY(!obj.instanceOf(obj)); QCOMPARE((int)cls.lastExtensionType(), -1); } // Callable { TestClass cls(&eng); cls.setCallableMode(TestClass::CallableReturnsSum); QVERIFY(cls.supportsExtension(QScriptClass::Callable)); QScriptValue obj = eng.newObject(&cls); eng.globalObject().setProperty("obj", obj); obj.setProperty("one", QScriptValue(&eng, 1)); obj.setProperty("two", QScriptValue(&eng, 2)); obj.setProperty("three", QScriptValue(&eng, 3)); // From C++ cls.clearReceivedArgs(); { QScriptValueList args; args << QScriptValue(&eng, 4) << QScriptValue(&eng, 5); QScriptValue ret = obj.call(obj, args); QCOMPARE(cls.lastExtensionType(), QScriptClass::Callable); QCOMPARE(cls.lastExtensionArgument().userType(), qMetaTypeId<QScriptContext*>()); QVERIFY(ret.isNumber()); QCOMPARE(ret.toNumber(), qsreal(15)); } // From JS cls.clearReceivedArgs(); { QScriptValue ret = eng.evaluate("obj(4, 5)"); QCOMPARE(cls.lastExtensionType(), QScriptClass::Callable); QCOMPARE(cls.lastExtensionArgument().userType(), qMetaTypeId<QScriptContext*>()); QVERIFY(ret.isNumber()); QCOMPARE(ret.toNumber(), qsreal(15)); } cls.setCallableMode(TestClass::CallableReturnsArgument); // From C++ cls.clearReceivedArgs(); { QScriptValue ret = obj.call(obj, QScriptValueList() << 123); QCOMPARE(cls.lastExtensionType(), QScriptClass::Callable); QCOMPARE(cls.lastExtensionArgument().userType(), qMetaTypeId<QScriptContext*>()); QVERIFY(ret.isNumber()); QCOMPARE(ret.toInt32(), 123); } cls.clearReceivedArgs(); { QScriptValue ret = obj.call(obj, QScriptValueList() << true); QCOMPARE(cls.lastExtensionType(), QScriptClass::Callable); QCOMPARE(cls.lastExtensionArgument().userType(), qMetaTypeId<QScriptContext*>()); QVERIFY(ret.isBoolean()); QCOMPARE(ret.toBoolean(), true); } { QScriptValue ret = obj.call(obj, QScriptValueList() << QString::fromLatin1("ciao")); QVERIFY(ret.isString()); QCOMPARE(ret.toString(), QString::fromLatin1("ciao")); } { QScriptValue objobj = eng.newObject(); QScriptValue ret = obj.call(obj, QScriptValueList() << objobj); QVERIFY(ret.isObject()); QVERIFY(ret.strictlyEquals(objobj)); } { QScriptValue ret = obj.call(obj, QScriptValueList() << QScriptValue()); QVERIFY(ret.isUndefined()); } // From JS cls.clearReceivedArgs(); { QScriptValue ret = eng.evaluate("obj(123)"); QVERIFY(ret.isNumber()); QCOMPARE(ret.toInt32(), 123); } cls.setCallableMode(TestClass::CallableReturnsInvalidVariant); { QScriptValue ret = obj.call(obj); QVERIFY(ret.isUndefined()); } cls.setCallableMode(TestClass::CallableReturnsThisObject); // From C++ { QScriptValue ret = obj.call(obj); QVERIFY(ret.isObject()); QVERIFY(ret.strictlyEquals(obj)); } // From JS { QScriptValue ret = eng.evaluate("obj()"); QVERIFY(ret.isObject()); QVERIFY(ret.strictlyEquals(eng.globalObject())); } cls.setCallableMode(TestClass::CallableReturnsCallee); // From C++ { QScriptValue ret = obj.call(); QVERIFY(ret.isObject()); QVERIFY(ret.strictlyEquals(obj)); } // From JS { QScriptValue ret = eng.evaluate("obj()"); QVERIFY(ret.isObject()); QVERIFY(ret.strictlyEquals(obj)); } cls.setCallableMode(TestClass::CallableReturnsArgumentsObject); // From C++ { QScriptValue ret = obj.call(obj, QScriptValueList() << 123); QVERIFY(ret.isObject()); QVERIFY(ret.property("length").isNumber()); QCOMPARE(ret.property("length").toInt32(), 1); QVERIFY(ret.property(0).isNumber()); QCOMPARE(ret.property(0).toInt32(), 123); } // From JS { QScriptValue ret = eng.evaluate("obj(123)"); QVERIFY(ret.isObject()); QVERIFY(ret.property("length").isNumber()); QCOMPARE(ret.property("length").toInt32(), 1); QVERIFY(ret.property(0).isNumber()); QCOMPARE(ret.property(0).toInt32(), 123); } // construct() // From C++ cls.clearReceivedArgs(); cls.setCallableMode(TestClass::CallableReturnsGlobalObject); { QScriptValue ret = obj.construct(); QCOMPARE(cls.lastExtensionType(), QScriptClass::Callable); QCOMPARE(cls.lastExtensionArgument().userType(), qMetaTypeId<QScriptContext*>()); QVERIFY(ret.isObject()); QVERIFY(ret.strictlyEquals(eng.globalObject())); } // From JS cls.clearReceivedArgs(); { QScriptValue ret = eng.evaluate("new obj()"); QCOMPARE(cls.lastExtensionType(), QScriptClass::Callable); QCOMPARE(cls.lastExtensionArgument().userType(), qMetaTypeId<QScriptContext*>()); QVERIFY(ret.isObject()); QVERIFY(ret.strictlyEquals(eng.globalObject())); } // From C++ cls.clearReceivedArgs(); cls.setCallableMode(TestClass::CallableInitializesThisObject); { QScriptValue ret = obj.construct(); QCOMPARE(cls.lastExtensionType(), QScriptClass::Callable); QCOMPARE(cls.lastExtensionArgument().userType(), qMetaTypeId<QScriptContext*>()); QVERIFY(ret.isQObject()); QCOMPARE(ret.toQObject(), (QObject*)&eng); } // From JS cls.clearReceivedArgs(); { QScriptValue ret = eng.evaluate("new obj()"); QCOMPARE(cls.lastExtensionType(), QScriptClass::Callable); QCOMPARE(cls.lastExtensionArgument().userType(), qMetaTypeId<QScriptContext*>()); QVERIFY(ret.isQObject()); QCOMPARE(ret.toQObject(), (QObject*)&eng); } } // HasInstance { TestClass cls(&eng); cls.setHasInstance(true); QVERIFY(cls.supportsExtension(QScriptClass::HasInstance)); QScriptValue obj = eng.newObject(&cls); obj.setProperty("foo", QScriptValue(&eng, 123)); QScriptValue plain = eng.newObject(); QVERIFY(!plain.instanceOf(obj)); eng.globalObject().setProperty("HasInstanceTester", obj); eng.globalObject().setProperty("hasInstanceValue", plain); cls.clearReceivedArgs(); { QScriptValue ret = eng.evaluate("hasInstanceValue instanceof HasInstanceTester"); QCOMPARE(cls.lastExtensionType(), QScriptClass::HasInstance); QCOMPARE(cls.lastExtensionArgument().userType(), qMetaTypeId<QScriptValueList>()); QScriptValueList lst = qvariant_cast<QScriptValueList>(cls.lastExtensionArgument()); QCOMPARE(lst.size(), 2); QVERIFY(lst.at(0).strictlyEquals(obj)); QVERIFY(lst.at(1).strictlyEquals(plain)); QVERIFY(ret.isBoolean()); QVERIFY(!ret.toBoolean()); } plain.setProperty("foo", QScriptValue(&eng, 456)); QVERIFY(!plain.instanceOf(obj)); { QScriptValue ret = eng.evaluate("hasInstanceValue instanceof HasInstanceTester"); QVERIFY(ret.isBoolean()); QVERIFY(!ret.toBoolean()); } plain.setProperty("foo", obj.property("foo")); QVERIFY(plain.instanceOf(obj)); { QScriptValue ret = eng.evaluate("hasInstanceValue instanceof HasInstanceTester"); QVERIFY(ret.isBoolean()); QVERIFY(ret.toBoolean()); } } }
void ScriptRunner::tests() { QFile file(m_testScriptFileName); if (m_doExit) return; TestFunctionResult *tf = m_resultLogger->getTestFunctionResult("initTestCase"); if (!tf) tf = m_resultLogger->createTestFunctionResult("initTestCase"); if(file.open(QIODevice::ReadOnly)) { QString scriptContent = file.readAll(); if (scriptContent.length() <= 0) { tf->addError("Can't evaluate empty script from file: '" + m_testScriptFileName +"'"); stop(); return; } QScriptSyntaxCheckResult result = QScriptEngine::checkSyntax(scriptContent); if (result.state() != QScriptSyntaxCheckResult::Valid) { QString err = "Can't evaluate script content from file. Check syntax of script on file: '" + m_testScriptFileName +"'" + " Error: " + result.errorMessage() + " line: " + result.errorLineNumber() + " column: " + result.errorColumnNumber(); tf->addError(err); stop(); return; } if (m_doExit) return; QScriptValue val = m_engine->evaluate(scriptContent, m_testScriptFileName); if(m_engine->hasUncaughtException()) { QString err = "Can't evaluate script content from file. Check syntax of script on file: '" + m_testScriptFileName + "'" + " Error: " + m_engine->uncaughtExceptionBacktrace().join(" ") + " at line " + m_engine->uncaughtExceptionLineNumber(); tf->addError(err); stop(); return; } } else { stop(); tf->addError("Failed to read script from file '" + m_testScriptFileName +"'"); return; } if (m_doExit) return; QScriptValue ctor = m_engine->evaluate("Tests"); QScriptValue script = m_engine->newQObject(this, QScriptEngine::QtOwnership); QScriptValue scripttests = ctor.construct(QScriptValueList() << script); if(m_engine->hasUncaughtException()) { QString err = "Can't evaluate script content from file. Check syntax of script on file: '" + m_testScriptFileName +"'" + " Error: " + m_engine->uncaughtExceptionBacktrace().join(" "); tf->addError(err); stop(); return; } }