// Configuration NResponse & NTcpServerSocketCfgServices::getSharedDir(const NClientSession &, NResponse & response) { QScriptEngine se; QScriptValue svRoot = se.newObject(); NDirList sd = NConfig::instance().sharedDirectories(); int count = sd.count(); svRoot.setProperty(RSP_SUCCESS , QScriptValue(count > 0)); svRoot.setProperty(RSP_MSG, QScriptValue(count > 0 ? RSP_MSG_LOADED : RSP_MSG_NO_RESULTS)); svRoot.setProperty(RSP_COUNT, QScriptValue(count)); QScriptValue svData = se.newArray(count); svRoot.setProperty(RSP_DATA, svData); for(int i = 0; i < count; i++) { NDir dir = sd.at(i); QScriptValue svDir = se.newObject(); svData.setProperty(i, svDir); svDir.setProperty("id", i); svDir.setProperty("path", dir.path()); svDir.setProperty("recursive", dir.recursive()); svDir.setProperty("shared", dir.shared()); svDir.setProperty("exists", dir.exists()); } response.setData(NJson::serializeToQByteArray(svRoot)); return response; }
bool HttpHandlerQtScript::handleRequest(Pillow::HttpRequest *request) { if (!_scriptFunction.isFunction()) return false; QScriptEngine* engine = _scriptFunction.engine(); QScriptValue requestObject = engine->newObject(); requestObject.setProperty("nativeRequest", _scriptFunction.engine()->newQObject(request)); requestObject.setProperty("requestMethod", QUrl::fromPercentEncoding(request->requestMethod())); requestObject.setProperty("requestUri", QUrl::fromPercentEncoding(request->requestUri())); requestObject.setProperty("requestFragment", QUrl::fromPercentEncoding(request->requestFragment())); requestObject.setProperty("requestPath", QUrl::fromPercentEncoding(request->requestPath())); requestObject.setProperty("requestQueryString", QUrl::fromPercentEncoding(request->requestQueryString())); requestObject.setProperty("requestHeaders", qScriptValueFromValue(engine, request->requestHeaders())); QList<QPair<QString, QString> > queryParams = QUrl(request->requestUri()).queryItems(); QScriptValue queryParamsObject = engine->newObject(); for (int i = 0, iE = queryParams.size(); i < iE; ++i) queryParamsObject.setProperty(queryParams.at(i).first, queryParams.at(i).second); requestObject.setProperty("requestQueryParams", queryParamsObject); QScriptValue result = _scriptFunction.call(_scriptFunction, QScriptValueList() << requestObject); if (result.isError()) { if (request->state() == HttpRequest::SendingHeaders) { // Nothing was sent yet... We have a chance to let the client know we had an error. request->writeResponseString(500, HttpHeaderCollection(), objectToString(result)); } engine->clearExceptions(); return true; } return result.toBool(); }
NResponse & NTcpServerSocketCfgServices::postSharedDir(const NClientSession & session, NResponse & response) { //logDebug("NTcpServerSocketCfgServices::svcPostSharedDir", session.postData()); QScriptEngine se; se.evaluate("var data = " + QString::fromUtf8(session.content())); QScriptValue svReadData = se.globalObject().property("data").property("data"); NDir dir = NDir(svReadData.property("path").toString(), svReadData.property("recursive").toBool(), svReadData.property("shared").toBool()); int id = getConfig().addSharedDirectory(dir); QScriptValue svRoot = se.newObject(); svRoot.setProperty(RSP_SUCCESS , QScriptValue(true)); svRoot.setProperty(RSP_MSG, QScriptValue(RSP_MSG_LOADED)); // we add new user to response QScriptValue svData = se.newArray(1); svRoot.setProperty(RSP_DATA, svData); QScriptValue svDir = se.newObject(); svData.setProperty(0, svDir); svDir.setProperty("id", id); svDir.setProperty("path", dir.path()); svDir.setProperty("recursive", dir.recursive()); svDir.setProperty("shared", dir.shared()); svDir.setProperty("exists", dir.exists()); //logDebug("NJson::serialize(svRoot)", NJson::serialize(svRoot)); response.setData(NJson::serializeToQByteArray(svRoot)); return response; }
void tst_QScriptValueIterator::assignObjectToIterator() { QScriptEngine eng; QScriptValue obj1 = eng.newObject(); obj1.setProperty("foo", 123); QScriptValue obj2 = eng.newObject(); obj2.setProperty("bar", 456); QScriptValueIterator it(obj1); QVERIFY(it.hasNext()); it.next(); it = obj2; QVERIFY(it.hasNext()); it.next(); QCOMPARE(it.name(), QString::fromLatin1("bar")); it = obj1; QVERIFY(it.hasNext()); it.next(); QCOMPARE(it.name(), QString::fromLatin1("foo")); it = obj2; QVERIFY(it.hasNext()); it.next(); QCOMPARE(it.name(), QString::fromLatin1("bar")); it = obj2; QVERIFY(it.hasNext()); it.next(); QCOMPARE(it.name(), QString::fromLatin1("bar")); }
void tst_QScriptValueIterator::iterateBackAndForth() { QScriptEngine engine; { QScriptValue object = engine.newObject(); object.setProperty("foo", QScriptValue(&engine, "bar")); object.setProperty("rab", QScriptValue(&engine, "oof"), QScriptValue::SkipInEnumeration); // should not affect iterator QScriptValueIterator it(object); QVERIFY(it.hasNext()); it.next(); QCOMPARE(it.name(), QLatin1String("foo")); QVERIFY(it.hasPrevious()); it.previous(); QCOMPARE(it.name(), QLatin1String("foo")); QVERIFY(it.hasNext()); it.next(); QCOMPARE(it.name(), QLatin1String("foo")); QVERIFY(it.hasPrevious()); it.previous(); QCOMPARE(it.name(), QLatin1String("foo")); QVERIFY(it.hasNext()); it.next(); QCOMPARE(it.name(), QLatin1String("foo")); QVERIFY(it.hasNext()); it.next(); QCOMPARE(it.name(), QLatin1String("rab")); QVERIFY(it.hasPrevious()); it.previous(); QCOMPARE(it.name(), QLatin1String("rab")); QVERIFY(it.hasNext()); it.next(); QCOMPARE(it.name(), QLatin1String("rab")); QVERIFY(it.hasPrevious()); it.previous(); QCOMPARE(it.name(), QLatin1String("rab")); } { // hasNext() and hasPrevious() cache their result; verify that the result is in sync QScriptValue object = engine.newObject(); object.setProperty("foo", QScriptValue(&engine, "bar")); object.setProperty("rab", QScriptValue(&engine, "oof")); QScriptValueIterator it(object); QVERIFY(it.hasNext()); it.next(); QCOMPARE(it.name(), QString::fromLatin1("foo")); QVERIFY(it.hasNext()); it.previous(); QCOMPARE(it.name(), QString::fromLatin1("foo")); QVERIFY(!it.hasPrevious()); it.next(); QCOMPARE(it.name(), QString::fromLatin1("foo")); QVERIFY(it.hasPrevious()); it.next(); QCOMPARE(it.name(), QString::fromLatin1("rab")); } }
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_QScriptValueIterator::iterateForward() { QFETCH(QStringList, propertyNames); QFETCH(QStringList, propertyValues); QMap<QString, QString> pmap; QVERIFY(propertyNames.size() == propertyValues.size()); QScriptEngine engine; QScriptValue object = engine.newObject(); for (int i = 0; i < propertyNames.size(); ++i) { QString name = propertyNames.at(i); QString value = propertyValues.at(i); pmap.insert(name, value); object.setProperty(name, QScriptValue(&engine, value)); } QScriptValue otherObject = engine.newObject(); otherObject.setProperty("foo", QScriptValue(&engine, 123456)); otherObject.setProperty("protoProperty", QScriptValue(&engine, 654321)); object.setPrototype(otherObject); // should not affect iterator QStringList lst; QScriptValueIterator it(object); while (!pmap.isEmpty()) { QCOMPARE(it.hasNext(), true); QCOMPARE(it.hasNext(), true); it.next(); QString name = it.name(); QCOMPARE(pmap.contains(name), true); QCOMPARE(it.name(), name); QCOMPARE(it.flags(), object.propertyFlags(name)); QCOMPARE(it.value().strictlyEquals(QScriptValue(&engine, pmap.value(name))), true); QCOMPARE(it.scriptName(), engine.toStringHandle(name)); pmap.remove(name); lst.append(name); } QCOMPARE(it.hasNext(), false); QCOMPARE(it.hasNext(), false); it.toFront(); for (int i = 0; i < lst.count(); ++i) { QCOMPARE(it.hasNext(), true); it.next(); QCOMPARE(it.name(), lst.at(i)); } for (int i = 0; i < lst.count(); ++i) { QCOMPARE(it.hasPrevious(), true); it.previous(); QCOMPARE(it.name(), lst.at(lst.count()-1-i)); } QCOMPARE(it.hasPrevious(), false); }
// Check the overhead of the extension "instanceOf" void tst_QScriptClass::hasInstance() { QScriptEngine eng; ExtensionScriptClass cls(&eng); QScriptValue obj = eng.newObject(&cls); obj.setProperty("foo", 123); QScriptValue plain = eng.newObject(); plain.setProperty("foo", obj.property("foo")); QBENCHMARK { for (int i = 0; i < iterationNumber; ++i) (void)plain.instanceOf(obj); } }
void GeoHelper::searchFinishedSlot(QGeoSearchReply *reply) { if (reply->error() == QGeoSearchReply::NoError) { QScriptEngine scriptEngine; QScriptValue replyObject = scriptEngine.newArray(); QList<QGeoPlace> places = reply->places(); for (int i = 0; i < places.count(); i++) { QScriptValue placeObject = scriptEngine.newObject(); QScriptValue coordinateObject = scriptEngine.newObject(); QGeoCoordinate coordinate = places[i].coordinate(); coordinateObject.setProperty("latitude", QScriptValue(coordinate.latitude())); coordinateObject.setProperty("longitude", QScriptValue(coordinate.longitude())); placeObject.setProperty("coordinate", coordinateObject); QScriptValue addressObject = scriptEngine.newObject(); QGeoAddress address = places[i].address(); if (!address.isEmpty()) { addressObject.setProperty("country", address.country()); addressObject.setProperty("countryCode", address.countryCode()); addressObject.setProperty("state", address.state()); addressObject.setProperty("county", address.county()); addressObject.setProperty("city", address.city()); addressObject.setProperty("district", address.district()); addressObject.setProperty("street", address.street()); addressObject.setProperty("postcode", address.postcode()); } placeObject.setProperty("address", addressObject); replyObject.setProperty(i, placeObject); } QScriptValue fun = scriptEngine.evaluate("(function(a) { return JSON.stringify(a); })"); QScriptValueList args; args << replyObject; QScriptValue result = fun.call(QScriptValue(), args); emit searchReply(result.toString()); } }
void tst_QScriptContext::thisObject() { QScriptEngine eng; QScriptValue fun = eng.newFunction(get_thisObject); eng.globalObject().setProperty("get_thisObject", fun); { QScriptValue result = eng.evaluate("get_thisObject()"); QCOMPARE(result.isObject(), true); QCOMPARE(result.toString(), QString("[object global]")); } { QScriptValue result = eng.evaluate("get_thisObject.apply(new Number(123))"); QCOMPARE(result.isObject(), true); QCOMPARE(result.toNumber(), 123.0); } { QScriptValue obj = eng.newObject(); eng.currentContext()->setThisObject(obj); QVERIFY(eng.currentContext()->thisObject().equals(obj)); eng.currentContext()->setThisObject(QScriptValue()); QVERIFY(eng.currentContext()->thisObject().equals(obj)); QScriptEngine eng2; QScriptValue obj2 = eng2.newObject(); QTest::ignoreMessage(QtWarningMsg, "QScriptContext::setThisObject() failed: cannot set an object created in a different engine"); eng.currentContext()->setThisObject(obj2); } }
void tst_QScriptContext::callee() { QScriptEngine eng; { QScriptValue fun = eng.newFunction(get_callee); fun.setProperty("foo", QScriptValue(&eng, "bar")); eng.globalObject().setProperty("get_callee", fun); QScriptValue result = eng.evaluate("get_callee()"); QCOMPARE(result.isFunction(), true); QCOMPARE(result.property("foo").toString(), QString("bar")); } // callee when toPrimitive() is called internally { QScriptValue fun = eng.newFunction(store_callee_and_return_primitive); QScriptValue obj = eng.newObject(); obj.setProperty("toString", fun); QVERIFY(!obj.property("callee").isValid()); (void)obj.toString(); QVERIFY(obj.property("callee").isFunction()); QVERIFY(obj.property("callee").strictlyEquals(fun)); obj.setProperty("callee", QScriptValue()); QVERIFY(!obj.property("callee").isValid()); obj.setProperty("valueOf", fun); (void)obj.toNumber(); QVERIFY(obj.property("callee").isFunction()); QVERIFY(obj.property("callee").strictlyEquals(fun)); } }
NResponse & NTcpServerSocketCfgServices::deleteSharedDir(const NClientSession & session, NResponse & response) { logDebug("NTcpServerSocketCfgServices::svcDeleteSharedDir", session.resource()); int id = 0; QScriptEngine se; QScriptValue svRoot = se.newObject(); QString strId = session.resource(); bool ok; id = strId.toInt(&ok); if (!ok) { svRoot.setProperty(RSP_SUCCESS , QScriptValue(false)); svRoot.setProperty(RSP_MSG, QScriptValue(RSP_MSG_INVALID_INDEX)); //logDebug("NJson::serialize(svRoot)", NJson::serialize(svRoot)); response.setData(NJson::serializeToQByteArray(svRoot)); return response; } NDirList sharedDirs = getConfig().sharedDirectories(); if (id >= sharedDirs.count()) { svRoot.setProperty(RSP_SUCCESS , QScriptValue(false)); svRoot.setProperty(RSP_MSG, QScriptValue(RSP_MSG_INVALID_INDEX)); //logDebug("NJson::serialize(svRoot)", NJson::serialize(svRoot)); response.setData(NJson::serializeToQByteArray(svRoot)); return response; } getConfig().removeSharedDirectory(id); svRoot.setProperty(RSP_SUCCESS , QScriptValue(true)); svRoot.setProperty(RSP_MSG, QScriptValue(QString(RSP_MSG_N_DELETED).arg(id))); //logDebug("NJson::serialize(svRoot)", NJson::serialize(svRoot)); response.setData(NJson::serializeToQByteArray(svRoot)); return response; }
NResponse & NTcpServerSocketMusicServices::getYear(const NClientSession & session, NResponse & response) { bool ok; QString search = session.url().queryItemValue("search"); QStringList searches = search.split("+", QString::SkipEmptyParts); searches = NConvert_n::fromUTF8PercentEncoding(searches); int start = session.url().queryItemValue("start").toInt(); int limit = session.url().queryItemValue("limit").toInt(&ok); if (!ok) limit = 25; QString dir = session.url().queryItemValue("dir"); const NTcpServerAuthSession authSession = getAuthServices().getSession(session.sessionId()); logMessage(session.socket()->peerAddress().toString(), QString("%1 is looking for year: \"%2\"; start: %3; limit: %4, dir:\"%5\""). arg(authSession.login()).arg(NConvert_n::fromUTF8PercentEncoding(search)).arg(start).arg(limit).arg(dir)); int totalCount = NMDB.getYearListCount(searches); QScriptEngine se; QScriptValue svRoot = se.newObject(); QScriptValue svData = se.newArray(totalCount); svRoot.setProperty(RSP_DATA, svData); bool succeed = NMDB.getYearList(se, svData, totalCount, searches, start, limit, dir); setJsonRootReponse(svRoot, totalCount, succeed); response.setData(NJson::serializeToQByteArray(svRoot)); return response; }
QScriptValue variantListToScriptValue(QVariantList& variantList, QScriptEngine& scriptEngine) { QScriptValue scriptValue = scriptEngine.newObject(); scriptValue.setProperty("length", variantList.size()); int i = 0; foreach (QVariant v, variantList) { scriptValue.setProperty(i++, variantToScriptValue(v, scriptEngine)); }
void tst_QScriptClass::newInstance() { QScriptEngine eng; TestClass cls(&eng); QScriptValue obj1 = eng.newObject(&cls); QVERIFY(!obj1.data().isValid()); QVERIFY(obj1.prototype().strictlyEquals(cls.prototype())); QEXPECT_FAIL("", "classname is not implemented", Continue); QCOMPARE(obj1.toString(), QString::fromLatin1("[object TestClass]")); QCOMPARE(obj1.scriptClass(), (QScriptClass*)&cls); QScriptValue num(&eng, 456); QScriptValue obj2 = eng.newObject(&cls, num); QVERIFY(obj2.data().strictlyEquals(num)); QVERIFY(obj2.prototype().strictlyEquals(cls.prototype())); QCOMPARE(obj2.scriptClass(), (QScriptClass*)&cls); QScriptValue obj3 = eng.newObject(); QCOMPARE(obj3.scriptClass(), (QScriptClass*)0); obj3.setScriptClass(&cls); QCOMPARE(obj3.scriptClass(), (QScriptClass*)&cls); obj3.setScriptClass(0); QCOMPARE(obj3.scriptClass(), (QScriptClass*)0); obj3.setScriptClass(&cls); QCOMPARE(obj3.scriptClass(), (QScriptClass*)&cls); TestClass cls2(&eng); obj3.setScriptClass(&cls2); QCOMPARE(obj3.scriptClass(), (QScriptClass*)&cls2); // undefined behavior really, but shouldn't crash QScriptValue arr = eng.newArray(); QVERIFY(arr.isArray()); QCOMPARE(arr.scriptClass(), (QScriptClass*)0); QTest::ignoreMessage(QtWarningMsg, "QScriptValue::setScriptClass() failed: cannot change class of non-QScriptObject"); arr.setScriptClass(&cls); QEXPECT_FAIL("", "Changing class of arbitrary script object is not allowed (it's OK)", Continue); QCOMPARE(arr.scriptClass(), (QScriptClass*)&cls); QEXPECT_FAIL("", "Changing class of arbitrary script object is not allowed (it's OK)", Continue); QVERIFY(!arr.isArray()); QVERIFY(arr.isObject()); }
NResponse & NTcpServerSocketUIServices::nop(NResponse & response) { QScriptEngine se; QScriptValue svRoot = se.newObject(); svRoot.setProperty(RSP_SUCCESS , QScriptValue(true)); svRoot.setProperty(RSP_MSG, QScriptValue("Nop")); svRoot.setProperty("status", QScriptValue(NServer::jobToString(NSERVER.jobStatus()))); response.setData(NJson::serializeToQByteArray(svRoot)); return response; }
NResponse & NTcpServerSocketCfgServices::lookForModification(NResponse & response) { getConfig().clearDirUpdateData(); QScriptEngine se; QScriptValue svRoot = se.newObject(); svRoot.setProperty(RSP_SUCCESS , QScriptValue(true)); svRoot.setProperty(RSP_MSG, QScriptValue("Server will looking for modification")); response.setData(NJson::serializeToQByteArray(svRoot)); return response; }
// Test the time taken to get the propeties flags accross the engine void tst_QScriptClass::propertyFlags() { QScriptEngine eng; FooScriptClass cls(&eng); QScriptValue obj = eng.newObject(&cls); QScriptString foo = eng.toStringHandle("foo"); QBENCHMARK { for (int i = 0; i < iterationNumber; ++i) (void)obj.propertyFlags(foo); } }
QScriptValue variantMapToScriptValue(QVariantMap& variantMap, QScriptEngine& scriptEngine) { QScriptValue scriptValue = scriptEngine.newObject(); for (QVariantMap::const_iterator iter = variantMap.begin(); iter != variantMap.end(); ++iter) { QString key = iter.key(); QVariant qValue = iter.value(); scriptValue.setProperty(key, variantToScriptValue(qValue, scriptEngine)); } return scriptValue; }
void tst_QScriptClass::newInstance() { QScriptEngine eng; TestClass cls(&eng); QScriptValue obj1 = eng.newObject(&cls); QVERIFY(!obj1.data().isValid()); QVERIFY(obj1.prototype().strictlyEquals(cls.prototype())); QCOMPARE(obj1.toString(), QString::fromLatin1("[object TestClass]")); QCOMPARE(obj1.scriptClass(), (QScriptClass*)&cls); QScriptValue num(&eng, 456); QScriptValue obj2 = eng.newObject(&cls, num); QVERIFY(obj2.data().strictlyEquals(num)); QVERIFY(obj2.prototype().strictlyEquals(cls.prototype())); QCOMPARE(obj2.scriptClass(), (QScriptClass*)&cls); QScriptValue obj3 = eng.newObject(); QCOMPARE(obj3.scriptClass(), (QScriptClass*)0); obj3.setScriptClass(&cls); QCOMPARE(obj3.scriptClass(), (QScriptClass*)&cls); obj3.setScriptClass(0); QCOMPARE(obj3.scriptClass(), (QScriptClass*)0); obj3.setScriptClass(&cls); QCOMPARE(obj3.scriptClass(), (QScriptClass*)&cls); TestClass cls2(&eng); obj3.setScriptClass(&cls2); QCOMPARE(obj3.scriptClass(), (QScriptClass*)&cls2); // undefined behavior really, but shouldn't crash QScriptValue arr = eng.newArray(); QVERIFY(arr.isArray()); QCOMPARE(arr.scriptClass(), (QScriptClass*)0); arr.setScriptClass(&cls); QCOMPARE(arr.scriptClass(), (QScriptClass*)&cls); QVERIFY(!arr.isArray()); QVERIFY(arr.isObject()); }
//! [76] QScriptValue Person_ctor(QScriptContext *ctx, QScriptEngine *eng) { QScriptValue object; if (ctx->isCalledAsConstructor()) { object = ctx->thisObject(); } else { object = eng->newObject(); object.setPrototype(ctx->callee().property("prototype")); } object.setProperty("name", ctx->argument(0)); return object; }
// Test the overhead of checking for an inexisting property of a QScriptClass void tst_QScriptClass::noSuchProperty() { QScriptEngine eng; QScriptClass cls(&eng); QScriptValue obj = eng.newObject(&cls); QString propertyName = QString::fromLatin1("foo"); QBENCHMARK { for (int i = 0; i < iterationNumber; ++i) (void)obj.property(propertyName); } Q_ASSERT(!obj.property(propertyName).isValid()); }
//---------------------------------------------------------------------------- QString voUtils::stringify(const QString& name, vtkTable * table, const QList<vtkIdType>& columnIdsToSkip) { if (!table) { return QString(); } QScriptEngine scriptEngine; QScriptValue object = scriptEngine.newObject(); object.setProperty("name", QScriptValue(name)); object.setProperty("data", scriptValueFromTable(&scriptEngine, table, columnIdsToSkip)); return voUtils::stringify(&scriptEngine, object); }
// Test the overhead of setting a value on QScriptClass accross the Javascript engine void tst_QScriptClass::setProperty() { QScriptEngine eng; FooScriptClass cls(&eng); QScriptValue obj = eng.newObject(&cls); QScriptValue value(456); QScriptString foo = eng.toStringHandle("foo"); QBENCHMARK { for (int i = 0; i < iterationNumber; ++i) obj.setProperty(foo, value); } }
int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); QStringList paths = QStringList() << QCoreApplication::applicationDirPath() + "/../../plugins"; app.setLibraryPaths(paths); QScriptEngine *engine = new QScriptEngine(); QScriptValue global = engine->globalObject(); // add the qt object global.setProperty("qs", engine->newObject()); // add a 'script' object QScriptValue script = engine->newObject(); global.property("qs").setProperty("script", script); // add a 'system' object QScriptValue system = engine->newObject(); global.property("qs").setProperty("system", system); // add os information to qt.system.os #ifdef Q_OS_WIN32 QScriptValue osName = engine->toScriptValue(QString("windows")); #elif defined(Q_OS_LINUX) QScriptValue osName = engine->toScriptValue(QString("linux")); #elif defined(Q_OS_MAC) QScriptValue osName = engine->toScriptValue(QString("mac")); #elif defined(Q_OS_UNIX) QScriptValue osName = engine->toScriptValue(QString("unix")); #endif system.setProperty("os", osName); // add environment variables to qt.system.env QMap<QString,QVariant> envMap; QStringList envList = QProcess::systemEnvironment(); foreach (const QString &entry, envList) { QStringList keyVal = entry.split('='); if (keyVal.size() == 1) envMap.insert(keyVal.at(0), QString()); else envMap.insert(keyVal.at(0), keyVal.at(1)); }
// Check the overhead of the extension "call" void tst_QScriptClass::call() { QScriptEngine eng; ExtensionScriptClass cls(&eng); QScriptValue obj = eng.newObject(&cls); QScriptValue thisObject; QScriptValueList args; args.append(123); QBENCHMARK { for (int i = 0; i < iterationNumber; ++i) (void)obj.call(thisObject, args); } }
void tst_QScriptValueIterator::flags() { QScriptEngine engine; QScriptValue object = engine.newObject(); QScriptValue::PropertyFlags flags = flags; object.setProperty("foo", 123, QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly | QScriptValue::Undeletable); QScriptValueIterator it(object); it.next(); QBENCHMARK { for (int i = 0; i < 50000; ++i) it.flags(); } }
QScriptValue CreateValue(const QVariant& value, QScriptEngine& engine) { if(value.type() == QVariant::Map) { QScriptValue obj = engine.newObject(); QVariantMap map = value.toMap(); QVariantMap::const_iterator it = map.begin(); QVariantMap::const_iterator end = map.end(); while(it != end) { obj.setProperty( it.key(), ::CreateValue(it.value(), engine) ); ++it; } return obj; } if(value.type() == QVariant::List) { QVariantList list = value.toList(); QScriptValue array = engine.newArray(list.length()); for(int i=0; i<list.count(); i++) array.setProperty(i, ::CreateValue(list.at(i),engine)); return array; } switch(value.type()) { case QVariant::String: return QScriptValue(value.toString()); case QVariant::Int: return QScriptValue(value.toInt()); case QVariant::UInt: return QScriptValue(value.toUInt()); case QVariant::Bool: return QScriptValue(value.toBool()); case QVariant::ByteArray: return QScriptValue(QLatin1String(value.toByteArray())); case QVariant::Double: return QScriptValue((qsreal)value.toDouble()); default: break; } if(value.isNull()) return QScriptValue(QScriptValue::NullValue); return engine.newVariant(value); }
NResponse & NTcpServerSocketCfgServices::getAvailableLevelList(NResponse & response) { QScriptEngine se; QScriptValue svRoot = se.newObject(); QStringList levels = NTcpServerAuthSession::toStringLevel(AUTH_LEVEL_ADMIN, " ").split(" "); svRoot.setProperty(RSP_SUCCESS , QScriptValue(levels.count() > 0)); svRoot.setProperty(RSP_MSG, QScriptValue(levels.count() > 0 ? RSP_MSG_LOADED : RSP_MSG_NO_RESULTS)); svRoot.setProperty(RSP_COUNT, QScriptValue(levels.count())); QScriptValue svData = se.newArray(levels.count()); svRoot.setProperty(RSP_DATA, svData); for(int i = 0; i < levels.count(); i++) { QScriptValue svLevel = se.newObject(); svData.setProperty(i, svLevel); svLevel.setProperty("id", NTcpServerAuthSession::toIntLevel(levels.at(i))); svLevel.setProperty("level", levels.at(i)); } response.setData(NJson::serializeToQByteArray(svRoot)); return response; }
void tst_QScriptClass::enumerate() { QScriptEngine eng; TestClass cls(&eng); QScriptValue obj = eng.newObject(&cls); QScriptString foo = eng.toStringHandle("foo"); obj.setProperty(foo, QScriptValue(&eng, 123)); cls.setIterationEnabled(false); { QScriptValueIterator it(obj); QVERIFY(it.hasNext()); it.next(); QVERIFY(it.scriptName() == foo); QVERIFY(!it.hasNext()); } // add a custom property QScriptString foo2 = eng.toStringHandle("foo2"); const uint foo2Id = 123; const QScriptValue::PropertyFlags foo2Pflags = QScriptValue::Undeletable; QScriptValue foo2Value(&eng, 456); cls.addCustomProperty(foo2, QScriptClass::HandlesReadAccess | QScriptClass::HandlesWriteAccess, foo2Id, foo2Pflags, QScriptValue()); cls.setIterationEnabled(true); QScriptValueIterator it(obj); for (int x = 0; x < 2; ++x) { QVERIFY(it.hasNext()); it.next(); QEXPECT_FAIL("", "", Abort); QVERIFY(it.scriptName() == foo); QVERIFY(it.hasNext()); it.next(); QVERIFY(it.scriptName() == foo2); QCOMPARE(it.flags(), foo2Pflags); QVERIFY(!it.hasNext()); QVERIFY(it.hasPrevious()); it.previous(); QVERIFY(it.scriptName() == foo2); QCOMPARE(it.flags(), foo2Pflags); QVERIFY(it.hasPrevious()); it.previous(); QVERIFY(it.scriptName() == foo); QVERIFY(!it.hasPrevious()); } }