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] #if !defined(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"); #if !defined(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] }
// Perhaps shpw entire example for getting debugger up with script int main(int argv, char **args) { QApplication app(argv, args); QString fileName("helloscript.qs"); QFile scriptFile(fileName); scriptFile.open(QIODevice::ReadOnly); QTextStream stream(&scriptFile); QString contents = stream.readAll(); scriptFile.close(); QScriptEngine *engine = new QScriptEngine(); QScriptEngineDebugger *debugger = new QScriptEngineDebugger(); debugger->attachTo(engine); // Set up configuration with only stack and code QWidget *widget = new QWidget; //![0] QWidget *codeWindow = debugger->widget(QScriptEngineDebugger::CodeWidget); QWidget *stackWidget = debugger->widget(QScriptEngineDebugger::StackWidget); QLayout *layout = new QHBoxLayout; layout->addWidget(codeWindow); layout->addWidget(stackWidget); //![0] //![1] QAction *continueAction = debugger->action(QScriptEngineDebugger::ContinueAction); QAction *stepOverAction = debugger->action(QScriptEngineDebugger::StepOverAction); QAction *stepIntoAction = debugger->action(QScriptEngineDebugger::StepIntoAction); QToolBar *toolBar = new QToolBar; toolBar->addAction(continueAction); //![1] toolBar->addAction(stepOverAction); toolBar->addAction(stepIntoAction); layout->addWidget(toolBar); continueAction->setIcon(QIcon("copy.png")); debugger->setAutoShowStandardWindow(false); widget->setLayout(layout); widget->show(); QPushButton button; QScriptValue scriptButton = engine->newQObject(&button); engine->globalObject().setProperty("button", scriptButton); //![2] debugger->action(QScriptEngineDebugger::InterruptAction)->trigger(); engine->evaluate(contents, fileName); //![2] return app.exec(); }
void tst_QScriptContext::parentContextCallee_QT2270() { QScriptEngine engine; engine.globalObject().setProperty("getParentContextCallee", engine.newFunction(getParentContextCallee)); QScriptValue fun = engine.evaluate("(function() { return getParentContextCallee(); })"); QVERIFY(fun.isFunction()); QScriptValue callee = fun.call(); QVERIFY(callee.equals(fun)); }
QVariantList parseRetrievedMessages(const QByteArray &result) { std::cout << QString(result).toStdString() << std::endl; QVariantList list; QScriptEngine engine; QScriptValue response = engine.evaluate("(" + QString(result) + ")").property(RESPONSE); QScriptValueIterator it(response); while (it.hasNext()) { it.next(); // Parse message id QString messageId = it.value().property(MESSAGE_ID).toString(); // Parse message text QByteArray rawText = it.value().property(MESSAGE_TEXT).toVariant().toByteArray(); QString messageText = QString::fromUtf8(rawText, rawText.size()); // Parse message date QString messageDate = QDateTime::fromTime_t(it.value().property(MESSAGE_DATE).toUInt32()).toString(DATE_TIME_FORMAT); // Parse likes, comments and reposts int likes = it.value().property(MESSAGE_LIKES).property(COUNT).toInt32(); int comments = it.value().property(MESSAGE_COMMENTS).property(COUNT).toInt32(); int reposts = it.value().property(MESSAGE_REPOSTS).property(COUNT).toInt32(); // Online status bool online = it.value().property(IS_ONLINE).toNumber() == ONLINE; if (!messageId.isEmpty() && !messageText.isEmpty() && !messageDate.isEmpty()) { QVariantMap message; message.insert(MESSAGE_ID, messageId); message.insert(MESSAGE_TEXT, messageText); message.insert(MESSAGE_DATE,messageDate); if (likes > 0) message.insert(MESSAGE_LIKES, likes); if (comments > 0) message.insert(MESSAGE_COMMENTS, comments); if (reposts > 0) message.insert(MESSAGE_REPOSTS, reposts); if (online) message.insert(IS_ONLINE, ONLINE); list.append(message); } } return list; }
QString Json::encode(const QMap<QString,QVariant> &map) { QScriptEngine engine; engine.evaluate("function toString() { return JSON.stringify(this) }"); QScriptValue toString = engine.globalObject().property("toString"); QScriptValue obj = encodeInner(map, &engine); return toString.call(obj).toString(); }
void tst_QScriptContext::popNativeContextScope() { QScriptEngine eng; QScriptContext *ctx = eng.pushContext(); QVERIFY(ctx->popScope().isObject()); // the activation object QCOMPARE(ctx->scopeChain().size(), 1); QVERIFY(ctx->scopeChain().at(0).strictlyEquals(eng.globalObject())); // This was different in 4.5: scope and activation were decoupled QVERIFY(ctx->activationObject().strictlyEquals(eng.globalObject())); QVERIFY(!eng.evaluate("var foo = 123; function bar() {}").isError()); QVERIFY(eng.globalObject().property("foo").isNumber()); QVERIFY(eng.globalObject().property("bar").isFunction()); QScriptValue customScope = eng.newObject(); ctx->pushScope(customScope); QCOMPARE(ctx->scopeChain().size(), 2); QVERIFY(ctx->scopeChain().at(0).strictlyEquals(customScope)); QVERIFY(ctx->scopeChain().at(1).strictlyEquals(eng.globalObject())); QVERIFY(ctx->activationObject().strictlyEquals(eng.globalObject())); ctx->setActivationObject(customScope); QVERIFY(ctx->activationObject().strictlyEquals(customScope)); QCOMPARE(ctx->scopeChain().size(), 2); QVERIFY(ctx->scopeChain().at(0).strictlyEquals(customScope)); QEXPECT_FAIL("", "QTBUG-11012", Continue); QVERIFY(ctx->scopeChain().at(1).strictlyEquals(eng.globalObject())); QVERIFY(!eng.evaluate("baz = 456; var foo = 789; function barbar() {}").isError()); QEXPECT_FAIL("", "QTBUG-11012", Continue); QVERIFY(eng.globalObject().property("baz").isNumber()); QVERIFY(customScope.property("foo").isNumber()); QVERIFY(customScope.property("barbar").isFunction()); QVERIFY(ctx->popScope().strictlyEquals(customScope)); QCOMPARE(ctx->scopeChain().size(), 1); QEXPECT_FAIL("", "QTBUG-11012", Continue); QVERIFY(ctx->scopeChain().at(0).strictlyEquals(eng.globalObject())); // Need to push another object, otherwise we crash in popContext() (QTBUG-11012) ctx->pushScope(customScope); eng.popContext(); }
void MainWindow::on_pushButton_2_clicked() { QString CodeFunction="2+2*2"; QScriptEngine engine; double Result = engine.evaluate(CodeFunction).toNumber(); ui->textEdit->insertPlainText(QString::number(Result)+"\n"); }
void tst_QScriptContext::jsActivationObject() { QScriptEngine eng; eng.globalObject().setProperty("get_jsActivationObject", eng.newFunction(get_jsActivationObject)); eng.evaluate("function f1() { var w = get_jsActivationObject('arg1'); return w; }"); eng.evaluate("function f2(x,y,z) { var v1 = 42;\n" // "function foo() {};\n" //this would avoid JSC to optimize "var v2 = f1(); return v2; }"); eng.evaluate("function f3() { var v1 = 'nothing'; return f2(1,2,3); }"); QScriptValue result1 = eng.evaluate("f2('hello', 'useless', 'world')"); QScriptValue result2 = eng.evaluate("f3()"); QVERIFY(result1.isObject()); QEXPECT_FAIL("", "JSC optimize away the activation object", Abort); QCOMPARE(result1.property("v1").toInt32() , 42); QCOMPARE(result1.property("arguments").property(1).toString() , QString::fromLatin1("useless")); QVERIFY(result2.isObject()); QCOMPARE(result2.property("v1").toInt32() , 42); QCOMPARE(result2.property("arguments").property(1).toString() , QString::fromLatin1("2")); }
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; } }
void tst_QScriptClass::getProperty_invalidValue() { QScriptEngine eng; TestClass cls(&eng); cls.addCustomProperty(eng.toStringHandle("foo"), QScriptClass::HandlesReadAccess, /*id=*/0, QScriptValue::ReadOnly, QScriptValue()); QScriptValue obj = eng.newObject(&cls); QVERIFY(obj.property("foo").isUndefined()); eng.globalObject().setProperty("obj", obj); QVERIFY(eng.evaluate("obj.hasOwnProperty('foo'))").toBool()); // The JS environment expects that a valid value is returned, // otherwise we could crash. QVERIFY(eng.evaluate("obj.foo").isUndefined()); QVERIFY(eng.evaluate("obj.foo + ''").isString()); QVERIFY(eng.evaluate("Object.getOwnPropertyDescriptor(obj, 'foo').value").isUndefined()); QVERIFY(eng.evaluate("Object.getOwnPropertyDescriptor(obj, 'foo').value +''").isString()); }
void tst_QScriptContext::toString() { QScriptEngine eng; eng.globalObject().setProperty("parentContextToString", eng.newFunction(parentContextToString)); QScriptValue ret = eng.evaluate("function foo(first, second, third) {\n" " return parentContextToString();\n" "}; foo(1, 2, 3)", "script.qs"); QVERIFY(ret.isString()); QCOMPARE(ret.toString(), QString::fromLatin1("foo(first = 1, second = 2, third = 3) at script.qs:2")); }
void StravaUploader::requestVerifyUploadFinished(QNetworkReply *reply) { uploadSuccessful = false; if (reply->error() != QNetworkReply::NoError) qDebug() << "Error from upload " <<reply->error(); else { QString response = reply->readLine(); //qDebug() << response; QScriptValue sc; QScriptEngine se; sc = se.evaluate("("+response+")"); uploadProgress = sc.property("upload_progress").toString(); //qDebug() << "upload_progress: " << uploadProgress; parent->progressBar->setValue(uploadProgress.toInt()); stravaActivityId = sc.property("activity_id").toString(); if (stravaActivityId.length() == 0) { requestVerifyUpload(); return; } ride->ride()->setTag("Strava activityId", stravaActivityId); ride->setDirty(true); sc = se.evaluate("("+response+")"); uploadStatus = sc.property("upload_status").toString(); //qDebug() << "upload_status: " << uploadStatus; parent->progressLabel->setText(uploadStatus); if (uploadProgress.toInt() < 97) { requestVerifyUpload(); return; } uploadSuccessful = true; } }
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); }
void tst_QScriptContext::scopeChain() { QScriptEngine eng; { QScriptValueList ret = eng.currentContext()->scopeChain(); QCOMPARE(ret.size(), 1); QVERIFY(ret.at(0).strictlyEquals(eng.globalObject())); } { eng.globalObject().setProperty("getScopeChain", eng.newFunction(getScopeChain)); QScriptValueList ret = qscriptvalue_cast<QScriptValueList>(eng.evaluate("getScopeChain()")); QCOMPARE(ret.size(), 1); QVERIFY(ret.at(0).strictlyEquals(eng.globalObject())); } { eng.evaluate("function foo() { function bar() { return getScopeChain(); } return bar() }"); QScriptValueList ret = qscriptvalue_cast<QScriptValueList>(eng.evaluate("foo()")); QEXPECT_FAIL("", "Number of items in returned scope chain is incorrect", Abort); QCOMPARE(ret.size(), 3); QVERIFY(ret.at(2).strictlyEquals(eng.globalObject())); QCOMPARE(ret.at(1).toString(), QString::fromLatin1("activation")); QVERIFY(ret.at(1).property("arguments").isObject()); QCOMPARE(ret.at(0).toString(), QString::fromLatin1("activation")); QVERIFY(ret.at(0).property("arguments").isObject()); } { QScriptValueList ret = qscriptvalue_cast<QScriptValueList>(eng.evaluate("o = { x: 123 }; with(o) getScopeChain();")); QCOMPARE(ret.size(), 2); QVERIFY(ret.at(1).strictlyEquals(eng.globalObject())); QVERIFY(ret.at(0).isObject()); QCOMPARE(ret.at(0).property("x").toInt32(), 123); } { QScriptValueList ret = qscriptvalue_cast<QScriptValueList>( eng.evaluate("o1 = { x: 123}; o2 = { y: 456 }; with(o1) { with(o2) { getScopeChain(); } }")); QCOMPARE(ret.size(), 3); QVERIFY(ret.at(2).strictlyEquals(eng.globalObject())); QVERIFY(ret.at(1).isObject()); QCOMPARE(ret.at(1).property("x").toInt32(), 123); QVERIFY(ret.at(0).isObject()); QCOMPARE(ret.at(0).property("y").toInt32(), 456); } }
void AddWindow::replyFinished(QNetworkReply *reply) { QVariant statusCodev = reply->readAll(); str = statusCodev.toString(); QScriptValue sc; QScriptEngine engine; sc=engine.evaluate("value="+str); QScriptValueIterator it(sc); it.next(); QString Id=it.value().toString(); if(Id=="Parse error") { ui->textBrowser->clear(); ui->label_2->hide(); ui->faceButton->hide(); ui->label_4->hide(); ui->pushButton_2->hide(); QString c="不存在该用户,请重新输入"; ui->textBrowser->setText(c); } else{ ui->textBrowser->clear(); it.next(); it.next(); QString nickname=it.value().toString(); ui->label_2->setText(nickname); it.next(); //头像处理 QByteArray head,face; QString str(it.value().toString()); int j = str.indexOf('-'); while(j!=-1){ str[j] = '+'; j = str.indexOf('-'); } head = QByteArray::fromBase64(str.toLatin1()); face = qUncompress(head); QImage img; img.loadFromData(face); ui->faceButton->setIcon(QPixmap::fromImage(img)); it.next(); QString signature=it.value().toString(); ui->label_4->setText(signature); ui->label_2->show(); ui->faceButton->show(); ui->label_4->show(); ui->pushButton_2->show(); } /*while (it.hasNext()){ it.next(); qDebug()<<it.name()<<":"<<it.value().toString(); }*/ }
void QDeclarativeExpressionPrivate::init(QDeclarativeContextData *ctxt, void *expr, QDeclarativeRefCount *rc, QObject *me, const QString &srcUrl, int lineNumber) { url = srcUrl; line = lineNumber; if (dataRef) dataRef->release(); dataRef = rc; if (dataRef) dataRef->addref(); quint32 *exprData = (quint32 *)expr; QDeclarativeCompiledData *dd = (QDeclarativeCompiledData *)rc; expression = QString::fromRawData((QChar *)(exprData + 2), exprData[1]); int progIdx = *(exprData); bool isSharedProgram = progIdx & 0x80000000; progIdx &= 0x7FFFFFFF; QDeclarativeEngine *engine = ctxt->engine; QDeclarativeEnginePrivate *ep = QDeclarativeEnginePrivate::get(engine); QScriptEngine *scriptEngine = QDeclarativeEnginePrivate::getScriptEngine(engine); if (isSharedProgram) { if (!dd->cachedClosures.at(progIdx)) { QScriptContext *scriptContext = QScriptDeclarativeClass::pushCleanContext(scriptEngine); scriptContext->pushScope(ep->contextClass->newSharedContext()); scriptContext->pushScope(ep->globalClass->staticGlobalObject()); dd->cachedClosures[progIdx] = new QScriptValue(scriptEngine->evaluate(expression, url, line)); scriptEngine->popContext(); } expressionFunction = *dd->cachedClosures.at(progIdx); expressionFunctionMode = SharedContext; expressionFunctionValid = true; } else { if (!dd->cachedPrograms.at(progIdx)) { dd->cachedPrograms[progIdx] = new QScriptProgram(expression, url, line); } expressionFunction = evalInObjectScope(ctxt, me, *dd->cachedPrograms.at(progIdx), &expressionContext); expressionFunctionMode = ExplicitContext; expressionFunctionValid = true; } QDeclarativeAbstractExpression::setContext(ctxt); scopeObject = me; }
void CJavaScript_Protocol::slot_TagChange(CPointI *pPoint_, QVariant /*VarSet_*/) { CJavaScript_DataChange_Point *pPoint = (CJavaScript_DataChange_Point *)pPoint_; qDebug()<<"222222222222222"<<__func__<<__LINE__<<pPoint->m_strLink; for (int nJavaScriptCount = 0; nJavaScriptCount < pPoint->m_JavaScriptList.count(); ++nJavaScriptCount) { JavaScript *pJavaScript = pPoint->m_JavaScriptList.at(nJavaScriptCount); qDebug()<<__func__<<__LINE__<<pPoint->m_strLink<<pJavaScript->m_strScript; QScriptEngine engine; QMap<QString,PointStruct*>::iterator iterator; for (iterator = pJavaScript->m_PointStructMap.begin(); iterator != pJavaScript->m_PointStructMap.end(); ++iterator) { QString strName = iterator.value()->m_strName; qDebug()<<__func__<<__LINE__<<pPoint->m_strLink<<pJavaScript->m_strScript<<strName; CTagI *pTag = iterator.value()->m_pPoint->m_pTag; if (pTag) { iterator.value()->m_pPoint->m_SrcValue = pTag->GetProjectValue()->GetVarValue(); engine.globalObject().setProperty(strName,pTag->GetProjectValue()->GetVarValue().toFloat()); qDebug()<<__func__<<__LINE__<<pPoint->m_strLink<<pJavaScript->m_strScript<<strName<<pTag->GetProjectValue()->GetVarValue().toFloat(); }else { qDebug()<<__func__<<__LINE__<<pPoint->m_strLink<<pJavaScript->m_strScript<<strName<<"return;"; // return; } } engine.evaluate(pJavaScript->m_strScript); for (iterator = pJavaScript->m_PointStructMap.begin(); iterator != pJavaScript->m_PointStructMap.end(); ++iterator) { QString strName = iterator.value()->m_strName; qDebug()<<__func__<<__LINE__<<pPoint->m_strLink<<pJavaScript->m_strScript<<strName; CTagI *pTag = iterator.value()->m_pPoint->m_pTag; if (pTag) { qDebug()<<__func__<<__LINE__<<pTag->GetName(); QVariant value = engine.globalObject().property(strName).toVariant(); if (value != iterator.value()->m_pPoint->m_SrcValue) { engine.globalObject().setProperty(strName,pTag->GetProjectValue()->GetVarValue().toFloat()); pTag->SetValue(iterator.value()->m_pPoint,value,value); qDebug()<<__func__<<__LINE__<<pTag->GetName()<<"setvalue1"<<value; }else { qDebug()<<__func__<<__LINE__<<pTag->GetName()<<"setvalue2"<<value; } }else { // return; } } } }
void RGhostUploader::handshakeFinished() { QScriptEngine engine; json = engine.evaluate( "(" + reply->readAll() + ")" ); cookie = reply->rawHeader("Set-Cookie"); /*qDebug() << "RGhost uploader::" << "got json" << "\nheaders:" << reply->rawHeaderList() << "\ncookie:" << reply->rawHeader("Set-Cookie") << "\n response:" << reply->readAll();*/ doUpload(); }
QString CodeEditor::beautifyJavaScriptCode( const QString &source ){ QScriptEngine engine; QScriptValue options = engine.newObject(); options.setProperty("preserve_newlines", true); options.setProperty("space_after_anon_function", true); options.setProperty("braces_on_own_line", false); options.setProperty("keep_array_indentation", true); if (source.isEmpty()) { return source; } QString fileName = qApp->applicationDirPath()+"/beautify.js"; QFile file(fileName); if(!file.exists()){ QMessageBox::critical(0,"","Could not find 'beautify.js' in application directory! Cannot beautify code."); return source; } if(!file.open(QFile::ReadOnly)) { return source; } QString script = file.readAll(); file.close(); if (script.isEmpty()) { return source; } engine.evaluate(script); engine.globalObject().setProperty("source", QScriptValue(source)); engine.globalObject().setProperty("options", options); QScriptValue result = engine.evaluate("js_beautify(source, options);"); return result.toString(); }
int main(int argc, char *argv[]) { //! [0] QScriptEngine engine; QObject *someObject = new MyObject; QScriptValue objectValue = engine.newQObject(someObject); engine.globalObject().setProperty("myObject", objectValue); //! [0] qDebug() << "myObject's calculate() function returns" << engine.evaluate("myObject.calculate(10)").toNumber(); return 0; }
bool videoDeleted(const QByteArray &result) { if (result.isEmpty()) { return false; } QScriptEngine engine; int vid = engine.evaluate("(" + QString(result) + ")").property(RESPONSE).toInteger(); return vid == 1; }
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 Parser::suggestionsReply(QNetworkReply *reply) { QString content; QTextCodec * codec = QTextCodec::codecForName("windows-1251"); content = codec->toUnicode(reply->readAll()); // Parsing AddHash(need for adding songs to your library) QString addHash; QRegExp rx("onclick=\"Audio\\.addShareAudio\\(this, [\\d]+, [\\d]+, '(.*)', 0\\)\\;\""); rx.setMinimal(true); rx.indexIn(content); addHash = rx.capturedTexts()[1]; QString data; //QRegExp rx("\\{\"all\":(.*)\\}<!>"); rx.setPattern("\\{\"all\":(.*)\\}<!>"); rx.indexIn(content); data = rx.capturedTexts()[1]; if(data != "") { QScriptEngine engine; QScriptValue values; values = engine.evaluate(data); QScriptValue item; int i = 0; while(values.property(i).toString() != "") { item = values.property(i); Track *track = new Track(this); track->setArtist(trimXlam(item.property(5).toString())); track->setTitle(trimXlam(item.property(6).toString())); track->setDuration(item.property(4).toString()); track->setUrl(item.property(2).toString()); track->setAid(item.property(1).toString()); track->setOid(item.property(0).toString()); track->setHash(addHash); Q_EMIT newTrack(track); i++; } } if(m_iOffset > 0) loadMoreResults(); else Q_EMIT free(); }
bool musicAdded(const QByteArray &result) { if (result.isEmpty()) { return false; } QScriptEngine engine; int aid = engine.evaluate("(" + QString(result) + ")").property(RESPONSE).toInteger(); return aid > 0; }
//! [0] int main(int argc, char *argv[]) { Q_INIT_RESOURCE(helloscript); //! [0] //! [1] QApplication app(argc, argv); QScriptEngine engine; QTranslator translator; translator.load("helloscript_la"); app.installTranslator(&translator); engine.installTranslatorFunctions(); //! [1] //! [2] QPushButton button; QScriptValue scriptButton = engine.newQObject(&button); engine.globalObject().setProperty("button", scriptButton); //! [2] //! [3] QString fileName(":/helloscript.js"); QFile scriptFile(fileName); scriptFile.open(QIODevice::ReadOnly); QTextStream stream(&scriptFile); QString contents = stream.readAll(); scriptFile.close(); //! [3] #ifdef Q_OS_SYMBIAN contents.replace("button.show()", "button.showMaximized()"); #endif //! [4] QScriptValue result = engine.evaluate(contents, fileName); //! [4] //! [5] if (result.isError()) { QMessageBox::critical(0, "Hello Script", QString::fromLatin1("%0:%1: %2") .arg(fileName) .arg(result.property("lineNumber").toInt32()) .arg(result.toString())); return -1; } //! [5] //! [6] return app.exec(); }
void SpotifyIO::onTextMessageReceived(const QString &message) { QVariantMap json = QJsonDocument::fromJson(message.toUtf8()).toVariant().toMap(); if (json.contains("message")) { qDebug() << message; QStringList args = json["message"].toStringList(); if (args[0] == "do_work") { QScriptEngine engine; QScriptValue replyFunction = engine.newFunction(reply); engine.globalObject().setProperty("reply", replyFunction); QScriptValue value = engine.evaluate(args[1]); sendCommand("sp/work_done", QVariantList() << value.toString()); } else if (args[0] == "ping_flash2") { QString ping = args[1]; //QString pong = _constructPong(ping); //sendCommand("sp/pong_flash2", QVariantList() << pong); ping = ping.split(" ").join("-"); QUrl url; url.setScheme("http"); url.setHost("ping-pong.spotify.nodestuff.net"); url.setPath("/" + ping); QNetworkRequest req(url); req.setHeader(QNetworkRequest::UserAgentHeader, userAgent); QObject::connect(nam->get(req), SIGNAL(finished()), this, SLOT(onPongReply())); } else if (args[0] == "login_complete") { sendCommand("sp/log", QVariantList() << 41 << 1 << 0 << 0 << 0 << 0); sendCommand("sp/user_info", QVariantList(), this, COMMANDCALLBACK(onUserInfo)); getPlaylists(username, this, COMMANDCALLBACK(onMyPlaylists)); _state = LoggedInState; Q_EMIT stateChanged(); heartbeat->start(); } else { qWarning() << args[0] << "NOT IMPLEMENTED!"; } } else if (json.contains("id")) { int id = json["id"].toInt(); if (callbacks.contains(id)) { //qDebug() << "have callback for" << id << callbacks[id]; QMetaObject::invokeMethod(receivers.take(id), callbacks.take(id), Q_ARG(QVariant, json["result"])); } else { qDebug() << message; } } }
QString WebShopScript::getIdUrl(QString id) { QScriptEngine e; e.globalObject().setProperty("dtBomLocale", QLocale::system().name()); e.globalObject().setProperty("dtBomId", id); e.evaluate(searchIdScript); QString ret = e.globalObject().property("ret").toString(); qDebug() << "WebShopScript::getIdUrl:" << ret; return ret; }
QVariant BrainStimInterface::invokeScriptEngine(const QString &sScriptCode) { if (parentQMLViewerObject) { QScriptEngine *tmpScriptEngine = parentQMLViewerObject->getScriptEngine(); if (tmpScriptEngine) { QScriptValue tmpValue = tmpScriptEngine->evaluate(sScriptCode); return tmpValue.toVariant(); } } return QVariant::Invalid; }
void RemoteJob::parseJSON(){ qDebug() << "RemoteJob::parseJSON"; QScriptValue sc; QScriptEngine engine; sc = engine.evaluate("(" + QString(m_strResponseData) + ")"); // In new versions it may need to look like engine.evaluate(); if (sc.property("return_msg").toString().compare("OK") != 0){ qDebug() << "return msg is not ok"; emit error(); return; } emit finishedAddingJob(); }
void PlugScript::slNewPiece(InterfaceTetris tpD) { ifTetris=&tpD; // QByteArray tpCur( tpD.aBoard); iWaiting=0; QScriptEngine scrptEngine; QFile file("d:\\ETK\\Projects\\qt\\tetrisqt\\tetris.js"); if (!file.open(QFile::ReadOnly)) { QMessageBox::critical(0, QString("File open error"), "Can not open the script file:"+file.fileName() , QMessageBox::Yes ); } QLabel lb; QScriptValue objTetris=scrptEngine.newQObject(&lb); scrptEngine.globalObject().setProperty("objTetris", objTetris); //objTetris.setProperty("mBoard",tpCur); //scrptEngine.globalObject().setProperty("iTetris",interfaceTetris); //QScriptValue val=scrptEngine.evaluate(""); QString str=QLatin1String(file.readAll()); scrptEngine.globalObject().setProperty("foo", 123); QScriptValue result = scrptEngine.evaluate(str); // Q_ASSERT(result); if (result.isError()) { QMessageBox::critical(0, "Evaluating error", result.toString(), QMessageBox::Yes ); } iLines++; emit sgDbg(result.toInteger()); }