Ejemplo n.º 1
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());
	// Special functions
	engine->globalObject().setProperty("setTimer", engine->newFunction(js_setTimer));
	engine->globalObject().setProperty("queue", engine->newFunction(js_queue));
	engine->globalObject().setProperty("removeTimer", engine->newFunction(js_removeTimer));
	engine->globalObject().setProperty("include", engine->newFunction(js_include));
	engine->globalObject().setProperty("bind", engine->newFunction(js_bind));

	// Special global variables
	//== \item[version] Current version of the game, set in \emph{major.minor} format.
	engine->globalObject().setProperty("version", "3.2", QScriptValue::ReadOnly | QScriptValue::Undeletable);
	//== \item[selectedPlayer] The player ontrolled by the client on which the script runs.
	engine->globalObject().setProperty("selectedPlayer", selectedPlayer, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	//== \item[gameTime] The current game time. Updated before every invokation of a script.
	engine->globalObject().setProperty("gameTime", gameTime, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	//== \item[difficulty] The currently set campaign difficulty, or the current AI's difficulty setting. It will be one of
	//== EASY, MEDIUM, HARD or INSANE.
	engine->globalObject().setProperty("difficulty", difficulty, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	//== \item[mapName] The name of the current map.
	engine->globalObject().setProperty("mapName", game.map, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	//== \item[baseType] The type of base that the game starts with. It will be one of CAMP_CLEAN, CAMP_BASE or CAMP_WALLS.
	engine->globalObject().setProperty("baseType", game.base, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	//== \item[alliancesType] The type of alliances permitted in this game. It will be one of NO_ALLIANCES, ALLIANCES or ALLIANCES_TEAMS.
	engine->globalObject().setProperty("alliancesType", game.alliance, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	//== \item[powerType] The power level set for this game.
	engine->globalObject().setProperty("powerType", game.power, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	//== \item[maxPlayers] The number of active players in this game.
	engine->globalObject().setProperty("maxPlayers", game.maxPlayers, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	//== \item[scavengers] Whether or not scavengers are activated in this game.
	engine->globalObject().setProperty("scavengers", game.scavengers, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	//== \item[mapWidth] Width of map in tiles.
	engine->globalObject().setProperty("mapWidth", mapWidth, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	//== \item[mapHeight] Height of map in tiles.
	engine->globalObject().setProperty("mapHeight", mapHeight, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	//== \item[scavengerPlayer] Index of scavenger player. (3.2+ only)
	engine->globalObject().setProperty("scavengerPlayer", scavengerPlayer(), QScriptValue::ReadOnly | QScriptValue::Undeletable);

	// Regular functions
	registerFunctions(engine);

	// Remember internal, reserved names
	QScriptValueIterator it(engine->globalObject());
	while (it.hasNext())
	{
		it.next();
		internalNamespace.insert(it.name(), 1);
	}
	// We need to always save the 'me' special variable.
	//== \item[me] The player the script is currently running as.
	engine->globalObject().setProperty("me", player, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	QScriptValue result = engine->evaluate(source, path);
	ASSERT_OR_RETURN(false, !engine->hasUncaughtException(), "Uncaught exception at line %d, file %s: %s", 
	                 engine->uncaughtExceptionLineNumber(), path.toAscii().constData(), result.toString().toAscii().constData());

	// Register script
	scripts.push_back(engine);

	debug(LOG_SAVE, "Created script engine %d for player %d from %s", scripts.size() - 1, player, path.toUtf8().constData());
	return true;
}
Ejemplo n.º 2
1
QScriptEngine * ScriptEngineWorker::createScriptEngine(bool supportThreads)
{
	QScriptEngine *engine = new QScriptEngine();
	QLOG_INFO() << "New script engine" << engine << ", thread:" << QThread::currentThread();

	Scriptable<BatteryInterface>::registerMetatype(engine);
	Scriptable<ColorSensorInterface>::registerMetatype(engine);
	Scriptable<DisplayInterface>::registerMetatype(engine);
	Scriptable<EncoderInterface>::registerMetatype(engine);
	Scriptable<EventCodeInterface>::registerMetatype(engine);
	Scriptable<EventDeviceInterface>::registerMetatype(engine);
	Scriptable<EventInterface>::registerMetatype(engine);
	Scriptable<GamepadInterface>::registerMetatype(engine);
	Scriptable<FifoInterface>::registerMetatype(engine);
	Scriptable<KeysInterface>::registerMetatype(engine);
	Scriptable<LedInterface>::registerMetatype(engine);
	Scriptable<LineSensorInterface>::registerMetatype(engine);
	Scriptable<MailboxInterface>::registerMetatype(engine);
	Scriptable<MotorInterface>::registerMetatype(engine);
	Scriptable<ObjectSensorInterface>::registerMetatype(engine);
	Scriptable<SensorInterface>::registerMetatype(engine);
	Scriptable<SoundSensorInterface>::registerMetatype(engine);
	Scriptable<QTimer>::registerMetatype(engine);
	qScriptRegisterMetaType(engine, timeValToScriptValue, timeValFromScriptValue);
	Scriptable<VectorSensorInterface>::registerMetatype(engine);

	qScriptRegisterSequenceMetaType<QVector<int>>(engine);
	qScriptRegisterSequenceMetaType<QStringList>(engine);

	engine->globalObject().setProperty("brick", engine->newQObject(&mBrick));
	engine->globalObject().setProperty("script", engine->newQObject(&mScriptControl));

	if (mMailbox) {
		engine->globalObject().setProperty("mailbox", engine->newQObject(mMailbox));
	}

	// Gamepad can still be accessed from script as brick.gamepad(), 'gamepad' variable is here for backwards
	// compatibility.
	if (mBrick.gamepad()) {
		engine->globalObject().setProperty("gamepad", engine->newQObject(mBrick.gamepad()));
	}

	if (supportThreads) {
		engine->globalObject().setProperty("Threading", engine->newQObject(&mThreading));
	}

	evalSystemJs(engine);

	engine->setProcessEventsInterval(1);
	return engine;
}
Ejemplo n.º 3
0
/**
 * Handles the loading of trashed notes
 *
 * @brief OwnCloudService::handleTrashedLoading
 * @param data
 */
void OwnCloudService::handleTrashedLoading(QString data) {
    // check if we get any data at all
    if (data == "") {
        if (QMessageBox::critical(
                0, "ownCloud server connection error!",
                "Cannot connect to the ownCloud server!<br />"
                        "Please check your configuration in the settings!",
                "Open &settings", "&Cancel", QString::null, 0, 1) == 0) {
            mainWindow->openSettingsDialog();
        }

        return;
    }

    // we have to add [], so the string can be parsed as JSON
    data = QString("[") + data + QString("]");

    QScriptEngine engine;
    QScriptValue result = engine.evaluate(data);

    // get a possible error messages
    QString message = result.property(0).property("message").toString();

    // check if we got an error message
    if (message != "") {
        if (QMessageBox::critical(
                0, "ownCloud server connection error!",
                "ownCloud server error: <strong>" + message + "</strong><br />"
                        "Please check your configuration in the settings!",
                "Open &settings", "&Cancel", QString::null, 0, 1) == 0) {
            mainWindow->openSettingsDialog();
        }

        return;
    }

    // get the directory to check if everything is all right
    QString directory = result.property(0).property("directory").toString();

    // check if we got no usefull data
    if (directory == "") {
        if (QMessageBox::critical(
                0, "ownCloud server connection error!",
                "QOwnNotes was unable to connect to your ownCloud server! "
                        "Please check the configuration in the settings!",
                "Open &settings", "&Cancel", QString::null, 0, 1) == 0) {
            mainWindow->openSettingsDialog();
        }

        return;
    }

    // get the versions
    QScriptValue notes = result.property(0).property("notes");

    // check if we got no usefull data
    if (notes.toString() == "") {
        QMessageBox::information(0, "no other version",
                                 "There are no trashed notes on the server.");
        return;
    }

    TrashDialog *dialog = new TrashDialog(notes, mainWindow);
    dialog->exec();
}
Ejemplo n.º 4
0
void tst_QScriptClass::getAndSetProperty()
{
    QScriptEngine eng;

    TestClass cls(&eng);

    QScriptValue obj1 = eng.newObject(&cls);
    QScriptValue obj2 = eng.newObject(&cls);
    QScriptString foo = eng.toStringHandle("foo");
    QScriptString bar = eng.toStringHandle("bar");

    // should behave just like normal
    for (int x = 0; x < 2; ++x) {
        QScriptValue &o = (x == 0) ? obj1 : obj2;
        for (int y = 0; y < 2; ++y) {
            QScriptString &s = (y == 0) ? foo : bar;

            // read property
            cls.clearReceivedArgs();
            QScriptValue ret = o.property(s);
            QVERIFY(!ret.isValid());
            QVERIFY(cls.lastQueryPropertyObject().strictlyEquals(o));
            QVERIFY(cls.lastQueryPropertyName() == s);
            QVERIFY(!cls.lastPropertyObject().isValid());
            QVERIFY(!cls.lastSetPropertyObject().isValid());
            QVERIFY(cls.lastQueryPropertyFlags() == QScriptClass::HandlesReadAccess);

            // write property
            cls.clearReceivedArgs();
            QScriptValue num(&eng, 123);
            o.setProperty(s, num);
            QVERIFY(cls.lastQueryPropertyObject().strictlyEquals(o));
            QVERIFY(cls.lastQueryPropertyName() == s);
            QVERIFY(!cls.lastPropertyObject().isValid());
            QVERIFY(!cls.lastSetPropertyObject().isValid());
            // ### ideally, we should only test for HandlesWriteAccess in this case
            QVERIFY(cls.lastQueryPropertyFlags() == (QScriptClass::HandlesReadAccess | QScriptClass::HandlesWriteAccess));

            // re-read property
            cls.clearReceivedArgs();
            QVERIFY(o.property(s).strictlyEquals(num));
            QVERIFY(!cls.lastQueryPropertyObject().isValid());
        }
    }

    // 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, foo2Value);

    {
        // read property
        cls.clearReceivedArgs();
        {
            QScriptValue ret = obj1.property(foo2);
            QVERIFY(ret.strictlyEquals(foo2Value));
        }
        QVERIFY(cls.lastQueryPropertyObject().strictlyEquals(obj1));
        QVERIFY(cls.lastQueryPropertyName() == foo2);
        QVERIFY(cls.lastPropertyObject().strictlyEquals(obj1));
        QVERIFY(cls.lastPropertyName() == foo2);
        QCOMPARE(cls.lastPropertyId(), foo2Id);

        // read flags
        cls.clearReceivedArgs();
        QCOMPARE(obj1.propertyFlags(foo2), foo2Pflags);
        QVERIFY(cls.lastQueryPropertyObject().strictlyEquals(obj1));
        QVERIFY(cls.lastQueryPropertyName() == foo2);
        QVERIFY(!cls.lastPropertyObject().isValid());
        QVERIFY(cls.lastPropertyFlagsObject().strictlyEquals(obj1));
        QVERIFY(cls.lastPropertyFlagsName() == foo2);
        QCOMPARE(cls.lastPropertyFlagsId(), foo2Id);

        // write property
        cls.clearReceivedArgs();
        QScriptValue newFoo2Value(&eng, 789);
        obj1.setProperty(foo2, newFoo2Value);
        QVERIFY(cls.lastQueryPropertyObject().strictlyEquals(obj1));
        QVERIFY(cls.lastQueryPropertyName() == foo2);

        // read property again
        cls.clearReceivedArgs();
        {
            QScriptValue ret = obj1.property(foo2);
            QVERIFY(ret.strictlyEquals(newFoo2Value));
        }
        QVERIFY(cls.lastQueryPropertyObject().strictlyEquals(obj1));
        QVERIFY(cls.lastQueryPropertyName() == foo2);
        QVERIFY(cls.lastPropertyObject().strictlyEquals(obj1));
        QVERIFY(cls.lastPropertyName() == foo2);
        QCOMPARE(cls.lastPropertyId(), foo2Id);
    }
}
Ejemplo n.º 5
0
/*!
  Applies the given \a command to the given \a backend.
*/
QScriptDebuggerResponse QScriptDebuggerCommandExecutor::execute(
    QScriptDebuggerBackend *backend,
    const QScriptDebuggerCommand &command)
{
    QScriptDebuggerResponse response;
    switch (command.type()) {
    case QScriptDebuggerCommand::None:
        break;

    case QScriptDebuggerCommand::Interrupt:
        backend->interruptEvaluation();
        break;

    case QScriptDebuggerCommand::Continue:
        if (backend->engine()->isEvaluating()) {
            backend->continueEvalution();
            response.setAsync(true);
        }
        break;

    case QScriptDebuggerCommand::StepInto: {
        QVariant attr = command.attribute(QScriptDebuggerCommand::StepCount);
        int count = attr.isValid() ? attr.toInt() : 1;
        backend->stepInto(count);
        response.setAsync(true);
    }   break;

    case QScriptDebuggerCommand::StepOver: {
        QVariant attr = command.attribute(QScriptDebuggerCommand::StepCount);
        int count = attr.isValid() ? attr.toInt() : 1;
        backend->stepOver(count);
        response.setAsync(true);
    }   break;

    case QScriptDebuggerCommand::StepOut:
        backend->stepOut();
        response.setAsync(true);
        break;

    case QScriptDebuggerCommand::RunToLocation:
        backend->runToLocation(command.fileName(), command.lineNumber());
        response.setAsync(true);
        break;

    case QScriptDebuggerCommand::RunToLocationByID:
        backend->runToLocation(command.scriptId(), command.lineNumber());
        response.setAsync(true);
        break;

    case QScriptDebuggerCommand::ForceReturn: {
        int contextIndex = command.contextIndex();
        QScriptDebuggerValue value = command.scriptValue();
        QScriptEngine *engine = backend->engine();
        QScriptValue realValue = value.toScriptValue(engine);
        backend->returnToCaller(contextIndex, realValue);
        response.setAsync(true);
    }   break;

    case QScriptDebuggerCommand::Resume:
        backend->resume();
        response.setAsync(true);
        break;

    case QScriptDebuggerCommand::SetBreakpoint: {
        QScriptBreakpointData data = command.breakpointData();
        if (!data.isValid())
            data = QScriptBreakpointData(command.fileName(), command.lineNumber());
        int id = backend->setBreakpoint(data);
        response.setResult(id);
    }   break;

    case QScriptDebuggerCommand::DeleteBreakpoint: {
        int id = command.breakpointId();
        if (!backend->deleteBreakpoint(id))
            response.setError(QScriptDebuggerResponse::InvalidBreakpointID);
    }   break;

    case QScriptDebuggerCommand::DeleteAllBreakpoints:
        backend->deleteAllBreakpoints();
        break;

    case QScriptDebuggerCommand::GetBreakpoints: {
        QScriptBreakpointMap bps = backend->breakpoints();
        if (!bps.isEmpty())
            response.setResult(bps);
    }   break;

    case QScriptDebuggerCommand::GetBreakpointData: {
        int id = command.breakpointId();
        QScriptBreakpointData data = backend->breakpointData(id);
        if (data.isValid())
            response.setResult(data);
        else
            response.setError(QScriptDebuggerResponse::InvalidBreakpointID);
    }   break;

    case QScriptDebuggerCommand::SetBreakpointData: {
        int id = command.breakpointId();
        QScriptBreakpointData data = command.breakpointData();
        if (!backend->setBreakpointData(id, data))
            response.setError(QScriptDebuggerResponse::InvalidBreakpointID);
    }   break;

    case QScriptDebuggerCommand::GetScripts: {
        QScriptScriptMap scripts = backend->scripts();
        if (!scripts.isEmpty())
            response.setResult(scripts);
    }   break;

    case QScriptDebuggerCommand::GetScriptData: {
        qint64 id = command.scriptId();
        QScriptScriptData data = backend->scriptData(id);
        if (data.isValid())
            response.setResult(data);
        else
            response.setError(QScriptDebuggerResponse::InvalidScriptID);
    }   break;

    case QScriptDebuggerCommand::ScriptsCheckpoint:
        backend->scriptsCheckpoint();
        response.setResult(QVariant::fromValue(backend->scriptsDelta()));
        break;

    case QScriptDebuggerCommand::GetScriptsDelta:
        response.setResult(QVariant::fromValue(backend->scriptsDelta()));
        break;

    case QScriptDebuggerCommand::ResolveScript:
        response.setResult(backend->resolveScript(command.fileName()));
        break;

    case QScriptDebuggerCommand::GetBacktrace:
        response.setResult(backend->backtrace());
        break;

    case QScriptDebuggerCommand::GetContextCount:
        response.setResult(backend->contextCount());
        break;

    case QScriptDebuggerCommand::GetContextState: {
        QScriptContext *ctx = backend->context(command.contextIndex());
        if (ctx)
            response.setResult(static_cast<int>(ctx->state()));
        else
            response.setError(QScriptDebuggerResponse::InvalidContextIndex);
    }   break;

    case QScriptDebuggerCommand::GetContextID: {
        int idx = command.contextIndex();
        if ((idx >= 0) && (idx < backend->contextCount()))
            response.setResult(backend->contextIds()[idx]);
        else
            response.setError(QScriptDebuggerResponse::InvalidContextIndex);
    }   break;

    case QScriptDebuggerCommand::GetContextInfo: {
        QScriptContext *ctx = backend->context(command.contextIndex());
        if (ctx)
            response.setResult(QScriptContextInfo(ctx));
        else
            response.setError(QScriptDebuggerResponse::InvalidContextIndex);
    }   break;

    case QScriptDebuggerCommand::GetThisObject: {
        QScriptContext *ctx = backend->context(command.contextIndex());
        if (ctx)
            response.setResult(ctx->thisObject());
        else
            response.setError(QScriptDebuggerResponse::InvalidContextIndex);
    }   break;

    case QScriptDebuggerCommand::GetActivationObject: {
        QScriptContext *ctx = backend->context(command.contextIndex());
        if (ctx)
            response.setResult(ctx->activationObject());
        else
            response.setError(QScriptDebuggerResponse::InvalidContextIndex);
    }   break;

    case QScriptDebuggerCommand::GetScopeChain: {
        QScriptContext *ctx = backend->context(command.contextIndex());
        if (ctx) {
            QScriptDebuggerValueList dest;
            QScriptValueList src = ctx->scopeChain();
            for (int i = 0; i < src.size(); ++i)
                dest.append(src.at(i));
            response.setResult(dest);
        } else {
            response.setError(QScriptDebuggerResponse::InvalidContextIndex);
        }
    }   break;

    case QScriptDebuggerCommand::ContextsCheckpoint: {
        response.setResult(QVariant::fromValue(backend->contextsCheckpoint()));
    }   break;

    case QScriptDebuggerCommand::GetPropertyExpressionValue: {
        QScriptContext *ctx = backend->context(command.contextIndex());
        int lineNumber = command.lineNumber();
        QVariant attr = command.attribute(QScriptDebuggerCommand::UserAttribute);
        QStringList path = attr.toStringList();
        if (!ctx || path.isEmpty())
            break;
        QScriptContextInfo ctxInfo(ctx);
        if (ctx->callee().isValid()
            && ((lineNumber < ctxInfo.functionStartLineNumber())
                || (lineNumber > ctxInfo.functionEndLineNumber()))) {
            break;
        }
        QScriptValueList objects;
        int pathIndex = 0;
        if (path.at(0) == QLatin1String("this")) {
            objects.append(ctx->thisObject());
            ++pathIndex;
        } else {
            objects << ctx->scopeChain();
        }
        for (int i = 0; i < objects.size(); ++i) {
            QScriptValue val = objects.at(i);
            for (int j = pathIndex; val.isValid() && (j < path.size()); ++j) {
                val = val.property(path.at(j));
            }
            if (val.isValid()) {
                bool hadException = (ctx->state() == QScriptContext::ExceptionState);
                QString str = val.toString();
                if (!hadException && backend->engine()->hasUncaughtException())
                    backend->engine()->clearExceptions();
                response.setResult(str);
                break;
            }
        }
    }   break;

    case QScriptDebuggerCommand::GetCompletions: {
        QScriptContext *ctx = backend->context(command.contextIndex());
        QVariant attr = command.attribute(QScriptDebuggerCommand::UserAttribute);
        QStringList path = attr.toStringList();
        if (!ctx || path.isEmpty())
            break;
        QScriptValueList objects;
        QString prefix = path.last();
        QSet<QString> matches;
        if (path.size() > 1) {
            const QString &topLevelIdent = path.at(0);
            QScriptValue obj;
            if (topLevelIdent == QLatin1String("this")) {
                obj = ctx->thisObject();
            } else {
                QScriptValueList scopeChain;
                scopeChain = ctx->scopeChain();
                for (int i = 0; i < scopeChain.size(); ++i) {
                    QScriptValue oo = scopeChain.at(i).property(topLevelIdent);
                    if (oo.isObject()) {
                        obj = oo;
                        break;
                    }
                }
            }
            for (int i = 1; obj.isObject() && (i < path.size()-1); ++i)
                obj = obj.property(path.at(i));
            if (obj.isValid())
                objects.append(obj);
        } else {
            objects << ctx->scopeChain();
            QStringList keywords;
            keywords.append(QString::fromLatin1("this"));
            keywords.append(QString::fromLatin1("true"));
            keywords.append(QString::fromLatin1("false"));
            keywords.append(QString::fromLatin1("null"));
            for (int i = 0; i < keywords.size(); ++i) {
                const QString &kwd = keywords.at(i);
                if (isPrefixOf(prefix, kwd))
                    matches.insert(kwd);
            }
        }

        for (int i = 0; i < objects.size(); ++i) {
            QScriptValue obj = objects.at(i);
            while (obj.isObject()) {
                QScriptValueIterator it(obj);
                while (it.hasNext()) {
                    it.next();
                    QString propertyName = it.name();
                    if (isPrefixOf(prefix, propertyName))
                        matches.insert(propertyName);
                }
                obj = obj.prototype();
            }
        }
        QStringList matchesList = matches.toList();
        qStableSort(matchesList);
        response.setResult(matchesList);
    }   break;

    case QScriptDebuggerCommand::NewScriptObjectSnapshot: {
        int id = backend->newScriptObjectSnapshot();
        response.setResult(id);
    }   break;

    case QScriptDebuggerCommand::ScriptObjectSnapshotCapture: {
        int id = command.snapshotId();
        QScriptObjectSnapshot *snap = backend->scriptObjectSnapshot(id);
        Q_ASSERT(snap != 0);
        QScriptDebuggerValue object = command.scriptValue();
        Q_ASSERT(object.type() == QScriptDebuggerValue::ObjectValue);
        QScriptEngine *engine = backend->engine();
        QScriptValue realObject = object.toScriptValue(engine);
        Q_ASSERT(realObject.isObject());
        QScriptObjectSnapshot::Delta delta = snap->capture(realObject);
        QScriptDebuggerObjectSnapshotDelta result;
        result.removedProperties = delta.removedProperties;
        bool didIgnoreExceptions = backend->ignoreExceptions();
        backend->setIgnoreExceptions(true);
        for (int i = 0; i < delta.changedProperties.size(); ++i) {
            const QScriptValueProperty &src = delta.changedProperties.at(i);
            bool hadException = engine->hasUncaughtException();
            QString str = src.value().toString();
            if (!hadException && engine->hasUncaughtException())
                engine->clearExceptions();
            QScriptDebuggerValueProperty dest(src.name(), src.value(), str, src.flags());
            result.changedProperties.append(dest);
        }
        for (int j = 0; j < delta.addedProperties.size(); ++j) {
            const QScriptValueProperty &src = delta.addedProperties.at(j);
            bool hadException = engine->hasUncaughtException();
            QString str = src.value().toString();
            if (!hadException && engine->hasUncaughtException())
                engine->clearExceptions();
            QScriptDebuggerValueProperty dest(src.name(), src.value(), str, src.flags());
            result.addedProperties.append(dest);
        }
        backend->setIgnoreExceptions(didIgnoreExceptions);
        response.setResult(QVariant::fromValue(result));
    }   break;

    case QScriptDebuggerCommand::DeleteScriptObjectSnapshot: {
        int id = command.snapshotId();
        backend->deleteScriptObjectSnapshot(id);
    }   break;

    case QScriptDebuggerCommand::NewScriptValueIterator: {
        QScriptDebuggerValue object = command.scriptValue();
        Q_ASSERT(object.type() == QScriptDebuggerValue::ObjectValue);
        QScriptEngine *engine = backend->engine();
        QScriptValue realObject = object.toScriptValue(engine);
        Q_ASSERT(realObject.isObject());
        int id = backend->newScriptValueIterator(realObject);
        response.setResult(id);
    }   break;

    case QScriptDebuggerCommand::GetPropertiesByIterator: {
        int id = command.iteratorId();
        int count = 1000;
        QScriptValueIterator *it = backend->scriptValueIterator(id);
        Q_ASSERT(it != 0);
        QScriptDebuggerValuePropertyList props;
        for (int i = 0; (i < count) && it->hasNext(); ++i) {
            it->next();
            QString name = it->name();
            QScriptValue value = it->value();
            QString valueAsString = value.toString();
            QScriptValue::PropertyFlags flags = it->flags();
            QScriptDebuggerValueProperty prp(name, value, valueAsString, flags);
            props.append(prp);
        }
        response.setResult(props);
    }   break;

    case QScriptDebuggerCommand::DeleteScriptValueIterator: {
        int id = command.iteratorId();
        backend->deleteScriptValueIterator(id);
    }   break;

    case QScriptDebuggerCommand::Evaluate: {
        int contextIndex = command.contextIndex();
        QString program = command.program();
        QString fileName = command.fileName();
        int lineNumber = command.lineNumber();
        backend->evaluate(contextIndex, program, fileName, lineNumber);
        response.setAsync(true);
    }   break;

    case QScriptDebuggerCommand::ScriptValueToString: {
        QScriptDebuggerValue value = command.scriptValue();
        QScriptEngine *engine = backend->engine();
        QScriptValue realValue = value.toScriptValue(engine);
        response.setResult(realValue.toString());
    }   break;

    case QScriptDebuggerCommand::SetScriptValueProperty: {
        QScriptDebuggerValue object = command.scriptValue();
        QScriptEngine *engine = backend->engine();
        QScriptValue realObject = object.toScriptValue(engine);
        QScriptDebuggerValue value = command.subordinateScriptValue();
        QScriptValue realValue = value.toScriptValue(engine);
        QString name = command.name();
        realObject.setProperty(name, realValue);
    }   break;

    case QScriptDebuggerCommand::ClearExceptions:
        backend->engine()->clearExceptions();
        break;

    case QScriptDebuggerCommand::UserCommand:
    case QScriptDebuggerCommand::MaxUserCommand:
        break;
    }
    return response;
}
Ejemplo n.º 6
0
void REcmaBlock::initEcma(QScriptEngine& engine, QScriptValue* proto

                         )

{

    bool protoCreated = false;
    if(proto == NULL) {
        proto = new QScriptValue(engine.newVariant(qVariantFromValue(
                                     (RBlock*) 0)));
        protoCreated = true;
    }


    // primary base class RObject:

    QScriptValue dpt = engine.defaultPrototype(
                           qMetaTypeId<RObject*>());

    if (dpt.isValid()) {
        proto->setPrototype(dpt);
    }

    /*

    */


    QScriptValue fun;

    // toString:
    REcmaHelper::registerFunction(&engine, proto, toString, "toString");


    // destroy:
    REcmaHelper::registerFunction(&engine, proto, destroy, "destroy");

    // conversion for base class RObject
    REcmaHelper::registerFunction(&engine, proto, getRObject, "getRObject");


    // get class name
    REcmaHelper::registerFunction(&engine, proto, getClassName, "getClassName");


    // conversion to all base classes (multiple inheritance):
    REcmaHelper::registerFunction(&engine, proto, getBaseClasses, "getBaseClasses");


    // properties:


    // methods:

    REcmaHelper::registerFunction(&engine, proto, getType, "getType");

    REcmaHelper::registerFunction(&engine, proto, clone, "clone");

    REcmaHelper::registerFunction(&engine, proto, getName, "getName");

    REcmaHelper::registerFunction(&engine, proto, setName, "setName");

    REcmaHelper::registerFunction(&engine, proto, isFrozen, "isFrozen");

    REcmaHelper::registerFunction(&engine, proto, setFrozen, "setFrozen");

    REcmaHelper::registerFunction(&engine, proto, isAnonymous, "isAnonymous");

    REcmaHelper::registerFunction(&engine, proto, setAnonymous, "setAnonymous");

    REcmaHelper::registerFunction(&engine, proto, setOrigin, "setOrigin");

    REcmaHelper::registerFunction(&engine, proto, getOrigin, "getOrigin");

    REcmaHelper::registerFunction(&engine, proto, getProperty, "getProperty");

    REcmaHelper::registerFunction(&engine, proto, setProperty, "setProperty");

    REcmaHelper::registerFunction(&engine, proto, isSelectedForPropertyEditing, "isSelectedForPropertyEditing");

    engine.setDefaultPrototype(
        qMetaTypeId<RBlock*>(), *proto);




    QScriptValue ctor = engine.newFunction(createEcma, *proto, 2);

    // static methods:

    REcmaHelper::registerFunction(&engine, &ctor, init, "init");


    // static properties:

    ctor.setProperty("PropertyCustom",
                     qScriptValueFromValue(&engine, RBlock::PropertyCustom),
                     QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);

    ctor.setProperty("PropertyName",
                     qScriptValueFromValue(&engine, RBlock::PropertyName),
                     QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);

    ctor.setProperty("PropertyFrozen",
                     qScriptValueFromValue(&engine, RBlock::PropertyFrozen),
                     QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);

    ctor.setProperty("modelSpaceName",
                     qScriptValueFromValue(&engine, RBlock::modelSpaceName),
                     QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);


    // enum values:


    // enum conversions:


    // init class:
    engine.globalObject().setProperty("RBlock",
                                      ctor, QScriptValue::SkipInEnumeration);

    if( protoCreated ) {
        delete proto;
    }

}
Ejemplo n.º 7
0
                 void REcmaFileImporterAdapter::initEcma(QScriptEngine& engine, QScriptValue* proto 
    
    ) 
    
    {

    bool protoCreated = false;
    if(proto == NULL){
        proto = new QScriptValue(engine.newVariant(qVariantFromValue(
                (RFileImporterAdapter*) 0)));
        protoCreated = true;
    }

    
        // primary base class RFileImporter:
        
            QScriptValue dpt = engine.defaultPrototype(
                qMetaTypeId<RFileImporter*>());

            if (dpt.isValid()) {
                proto->setPrototype(dpt);
            }
          
        /*
        
        */
    

    QScriptValue fun;

    // toString:
    REcmaHelper::registerFunction(&engine, proto, toString, "toString");
    

    // destroy:
    REcmaHelper::registerFunction(&engine, proto, destroy, "destroy");
    
        // conversion for base class RFileImporter
        REcmaHelper::registerFunction(&engine, proto, getRFileImporter, "getRFileImporter");
        
        // conversion for base class RImporter
        REcmaHelper::registerFunction(&engine, proto, getRImporter, "getRImporter");
        

    // get class name
    REcmaHelper::registerFunction(&engine, proto, getClassName, "getClassName");
    

    // conversion to all base classes (multiple inheritance):
    REcmaHelper::registerFunction(&engine, proto, getBaseClasses, "getBaseClasses");
    

    // properties:
    

    // methods:
    
            REcmaHelper::registerFunction(&engine, proto, importFile, "importFile");
            
        engine.setDefaultPrototype(
            qMetaTypeId<RFileImporterAdapter*>(), *proto);

        
    

    QScriptValue ctor = engine.newFunction(createEcma, *proto, 2);
    
    // static methods:
    

    // static properties:
    

    // enum values:
    

    // enum conversions:
    
        
    // init class:
    engine.globalObject().setProperty("RFileImporterAdapter",
    ctor, QScriptValue::SkipInEnumeration);
    
    if( protoCreated ){
       delete proto;
    }
    
    }
Ejemplo n.º 8
0
void PostalCodeModel::parseFile( const QByteArray& file )
{
    QScriptValue data;
    QScriptEngine engine;

    // Qt requires parentheses around json code
    data = engine.evaluate( "(" + QString( file ) + ")" );

    // Parse if any result exists
    if ( data.property( "postalCodes" ).isArray() ) {
        QScriptValueIterator iterator( data.property( "postalCodes" ) );

        // Add items to the list
        while ( iterator.hasNext() ) {
            iterator.next();

            QString const placeName = QString::fromUtf8(
                                          iterator.value().property( "placeName" ).toString().toStdString().c_str());
            QString const adminName1 = QString::fromUtf8(
                                           iterator.value().property( "adminName1" ).toString().toStdString().c_str());
            QString const adminName2 = QString::fromUtf8(
                                           iterator.value().property( "adminName2" ).toString().toStdString().c_str());
            QString const adminName3 = QString::fromUtf8(
                                           iterator.value().property( "adminName3" ).toString().toStdString().c_str());
            QString const postalCode = iterator.value().property( "postalCode" ).toString();
            QString const countryCode = iterator.value().property( "countryCode" ).toString();
            double const longitude = iterator.value().property( "lng" ).toNumber();
            double const latitude = iterator.value().property( "lat" ).toNumber();

            QString const id = "postalCode_" + countryCode + postalCode;

            if ( !id.isEmpty() ) {
                QString tooltip;

                if ( !placeName.isEmpty() ) {
                    tooltip += placeName + " ";
                }

                addLine( &tooltip, postalCode );
                addLine( &tooltip, countryCode );
                addLine( &tooltip, adminName1 );
                addLine( &tooltip, adminName2 );
                addLine( &tooltip, adminName3 );
                tooltip = tooltip.trimmed();

                if( !itemExists( id ) ) {
                    // If it does not exist, create it
                    GeoDataCoordinates coordinates( longitude, latitude, 0.0, GeoDataCoordinates::Degree );

                    PostalCodeItem *item = new PostalCodeItem( this );
                    item->setId( id );
                    item->setCoordinate( coordinates );
                    item->setTarget( "earth" );
                    item->setToolTip( tooltip );
                    item->setText( postalCode );

                    addItemToList( item );
                }
            }
        }
    }
}
Ejemplo n.º 9
0
                 void REcmaDimDiametricEntity::init(QScriptEngine& engine, QScriptValue* proto 
    
    ) 
    
    {

    bool protoCreated = false;
    if(proto == NULL){
        proto = new QScriptValue(engine.newVariant(qVariantFromValue(
                (RDimDiametricEntity*) 0)));
        protoCreated = true;
    }

    
        // primary base class RDimensionEntity:
        
            QScriptValue dpt = engine.defaultPrototype(
                qMetaTypeId<RDimensionEntity*>());

            if (dpt.isValid()) {
                proto->setPrototype(dpt);
            }
          
        /*
        
        */
    

    QScriptValue fun;

    // toString:
    REcmaHelper::registerFunction(&engine, proto, toString, "toString");
    

    // destroy:
    REcmaHelper::registerFunction(&engine, proto, destroy, "destroy");
    
        // conversion for base class RDimensionEntity
        REcmaHelper::registerFunction(&engine, proto, getRDimensionEntity, "getRDimensionEntity");
        
        // conversion for base class REntity
        REcmaHelper::registerFunction(&engine, proto, getREntity, "getREntity");
        
        // conversion for base class RObject
        REcmaHelper::registerFunction(&engine, proto, getRObject, "getRObject");
        

    // get class name
    REcmaHelper::registerFunction(&engine, proto, getClassName, "getClassName");
    

    // conversion to all base classes (multiple inheritance):
    REcmaHelper::registerFunction(&engine, proto, getBaseClasses, "getBaseClasses");
    

    // properties:
    

    // methods:
    
            REcmaHelper::registerFunction(&engine, proto, clone, "clone");
            
            REcmaHelper::registerFunction(&engine, proto, getType, "getType");
            
            REcmaHelper::registerFunction(&engine, proto, setProperty, "setProperty");
            
            REcmaHelper::registerFunction(&engine, proto, getProperty, "getProperty");
            
            REcmaHelper::registerFunction(&engine, proto, getData, "getData");
            
            REcmaHelper::registerFunction(&engine, proto, setData, "setData");
            
            REcmaHelper::registerFunction(&engine, proto, setChordPoint, "setChordPoint");
            
            REcmaHelper::registerFunction(&engine, proto, getChordPoint, "getChordPoint");
            
            REcmaHelper::registerFunction(&engine, proto, setFarChordPoint, "setFarChordPoint");
            
            REcmaHelper::registerFunction(&engine, proto, getFarChordPoint, "getFarChordPoint");
            
        engine.setDefaultPrototype(
            qMetaTypeId<RDimDiametricEntity*>(), *proto);

        
    

    QScriptValue ctor = engine.newFunction(create, *proto, 2);
    
    // static methods:
    
            REcmaHelper::registerFunction(&engine, &ctor, init, "init");
            

    // static properties:
    
            ctor.setProperty("PropertyCustom",
                qScriptValueFromValue(&engine, RDimDiametricEntity::PropertyCustom),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyHandle",
                qScriptValueFromValue(&engine, RDimDiametricEntity::PropertyHandle),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyType",
                qScriptValueFromValue(&engine, RDimDiametricEntity::PropertyType),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyBlock",
                qScriptValueFromValue(&engine, RDimDiametricEntity::PropertyBlock),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyLayer",
                qScriptValueFromValue(&engine, RDimDiametricEntity::PropertyLayer),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyLinetype",
                qScriptValueFromValue(&engine, RDimDiametricEntity::PropertyLinetype),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyLineweight",
                qScriptValueFromValue(&engine, RDimDiametricEntity::PropertyLineweight),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyColor",
                qScriptValueFromValue(&engine, RDimDiametricEntity::PropertyColor),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyDrawOrder",
                qScriptValueFromValue(&engine, RDimDiametricEntity::PropertyDrawOrder),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyMiddleOfTextX",
                qScriptValueFromValue(&engine, RDimDiametricEntity::PropertyMiddleOfTextX),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyMiddleOfTextY",
                qScriptValueFromValue(&engine, RDimDiametricEntity::PropertyMiddleOfTextY),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyMiddleOfTextZ",
                qScriptValueFromValue(&engine, RDimDiametricEntity::PropertyMiddleOfTextZ),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyText",
                qScriptValueFromValue(&engine, RDimDiametricEntity::PropertyText),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyUpperTolerance",
                qScriptValueFromValue(&engine, RDimDiametricEntity::PropertyUpperTolerance),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyLowerTolerance",
                qScriptValueFromValue(&engine, RDimDiametricEntity::PropertyLowerTolerance),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyChordPointX",
                qScriptValueFromValue(&engine, RDimDiametricEntity::PropertyChordPointX),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyChordPointY",
                qScriptValueFromValue(&engine, RDimDiametricEntity::PropertyChordPointY),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyChordPointZ",
                qScriptValueFromValue(&engine, RDimDiametricEntity::PropertyChordPointZ),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyFarChordPointX",
                qScriptValueFromValue(&engine, RDimDiametricEntity::PropertyFarChordPointX),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyFarChordPointY",
                qScriptValueFromValue(&engine, RDimDiametricEntity::PropertyFarChordPointY),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyFarChordPointZ",
                qScriptValueFromValue(&engine, RDimDiametricEntity::PropertyFarChordPointZ),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            

    // enum values:
    

    // enum conversions:
    
        
    // init class:
    engine.globalObject().setProperty("RDimDiametricEntity",
    ctor, QScriptValue::SkipInEnumeration);
    
    if( protoCreated ){
       delete proto;
    }
    
    }
Ejemplo n.º 10
0
bool testPlayerScript(QString path, int player, int difficulty)
{
	QScriptEngine *engine = new QScriptEngine();
	QFile input(path);
	input.open(QIODevice::ReadOnly);
	QString source(QString::fromUtf8(input.readAll()));
	input.close();

	// Special functions
	engine->globalObject().setProperty("setTimer", engine->newFunction(js_setTimer));
	engine->globalObject().setProperty("queue", engine->newFunction(js_queue));
	engine->globalObject().setProperty("removeTimer", engine->newFunction(js_removeTimer));
	engine->globalObject().setProperty("include", engine->newFunction(js_include));
	engine->globalObject().setProperty("bind", engine->newFunction(js_bind));

	// Special global variables
	engine->globalObject().setProperty("version", 1, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("selectedPlayer", 0, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("gameTime", 2, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("difficulty", 1, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("mapName", "TEST", QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("baseType", 1, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("alliancesType", 2, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("powerType", 1, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("maxPlayers", CUR_PLAYERS, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("scavengers", true, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("mapWidth", 80, QScriptValue::ReadOnly | QScriptValue::Undeletable);
	engine->globalObject().setProperty("mapHeight", 80, QScriptValue::ReadOnly | QScriptValue::Undeletable);

	// Most special global
	engine->globalObject().setProperty("me", player, QScriptValue::ReadOnly | QScriptValue::Undeletable);

	// Register functions to the script engine here
	engine->globalObject().setProperty("_", engine->newFunction(js_translate));
	engine->globalObject().setProperty("label", engine->newFunction(js_label));
	engine->globalObject().setProperty("enumLabels", engine->newFunction(js_enumLabels));
	engine->globalObject().setProperty("enumGateways", engine->newFunction(js_enumGateways));

	// horrible hacks follow -- do not rely on these being present!
	engine->globalObject().setProperty("hackNetOff", engine->newFunction(js_hackNetOff));
	engine->globalObject().setProperty("hackNetOn", engine->newFunction(js_hackNetOn));
	engine->globalObject().setProperty("objFromId", engine->newFunction(js_objFromId));

	// General functions -- geared for use in AI scripts
	engine->globalObject().setProperty("debug", engine->newFunction(js_debug));
	engine->globalObject().setProperty("console", engine->newFunction(js_console));
	engine->globalObject().setProperty("structureIdle", engine->newFunction(js_structureIdle));
	engine->globalObject().setProperty("enumStruct", engine->newFunction(js_enumStruct));
	engine->globalObject().setProperty("enumStructOffWorld", engine->newFunction(js_enumStructOffWorld));
	engine->globalObject().setProperty("enumDroid", engine->newFunction(js_enumDroid));
	engine->globalObject().setProperty("enumGroup", engine->newFunction(js_enumGroup));
	engine->globalObject().setProperty("enumFeature", engine->newFunction(js_enumFeature));
	engine->globalObject().setProperty("enumBlips", engine->newFunction(js_enumBlips));
	engine->globalObject().setProperty("enumResearch", engine->newFunction(js_enumResearch));
	engine->globalObject().setProperty("getResearch", engine->newFunction(js_getResearch));
	engine->globalObject().setProperty("pursueResearch", engine->newFunction(js_pursueResearch));
	engine->globalObject().setProperty("distBetweenTwoPoints", engine->newFunction(js_distBetweenTwoPoints));
	engine->globalObject().setProperty("newGroup", engine->newFunction(js_newGroup));
	engine->globalObject().setProperty("groupAddArea", engine->newFunction(js_groupAddArea));
	engine->globalObject().setProperty("groupAddDroid", engine->newFunction(js_groupAddDroid));
	engine->globalObject().setProperty("groupSize", engine->newFunction(js_groupSize));
	engine->globalObject().setProperty("orderDroidLoc", engine->newFunction(js_orderDroidLoc));
	engine->globalObject().setProperty("playerPower", engine->newFunction(js_playerPower));
	engine->globalObject().setProperty("isStructureAvailable", engine->newFunction(js_isStructureAvailable));
	engine->globalObject().setProperty("pickStructLocation", engine->newFunction(js_pickStructLocation));
	engine->globalObject().setProperty("droidCanReach", engine->newFunction(js_droidCanReach));
	engine->globalObject().setProperty("orderDroidStatsLoc", engine->newFunction(js_orderDroidBuild)); // deprecated
	engine->globalObject().setProperty("orderDroidBuild", engine->newFunction(js_orderDroidBuild));
	engine->globalObject().setProperty("orderDroidObj", engine->newFunction(js_orderDroidObj));
	engine->globalObject().setProperty("orderDroid", engine->newFunction(js_orderDroid));
	engine->globalObject().setProperty("buildDroid", engine->newFunction(js_buildDroid));
	engine->globalObject().setProperty("addDroid", engine->newFunction(js_addDroid));
	engine->globalObject().setProperty("addFeature", engine->newFunction(js_addFeature));
	engine->globalObject().setProperty("componentAvailable", engine->newFunction(js_componentAvailable));
	engine->globalObject().setProperty("isVTOL", engine->newFunction(js_isVTOL));
	engine->globalObject().setProperty("safeDest", engine->newFunction(js_safeDest));
	engine->globalObject().setProperty("activateStructure", engine->newFunction(js_activateStructure));
	engine->globalObject().setProperty("chat", engine->newFunction(js_chat));

	// Functions that operate on the current player only
	engine->globalObject().setProperty("centreView", engine->newFunction(js_centreView));
	engine->globalObject().setProperty("playSound", engine->newFunction(js_playSound));
	engine->globalObject().setProperty("gameOverMessage", engine->newFunction(js_gameOverMessage));

	// Global state manipulation -- not for use with skirmish AI (unless you want it to cheat, obviously)
	engine->globalObject().setProperty("setStructureLimits", engine->newFunction(js_setStructureLimits));
	engine->globalObject().setProperty("applyLimitSet", engine->newFunction(js_applyLimitSet));
	engine->globalObject().setProperty("setMissionTime", engine->newFunction(js_setMissionTime));
	engine->globalObject().setProperty("setReinforcementTime", engine->newFunction(js_setReinforcementTime));
	engine->globalObject().setProperty("completeResearch", engine->newFunction(js_completeResearch));
	engine->globalObject().setProperty("enableResearch", engine->newFunction(js_enableResearch));
	engine->globalObject().setProperty("setPower", engine->newFunction(js_setPower));
	engine->globalObject().setProperty("setTutorialMode", engine->newFunction(js_setTutorialMode));
	engine->globalObject().setProperty("setDesign", engine->newFunction(js_setDesign));
	engine->globalObject().setProperty("setMiniMap", engine->newFunction(js_setMiniMap));
	engine->globalObject().setProperty("addReticuleButton", engine->newFunction(js_addReticuleButton));
	engine->globalObject().setProperty("removeReticuleButton", engine->newFunction(js_removeReticuleButton));
	engine->globalObject().setProperty("enableStructure", engine->newFunction(js_enableStructure));
	engine->globalObject().setProperty("makeComponentAvailable", engine->newFunction(js_makeComponentAvailable));
	engine->globalObject().setProperty("enableComponent", engine->newFunction(js_enableComponent));
	engine->globalObject().setProperty("enableTemplate", engine->newFunction(js_enableTemplate));
	engine->globalObject().setProperty("allianceExistsBetween", engine->newFunction(js_allianceExistsBetween));
	engine->globalObject().setProperty("removeStruct", engine->newFunction(js_removeStruct));
	engine->globalObject().setProperty("removeObject", engine->newFunction(js_removeObject));
	engine->globalObject().setProperty("setScrollParams", engine->newFunction(js_setScrollParams));
	engine->globalObject().setProperty("addStructure", engine->newFunction(js_addStructure));
	engine->globalObject().setProperty("loadLevel", engine->newFunction(js_loadLevel));
	engine->globalObject().setProperty("setDroidExperience", engine->newFunction(js_setDroidExperience));
	engine->globalObject().setProperty("setNoGoArea", engine->newFunction(js_setNoGoArea));
	engine->globalObject().setProperty("setAlliance", engine->newFunction(js_setAlliance));
	engine->globalObject().setProperty("setAssemblyPoint", engine->newFunction(js_setAssemblyPoint));

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

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

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

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

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

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

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

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

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

	// Clean up
	delete engine;
	timers.clear();
	return true;
}
void tst_QScriptEngineDebugger::attachAndDetach()
{
#if defined(Q_OS_WINCE) && _WIN32_WCE < 0x600
    QSKIP("skipped due to high mem usage until task 261062 is fixed");
#endif
    {
        QScriptEngineDebugger debugger;
        QCOMPARE(debugger.state(), QScriptEngineDebugger::SuspendedState);
        debugger.attachTo(0);
        QScriptEngine engine;
        debugger.attachTo(&engine);
        QCOMPARE(debugger.state(), QScriptEngineDebugger::SuspendedState);
    }
    {
        QScriptEngineDebugger debugger;
        QScriptEngine engine;
        QScriptValue oldPrint = engine.globalObject().property("print");
        QVERIFY(oldPrint.isFunction());
        QVERIFY(!engine.globalObject().property("__FILE__").isValid());
        QVERIFY(!engine.globalObject().property("__LINE__").isValid());

        debugger.attachTo(&engine);
        QVERIFY(engine.globalObject().property("__FILE__").isUndefined());
        QVERIFY(engine.globalObject().property("__LINE__").isNumber());
        QVERIFY(!engine.globalObject().property("print").strictlyEquals(oldPrint));

        debugger.detach();
        QVERIFY(engine.globalObject().property("print").strictlyEquals(oldPrint));
        QVERIFY(!engine.globalObject().property("__FILE__").isValid());
        QVERIFY(!engine.globalObject().property("__LINE__").isValid());
    }
    {
        QScriptEngineDebugger debugger;
        QScriptEngine engine;
        debugger.attachTo(&engine);
        debugger.detach();
        QScriptEngine engine2;
        debugger.attachTo(&engine2);
    }
    {
        QScriptEngineDebugger debugger;
        QScriptEngine engine;
        debugger.attachTo(&engine);
        debugger.detach();
        QScriptEngine engine2;
        debugger.attachTo(&engine2);
        debugger.detach();
    }
#ifndef Q_OS_WINCE // demands too much memory for WinCE
    {
        QScriptEngineDebugger debugger;
        QScriptEngine engine;
        debugger.attachTo(&engine);
        QScriptEngineDebugger debugger2;
        debugger2.attachTo(&engine);
    }
#endif
    {
        QScriptEngine *engine = new QScriptEngine;
        QScriptEngineDebugger debugger;
        debugger.attachTo(engine);
        delete engine;
        QScriptEngine engine2;
        debugger.attachTo(&engine2);
    }
}
Ejemplo n.º 12
0
                 void REcmaSharedPointerLinetype::init(QScriptEngine& engine, QScriptValue* proto 
    
    ) 
    
    {

    bool protoCreated = false;
    if(proto == NULL){
        proto = new QScriptValue(engine.newVariant(qVariantFromValue(
                (RLinetypePointer*) 0)));
        protoCreated = true;
    }

    
        // primary base class RObject:
        
            proto->setPrototype(engine.defaultPrototype(
            qMetaTypeId<RObjectPointer>()));
          
        /*
        
        */
    

    QScriptValue fun;

    // toString:
    REcmaHelper::registerFunction(&engine, proto, toString, "toString");
    
    // copy:
    REcmaHelper::registerFunction(&engine, proto, copy, "copy");
    
        // shared pointer support:
        REcmaHelper::registerFunction(&engine, proto, data, "data");
        

        REcmaHelper::registerFunction(&engine, proto, isNull, "isNull");
        

    // destroy:
    REcmaHelper::registerFunction(&engine, proto, destroy, "destroy");
    
        // conversion for base class RObject
        REcmaHelper::registerFunction(&engine, proto, getRObject, "getRObject");
        

    // get class name
    REcmaHelper::registerFunction(&engine, proto, getClassName, "getClassName");
    

    // conversion to all base classes (multiple inheritance):
    REcmaHelper::registerFunction(&engine, proto, getBaseClasses, "getBaseClasses");
    

    // properties:
    

    // methods:
    
            REcmaHelper::registerFunction(&engine, proto, clone, "clone");
            
            REcmaHelper::registerFunction(&engine, proto, getName, "getName");
            
            REcmaHelper::registerFunction(&engine, proto, setName, "setName");
            
            REcmaHelper::registerFunction(&engine, proto, isValid, "isValid");
            
            REcmaHelper::registerFunction(&engine, proto, getProperty, "getProperty");
            
            REcmaHelper::registerFunction(&engine, proto, setProperty, "setProperty");
            
            REcmaHelper::registerFunction(&engine, proto, isSelectedForPropertyEditing, "isSelectedForPropertyEditing");
            
            REcmaHelper::registerFunction(&engine, proto, equals, "equals");
            
            REcmaHelper::registerFunction(&engine, proto, operator_not_assign, "operator_not_assign");
            
            REcmaHelper::registerFunction(&engine, proto, operator_less, "operator_less");
            
        engine.setDefaultPrototype(
            qMetaTypeId<RLinetypePointer>(), *proto);
      
    

    QScriptValue ctor = engine.newFunction(create, *proto, 2);
    
    // static methods:
    
            REcmaHelper::registerFunction(&engine, &ctor, init, "init");
            
            REcmaHelper::registerFunction(&engine, &ctor, getList, "getList");
            
            REcmaHelper::registerFunction(&engine, &ctor, getIcon, "getIcon");
            
            REcmaHelper::registerFunction(&engine, &ctor, getTitle, "getTitle");
            

    // static properties:
    
            ctor.setProperty("PropertyName",
                qScriptValueFromValue(&engine, RLinetype::PropertyName),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            

    // enum values:
    

    // enum conversions:
    
        
    // init class:
    engine.globalObject().setProperty("RLinetypePointer",
    ctor, QScriptValue::SkipInEnumeration);
    
    if( protoCreated ){
       delete proto;
    }
    
    }
int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);

    QScriptEngine eng;

    ByteArrayClass *baClass = new ByteArrayClass(&eng);
    eng.globalObject().setProperty("ByteArray", baClass->constructor());

    qDebug() << "ba = new ByteArray(4):" << eng.evaluate("ba = new ByteArray(4)").toString();
    qDebug() << "ba instanceof ByteArray:" << eng.evaluate("ba instanceof ByteArray").toBool();
    qDebug() << "ba.length:" << eng.evaluate("ba.length").toNumber();
    qDebug() << "ba[1] = 123; ba[1]:" << eng.evaluate("ba[1] = 123; ba[1]").toNumber();
    qDebug() << "ba[7] = 224; ba.length:" << eng.evaluate("ba[7] = 224; ba.length").toNumber();
    qDebug() << "for-in loop:" << eng.evaluate("result = '';\n"
                                               "for (var p in ba) {\n"
                                               "  if (result.length > 0)\n"
                                               "    result += ', ';\n"
                                               "  result += '(' + p + ',' + ba[p] + ')';\n"
                                               "} result").toString();
    qDebug() << "ba.toBase64():" << eng.evaluate("b64 = ba.toBase64()").toString();
    qDebug() << "ba.toBase64().toLatin1String():" << eng.evaluate("b64.toLatin1String()").toString();
    qDebug() << "ba.valueOf():" << eng.evaluate("ba.valueOf()").toString();
    qDebug() << "ba.chop(2); ba.length:" << eng.evaluate("ba.chop(2); ba.length").toNumber();
    qDebug() << "ba2 = new ByteArray(ba):" << eng.evaluate("ba2 = new ByteArray(ba)").toString();
    qDebug() << "ba2.equals(ba):" << eng.evaluate("ba2.equals(ba)").toBool();
    qDebug() << "ba2.equals(new ByteArray()):" << eng.evaluate("ba2.equals(new ByteArray())").toBool();

    return 0;
}
Ejemplo n.º 14
0
void ScriptJob::run()
{
    m_mutex->lock();
    if ( !loadScript(&m_data.program) ) {
        kDebug() << "Script could not be loaded correctly";
        m_mutex->unlock();
        return;
    }

    QScriptEngine *engine = m_engine;
    ScriptObjects objects = m_objects;
    m_mutex->unlock();

    // Store start time of the script
    QElapsedTimer timer;
    timer.start();

    // Add call to the appropriate function
    QString functionName;
    QScriptValueList arguments = QScriptValueList() << request()->toScriptValue( engine );
    switch ( request()->parseMode() ) {
    case ParseForDepartures:
    case ParseForArrivals:
        functionName = ServiceProviderScript::SCRIPT_FUNCTION_GETTIMETABLE;
        break;
    case ParseForJourneysByDepartureTime:
    case ParseForJourneysByArrivalTime:
        functionName = ServiceProviderScript::SCRIPT_FUNCTION_GETJOURNEYS;
        break;
    case ParseForStopSuggestions:
        functionName = ServiceProviderScript::SCRIPT_FUNCTION_GETSTOPSUGGESTIONS;
        break;
    case ParseForAdditionalData:
        functionName = ServiceProviderScript::SCRIPT_FUNCTION_GETADDITIONALDATA;
        break;
    default:
        kDebug() << "Parse mode unsupported:" << request()->parseMode();
        break;
    }

    if ( functionName.isEmpty() ) {
        // This should never happen, therefore no i18n
        handleError( "Unknown parse mode" );
        return;
    }

    // Check if the script function is implemented
    QScriptValue function = engine->globalObject().property( functionName );
    if ( !function.isFunction() ) {
        handleError( i18nc("@info/plain", "Function <icode>%1</icode> not implemented by "
                           "the script", functionName) );
        return;
    }

    // Call script function
    QScriptValue result = function.call( QScriptValue(), arguments );
    if ( engine->hasUncaughtException() ) {
        // TODO Get filename where the exception occured, maybe use ScriptAgent for that
        handleError( i18nc("@info/plain", "Error in script function <icode>%1</icode>, "
                           "line %2: <message>%3</message>.",
                           functionName, engine->uncaughtExceptionLineNumber(),
                           engine->uncaughtException().toString()) );
        return;
    }

    GlobalTimetableInfo globalInfo;
    globalInfo.requestDate = QDate::currentDate();
    globalInfo.delayInfoAvailable = !objects.result->isHintGiven( ResultObject::NoDelaysForStop );

    // The called function returned, but asynchronous network requests may have been started.
    // Wait for all network requests to finish, because slots in the script may get called
    if ( !waitFor(objects.network.data(), SIGNAL(allRequestsFinished()), WaitForNetwork) ) {
        return;
    }

    // Wait for script execution to finish
    ScriptAgent agent( engine );
    if ( !waitFor(&agent, SIGNAL(scriptFinished()), WaitForScriptFinish) ) {
        return;
    }

    // Update last download URL
    QMutexLocker locker( m_mutex );
    m_lastUrl = objects.network->lastUrl(); // TODO Store all URLs
    m_lastUserUrl = objects.network->lastUserUrl();

    // Inform about script run time
    DEBUG_ENGINE_JOBS( "Script finished in" << (timer.elapsed() / 1000.0)
            << "seconds: " << m_data.provider.scriptFileName() << request()->parseMode() );

    // If data for the current job has already been published, do not emit
    // xxxReady() with an empty resultset
    if ( m_published == 0 || m_objects.result->count() > m_published ) {
        const bool couldNeedForcedUpdate = m_published > 0;
        const MoreItemsRequest *moreItemsRequest =
                dynamic_cast< const MoreItemsRequest* >( request() );
        const AbstractRequest *_request =
                moreItemsRequest ? moreItemsRequest->request().data() : request();
        switch ( _request->parseMode() ) {
        case ParseForDepartures:
            emit departuresReady( m_objects.result->data().mid(m_published),
                    m_objects.result->features(), m_objects.result->hints(),
                    m_objects.network->lastUserUrl(), globalInfo,
                    *dynamic_cast<const DepartureRequest*>(_request),
                    couldNeedForcedUpdate );
            break;
        case ParseForArrivals: {
            emit arrivalsReady( m_objects.result->data().mid(m_published),
                    m_objects.result->features(), m_objects.result->hints(),
                    m_objects.network->lastUserUrl(), globalInfo,
                    *dynamic_cast< const ArrivalRequest* >(_request),
                    couldNeedForcedUpdate );
            break;
        }
        case ParseForJourneysByDepartureTime:
        case ParseForJourneysByArrivalTime:
            emit journeysReady( m_objects.result->data().mid(m_published),
                    m_objects.result->features(), m_objects.result->hints(),
                    m_objects.network->lastUserUrl(), globalInfo,
                    *dynamic_cast<const JourneyRequest*>(_request),
                    couldNeedForcedUpdate );
            break;
        case ParseForStopSuggestions:
            emit stopSuggestionsReady( m_objects.result->data().mid(m_published),
                    m_objects.result->features(), m_objects.result->hints(),
                    m_objects.network->lastUserUrl(), globalInfo,
                    *dynamic_cast<const StopSuggestionRequest*>(_request),
                    couldNeedForcedUpdate );
            break;

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

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

    // Check for exceptions
    if ( m_engine->hasUncaughtException() ) {
        // TODO Get filename where the exception occured, maybe use ScriptAgent for that
        handleError( i18nc("@info/plain", "Error in script function <icode>%1</icode>, "
                            "line %2: <message>%3</message>.",
                            functionName, m_engine->uncaughtExceptionLineNumber(),
                            m_engine->uncaughtException().toString()) );
        return;
    }

    // Cleanup
    m_engine->deleteLater();
    m_engine = 0;
    m_objects.storage->checkLifetime();
    m_objects.clear();
}
Ejemplo n.º 15
0
        // includes for base ecma wrapper classes
         void REcmaFileImporterRegistry::initEcma(QScriptEngine& engine, QScriptValue* proto 
    
    ) 
    
    {

    bool protoCreated = false;
    if(proto == NULL){
        proto = new QScriptValue(engine.newVariant(qVariantFromValue(
                (RFileImporterRegistry*) 0)));
        protoCreated = true;
    }

    

    QScriptValue fun;

    // toString:
    REcmaHelper::registerFunction(&engine, proto, toString, "toString");
    

    // destroy:
    REcmaHelper::registerFunction(&engine, proto, destroy, "destroy");
    

    // get class name
    REcmaHelper::registerFunction(&engine, proto, getClassName, "getClassName");
    

    // conversion to all base classes (multiple inheritance):
    REcmaHelper::registerFunction(&engine, proto, getBaseClasses, "getBaseClasses");
    

    // properties:
    

    // methods:
    
        engine.setDefaultPrototype(
            qMetaTypeId<RFileImporterRegistry*>(), *proto);

        
    

    QScriptValue ctor = engine.newFunction(createEcma, *proto, 2);
    
    // static methods:
    
            REcmaHelper::registerFunction(&engine, &ctor, registerFileImporter, "registerFileImporter");
            
            REcmaHelper::registerFunction(&engine, &ctor, unregisterFileImporter, "unregisterFileImporter");
            
            REcmaHelper::registerFunction(&engine, &ctor, getFileImporter, "getFileImporter");
            
            REcmaHelper::registerFunction(&engine, &ctor, getFilterStrings, "getFilterStrings");
            
            REcmaHelper::registerFunction(&engine, &ctor, hasFileImporter, "hasFileImporter");
            
            REcmaHelper::registerFunction(&engine, &ctor, getFilterExtensions, "getFilterExtensions");
            
            REcmaHelper::registerFunction(&engine, &ctor, getFilterExtensionPatterns, "getFilterExtensionPatterns");
            

    // static properties:
    

    // enum values:
    

    // enum conversions:
    
        
    // init class:
    engine.globalObject().setProperty("RFileImporterRegistry",
    ctor, QScriptValue::SkipInEnumeration);
    
    if( protoCreated ){
       delete proto;
    }
    
    }
Ejemplo n.º 16
0
                 void REcmaDimAlignedData::initEcma(QScriptEngine& engine, QScriptValue* proto 
    
    ) 
    
    {

    bool protoCreated = false;
    if(proto == NULL){
        proto = new QScriptValue(engine.newVariant(qVariantFromValue(
                (RDimAlignedData*) 0)));
        protoCreated = true;
    }

    
        // primary base class RDimLinearData:
        
            QScriptValue dpt = engine.defaultPrototype(
                qMetaTypeId<RDimLinearData*>());

            if (dpt.isValid()) {
                proto->setPrototype(dpt);
            }
          
        /*
        
        */
    

    QScriptValue fun;

    // toString:
    REcmaHelper::registerFunction(&engine, proto, toString, "toString");
    
    // copy:
    REcmaHelper::registerFunction(&engine, proto, copy, "copy");
    

    // destroy:
    REcmaHelper::registerFunction(&engine, proto, destroy, "destroy");
    
        // conversion for base class RDimLinearData
        REcmaHelper::registerFunction(&engine, proto, getRDimLinearData, "getRDimLinearData");
        
        // conversion for base class RDimensionData
        REcmaHelper::registerFunction(&engine, proto, getRDimensionData, "getRDimensionData");
        
        // conversion for base class REntityData
        REcmaHelper::registerFunction(&engine, proto, getREntityData, "getREntityData");
        

    // get class name
    REcmaHelper::registerFunction(&engine, proto, getClassName, "getClassName");
    

    // conversion to all base classes (multiple inheritance):
    REcmaHelper::registerFunction(&engine, proto, getBaseClasses, "getBaseClasses");
    

    // properties:
    

    // methods:
    
            REcmaHelper::registerFunction(&engine, proto, getBoundingBox, "getBoundingBox");
            
            REcmaHelper::registerFunction(&engine, proto, getReferencePoints, "getReferencePoints");
            
            REcmaHelper::registerFunction(&engine, proto, moveReferencePoint, "moveReferencePoint");
            
            REcmaHelper::registerFunction(&engine, proto, recomputeDefinitionPoint, "recomputeDefinitionPoint");
            
            REcmaHelper::registerFunction(&engine, proto, getShapes, "getShapes");
            
            REcmaHelper::registerFunction(&engine, proto, getMeasuredValue, "getMeasuredValue");
            
            REcmaHelper::registerFunction(&engine, proto, getAutoLabel, "getAutoLabel");
            
        engine.setDefaultPrototype(
            qMetaTypeId<RDimAlignedData*>(), *proto);

        
                engine.setDefaultPrototype(qMetaTypeId<
                RDimAlignedData
                > (), *proto);
            
    

    QScriptValue ctor = engine.newFunction(createEcma, *proto, 2);
    
    // static methods:
    

    // static properties:
    

    // enum values:
    

    // enum conversions:
    
        
    // init class:
    engine.globalObject().setProperty("RDimAlignedData",
    ctor, QScriptValue::SkipInEnumeration);
    
    if( protoCreated ){
       delete proto;
    }
    
    }
Ejemplo n.º 17
0
        // includes for base ecma wrapper classes
         void REcmaMathLineEdit::initEcma(QScriptEngine& engine, QScriptValue* proto 
    
    ) 
    
    {

    bool protoCreated = false;
    if(proto == NULL){
        proto = new QScriptValue(engine.newVariant(qVariantFromValue(
                (RMathLineEdit*) 0)));
        protoCreated = true;
    }

    
        // primary base class QLineEdit:
        
            QScriptValue dpt = engine.defaultPrototype(
                qMetaTypeId<QLineEdit*>());

            if (dpt.isValid()) {
                proto->setPrototype(dpt);
            }
          
        /*
        
        */
    

    QScriptValue fun;

    // toString:
    REcmaHelper::registerFunction(&engine, proto, toString, "toString");
    

    // destroy:
    REcmaHelper::registerFunction(&engine, proto, destroy, "destroy");
    
        // conversion for base class QLineEdit
        REcmaHelper::registerFunction(&engine, proto, getQLineEdit, "getQLineEdit");
        

    // get class name
    REcmaHelper::registerFunction(&engine, proto, getClassName, "getClassName");
    

    // conversion to all base classes (multiple inheritance):
    REcmaHelper::registerFunction(&engine, proto, getBaseClasses, "getBaseClasses");
    

    // properties:
    

    // methods:
    
            REcmaHelper::registerFunction(&engine, proto, isAngle, "isAngle");
            
            REcmaHelper::registerFunction(&engine, proto, setAngle, "setAngle");
            
            REcmaHelper::registerFunction(&engine, proto, isInteger, "isInteger");
            
            REcmaHelper::registerFunction(&engine, proto, setInteger, "setInteger");
            
            REcmaHelper::registerFunction(&engine, proto, setValue, "setValue");
            
            REcmaHelper::registerFunction(&engine, proto, getValue, "getValue");
            
            REcmaHelper::registerFunction(&engine, proto, getError, "getError");
            
            REcmaHelper::registerFunction(&engine, proto, clearError, "clearError");
            
            REcmaHelper::registerFunction(&engine, proto, isValid, "isValid");
            
            REcmaHelper::registerFunction(&engine, proto, setToolTip, "setToolTip");
            
            REcmaHelper::registerFunction(&engine, proto, slotTextChanged, "slotTextChanged");
            
            REcmaHelper::registerFunction(&engine, proto, slotTextEdited, "slotTextEdited");
            
        engine.setDefaultPrototype(
            qMetaTypeId<RMathLineEdit*>(), *proto);

        
                        qScriptRegisterMetaType<
                        RMathLineEdit*>(
                        &engine, toScriptValue, fromScriptValue, *proto);
                    
    

    QScriptValue ctor = engine.newFunction(createEcma, *proto, 2);
    
    // static methods:
    

    // static properties:
    

    // enum values:
    

    // enum conversions:
    
        
    // init class:
    engine.globalObject().setProperty("RMathLineEdit",
    ctor, QScriptValue::SkipInEnumeration);
    
    if( protoCreated ){
       delete proto;
    }
    
    }
Ejemplo n.º 18
0
QString QFormScriptRunner::QFormScriptRunnerPrivate::engineError(QScriptEngine &scriptEngine) {
    QScriptValue error = scriptEngine.evaluate(QLatin1String("Error"));
    if (error.isValid())
        return error.toString();
    return QCoreApplication::tr("Unknown error");
}
                 void REcmaDeleteSelectionOperation::initEcma(QScriptEngine& engine, QScriptValue* proto 
    
    ) 
    
    {

    bool protoCreated = false;
    if(proto == NULL){
        proto = new QScriptValue(engine.newVariant(qVariantFromValue(
                (RDeleteSelectionOperation*) 0)));
        protoCreated = true;
    }

    
        // primary base class RClipboardOperation:
        
            QScriptValue dpt = engine.defaultPrototype(
                qMetaTypeId<RClipboardOperation*>());

            if (dpt.isValid()) {
                proto->setPrototype(dpt);
            }
          
        /*
        
        */
    

    QScriptValue fun;

    // toString:
    REcmaHelper::registerFunction(&engine, proto, toString, "toString");
    

    // destroy:
    REcmaHelper::registerFunction(&engine, proto, destroy, "destroy");
    
        // conversion for base class RClipboardOperation
        REcmaHelper::registerFunction(&engine, proto, getRClipboardOperation, "getRClipboardOperation");
        
        // conversion for base class ROperation
        REcmaHelper::registerFunction(&engine, proto, getROperation, "getROperation");
        
        // conversion for base class RRequireHeap
        REcmaHelper::registerFunction(&engine, proto, getRRequireHeap, "getRRequireHeap");
        

    // get class name
    REcmaHelper::registerFunction(&engine, proto, getClassName, "getClassName");
    

    // conversion to all base classes (multiple inheritance):
    REcmaHelper::registerFunction(&engine, proto, getBaseClasses, "getBaseClasses");
    

    // properties:
    

    // methods:
    
            REcmaHelper::registerFunction(&engine, proto, apply, "apply");
            
            REcmaHelper::registerFunction(&engine, proto, preview, "preview");
            
        engine.setDefaultPrototype(
            qMetaTypeId<RDeleteSelectionOperation*>(), *proto);

        
    

    QScriptValue ctor = engine.newFunction(createEcma, *proto, 2);
    
    // static methods:
    

    // static properties:
    

    // enum values:
    

    // enum conversions:
    
        
    // init class:
    engine.globalObject().setProperty("RDeleteSelectionOperation",
    ctor, QScriptValue::SkipInEnumeration);
    
    if( protoCreated ){
       delete proto;
    }
    
    }
Ejemplo n.º 20
0
                 void REcmaRefPoint::initEcma(QScriptEngine& engine, QScriptValue* proto 
    
    ) 
    
    {

    bool protoCreated = false;
    if(proto == NULL){
        proto = new QScriptValue(engine.newVariant(qVariantFromValue(
                (RRefPoint*) 0)));
        protoCreated = true;
    }

    
        // primary base class RVector:
        
            QScriptValue dpt = engine.defaultPrototype(
                qMetaTypeId<RVector*>());

            if (dpt.isValid()) {
                proto->setPrototype(dpt);
            }
          
        /*
        
        */
    

    QScriptValue fun;

    // toString:
    REcmaHelper::registerFunction(&engine, proto, toString, "toString");
    
    // copy:
    REcmaHelper::registerFunction(&engine, proto, copy, "copy");
    

    // destroy:
    REcmaHelper::registerFunction(&engine, proto, destroy, "destroy");
    
        // conversion for base class RVector
        REcmaHelper::registerFunction(&engine, proto, getRVector, "getRVector");
        

    // get class name
    REcmaHelper::registerFunction(&engine, proto, getClassName, "getClassName");
    

    // conversion to all base classes (multiple inheritance):
    REcmaHelper::registerFunction(&engine, proto, getBaseClasses, "getBaseClasses");
    

    // properties:
    

    // methods:
    
            REcmaHelper::registerFunction(&engine, proto, isSecondary, "isSecondary");
            
            REcmaHelper::registerFunction(&engine, proto, setSecondary, "setSecondary");
            
            REcmaHelper::registerFunction(&engine, proto, isIgnore, "isIgnore");
            
            REcmaHelper::registerFunction(&engine, proto, setIgnore, "setIgnore");
            
            REcmaHelper::registerFunction(&engine, proto, isCenter, "isCenter");
            
            REcmaHelper::registerFunction(&engine, proto, setCenter, "setCenter");
            
            REcmaHelper::registerFunction(&engine, proto, isStart, "isStart");
            
            REcmaHelper::registerFunction(&engine, proto, setStart, "setStart");
            
            REcmaHelper::registerFunction(&engine, proto, isEnd, "isEnd");
            
            REcmaHelper::registerFunction(&engine, proto, setEnd, "setEnd");
            
            REcmaHelper::registerFunction(&engine, proto, setFlag, "setFlag");
            
            REcmaHelper::registerFunction(&engine, proto, getFlag, "getFlag");
            
            REcmaHelper::registerFunction(&engine, proto, getFlags, "getFlags");
            
            REcmaHelper::registerFunction(&engine, proto, setFlags, "setFlags");
            
        engine.setDefaultPrototype(
            qMetaTypeId<RRefPoint*>(), *proto);

        
                engine.setDefaultPrototype(qMetaTypeId<
                RRefPoint
                > (), *proto);
            
    

    QScriptValue ctor = engine.newFunction(createEcma, *proto, 2);
    
    // static methods:
    
            REcmaHelper::registerFunction(&engine, &ctor, toVectorList, "toVectorList");
            
            REcmaHelper::registerFunction(&engine, &ctor, toRefPointList, "toRefPointList");
            

    // static properties:
    

    // enum values:
    

    ctor.setProperty("NoFlags",
    QScriptValue(RRefPoint::NoFlags),
    QScriptValue::ReadOnly);


    ctor.setProperty("Secondary",
    QScriptValue(RRefPoint::Secondary),
    QScriptValue::ReadOnly);


    ctor.setProperty("Center",
    QScriptValue(RRefPoint::Center),
    QScriptValue::ReadOnly);


    ctor.setProperty("Ignore",
    QScriptValue(RRefPoint::Ignore),
    QScriptValue::ReadOnly);


    ctor.setProperty("Start",
    QScriptValue(RRefPoint::Start),
    QScriptValue::ReadOnly);


    ctor.setProperty("End",
    QScriptValue(RRefPoint::End),
    QScriptValue::ReadOnly);


    // enum conversions:
    
    qScriptRegisterMetaType<RRefPoint::Flag>(
        &engine,
        toScriptValueEnumFlag,
        fromScriptValueEnumFlag,
        ctor.property(QString::fromLatin1("prototype"))
    );

        
    // init class:
    engine.globalObject().setProperty("RRefPoint",
    ctor, QScriptValue::SkipInEnumeration);
    
    if( protoCreated ){
       delete proto;
    }
    
    }
Ejemplo n.º 21
0
        // includes for base ecma wrapper classes
         void REcmaExplodable::init(QScriptEngine& engine, QScriptValue* proto 
    
    ) 
    
    {

    bool protoCreated = false;
    if(proto == NULL){
        proto = new QScriptValue(engine.newVariant(qVariantFromValue(
                (RExplodable*) 0)));
        protoCreated = true;
    }

    

    QScriptValue fun;

    // toString:
    REcmaHelper::registerFunction(&engine, proto, toString, "toString");
    

    // destroy:
    REcmaHelper::registerFunction(&engine, proto, destroy, "destroy");
    

    // get class name
    REcmaHelper::registerFunction(&engine, proto, getClassName, "getClassName");
    

    // conversion to all base classes (multiple inheritance):
    REcmaHelper::registerFunction(&engine, proto, getBaseClasses, "getBaseClasses");
    

    // properties:
    

    // methods:
    
            REcmaHelper::registerFunction(&engine, proto, getExploded, "getExploded");
            
        engine.setDefaultPrototype(
            qMetaTypeId<RExplodable*>(), *proto);

        
    

    QScriptValue ctor = engine.newFunction(create, *proto, 2);
    
    // static methods:
    

    // static properties:
    

    // enum values:
    

    // enum conversions:
    
        
    // init class:
    engine.globalObject().setProperty("RExplodable",
    ctor, QScriptValue::SkipInEnumeration);
    
    if( protoCreated ){
       delete proto;
    }
    
    }
Ejemplo n.º 22
0
        // includes for base ecma wrapper classes
         void REcmaSharedPointerDirected::initEcma(QScriptEngine& engine, QScriptValue* proto 
    
    ) 
    
    {

    bool protoCreated = false;
    if(proto == NULL){
        proto = new QScriptValue(engine.newVariant(qVariantFromValue(
                (RDirectedPointer*) 0)));
        protoCreated = true;
    }

    

    QScriptValue fun;

    // toString:
    REcmaHelper::registerFunction(&engine, proto, toString, "toString");
    
        // shared pointer support:
        REcmaHelper::registerFunction(&engine, proto, data, "data");
        

        REcmaHelper::registerFunction(&engine, proto, isNull, "isNull");
        

    // destroy:
    REcmaHelper::registerFunction(&engine, proto, destroy, "destroy");
    

    // get class name
    REcmaHelper::registerFunction(&engine, proto, getClassName, "getClassName");
    

    // conversion to all base classes (multiple inheritance):
    REcmaHelper::registerFunction(&engine, proto, getBaseClasses, "getBaseClasses");
    

    // properties:
    

    // methods:
    
            REcmaHelper::registerFunction(&engine, proto, getDirection1, "getDirection1");
            
            REcmaHelper::registerFunction(&engine, proto, getDirection2, "getDirection2");
            
            REcmaHelper::registerFunction(&engine, proto, getSideOfPoint, "getSideOfPoint");
            
            REcmaHelper::registerFunction(&engine, proto, getStartPoint, "getStartPoint");
            
            REcmaHelper::registerFunction(&engine, proto, getEndPoint, "getEndPoint");
            
            REcmaHelper::registerFunction(&engine, proto, getMiddlePoint, "getMiddlePoint");
            
            REcmaHelper::registerFunction(&engine, proto, reverse, "reverse");
            
            REcmaHelper::registerFunction(&engine, proto, trimStartPoint, "trimStartPoint");
            
            REcmaHelper::registerFunction(&engine, proto, trimEndPoint, "trimEndPoint");
            
            REcmaHelper::registerFunction(&engine, proto, getTrimEnd, "getTrimEnd");
            
            REcmaHelper::registerFunction(&engine, proto, getDistanceFromStart, "getDistanceFromStart");
            
        engine.setDefaultPrototype(
            qMetaTypeId<RDirectedPointer>(), *proto);
      
    

    QScriptValue ctor = engine.newFunction(createEcma, *proto, 2);
    
    // static methods:
    

    // static properties:
    

    // enum values:
    

    // enum conversions:
    
        
    // init class:
    engine.globalObject().setProperty("RDirectedPointer",
    ctor, QScriptValue::SkipInEnumeration);
    
    if( protoCreated ){
       delete proto;
    }
    
    }
                 void REcmaSharedPointerAttributeDefinitionData::initEcma(QScriptEngine& engine, QScriptValue* proto 
    
    ) 
    
    {

    bool protoCreated = false;
    if(proto == NULL){
        proto = new QScriptValue(engine.newVariant(qVariantFromValue(
                (RAttributeDefinitionDataPointer*) 0)));
        protoCreated = true;
    }

    
        // primary base class RTextBasedData:
        
            proto->setPrototype(engine.defaultPrototype(
            qMetaTypeId<RTextBasedDataPointer>()));
          
        /*
        
        */
    

    QScriptValue fun;

    // toString:
    REcmaHelper::registerFunction(&engine, proto, toString, "toString");
    
    // copy:
    REcmaHelper::registerFunction(&engine, proto, copy, "copy");
    
        // shared pointer support:
        REcmaHelper::registerFunction(&engine, proto, data, "data");
        

        REcmaHelper::registerFunction(&engine, proto, isNull, "isNull");
        

    // destroy:
    REcmaHelper::registerFunction(&engine, proto, destroy, "destroy");
    
        // conversion for base class RTextBasedData
        REcmaHelper::registerFunction(&engine, proto, getRTextBasedData, "getRTextBasedData");
        
        // conversion for base class REntityData
        REcmaHelper::registerFunction(&engine, proto, getREntityData, "getREntityData");
        
        // conversion for base class RPainterPathSource
        REcmaHelper::registerFunction(&engine, proto, getRPainterPathSource, "getRPainterPathSource");
        

    // get class name
    REcmaHelper::registerFunction(&engine, proto, getClassName, "getClassName");
    

    // conversion to all base classes (multiple inheritance):
    REcmaHelper::registerFunction(&engine, proto, getBaseClasses, "getBaseClasses");
    

    // properties:
    

    // methods:
    
            REcmaHelper::registerFunction(&engine, proto, getTag, "getTag");
            
            REcmaHelper::registerFunction(&engine, proto, setTag, "setTag");
            
            REcmaHelper::registerFunction(&engine, proto, getPrompt, "getPrompt");
            
            REcmaHelper::registerFunction(&engine, proto, setPrompt, "setPrompt");
            
            REcmaHelper::registerFunction(&engine, proto, getRenderedText, "getRenderedText");
            
        engine.setDefaultPrototype(
            qMetaTypeId<RAttributeDefinitionDataPointer>(), *proto);
      
    

    QScriptValue ctor = engine.newFunction(create, *proto, 2);
    
    // static methods:
    

    // static properties:
    

    // enum values:
    

    // enum conversions:
    
        
    // init class:
    engine.globalObject().setProperty("RAttributeDefinitionDataPointer",
    ctor, QScriptValue::SkipInEnumeration);
    
    if( protoCreated ){
       delete proto;
    }
    
    }
Ejemplo n.º 24
0
void PluginFile::Connect(Evaluator *visitor) {
    QScriptEngine *engine = visitor->GetEngine();
    QScriptValue val = engine->newObject();
    QScriptValue objVal = engine->newQObject(val, this);
    engine->globalObject().setProperty("file", objVal);
}
Ejemplo n.º 25
0
        // includes for base ecma wrapper classes
         void REcmaThread::initEcma(QScriptEngine& engine, QScriptValue* proto 
    
    ) 
    
    {

    bool protoCreated = false;
    if(proto == NULL){
        proto = new QScriptValue(engine.newVariant(qVariantFromValue(
                (RThread*) 0)));
        protoCreated = true;
    }

    
        // primary base class QThread:
        
            QScriptValue dpt = engine.defaultPrototype(
                qMetaTypeId<QThread*>());

            if (dpt.isValid()) {
                proto->setPrototype(dpt);
            }
          
        /*
        
        */
    

    QScriptValue fun;

    // toString:
    REcmaHelper::registerFunction(&engine, proto, toString, "toString");
    

    // destroy:
    REcmaHelper::registerFunction(&engine, proto, destroy, "destroy");
    
        // conversion for base class QThread
        REcmaHelper::registerFunction(&engine, proto, getQThread, "getQThread");
        

    // get class name
    REcmaHelper::registerFunction(&engine, proto, getClassName, "getClassName");
    

    // conversion to all base classes (multiple inheritance):
    REcmaHelper::registerFunction(&engine, proto, getBaseClasses, "getBaseClasses");
    

    // properties:
    

    // methods:
    
            REcmaHelper::registerFunction(&engine, proto, start, "start");
            
        engine.setDefaultPrototype(
            qMetaTypeId<RThread*>(), *proto);

        
                        qScriptRegisterMetaType<
                        RThread*>(
                        &engine, toScriptValue, fromScriptValue, *proto);
                    
    

    QScriptValue ctor = engine.newFunction(create, *proto, 2);
    
    // static methods:
    
            REcmaHelper::registerFunction(&engine, &ctor, yieldCurrentThread, "yieldCurrentThread");
            
            REcmaHelper::registerFunction(&engine, &ctor, currentThreadAddress, "currentThreadAddress");
            
            REcmaHelper::registerFunction(&engine, &ctor, currentThreadName, "currentThreadName");
            
            REcmaHelper::registerFunction(&engine, &ctor, currentThread, "currentThread");
            

    // static properties:
    

    // enum values:
    

    // enum conversions:
    
        
    // init class:
    engine.globalObject().setProperty("RThread",
    ctor, QScriptValue::SkipInEnumeration);
    
    if( protoCreated ){
       delete proto;
    }
    
    }
Ejemplo n.º 26
0
ScriptDebugger::ScriptDebugger(const MODELMAP &models, QStandardItemModel *triggerModel) : QDialog(NULL, Qt::Window)
{
	modelMap = models;
	QSignalMapper *signalMapper = new QSignalMapper(this);

	// Add main page
	QWidget *mainWidget = new QWidget(this);
	QVBoxLayout *mainLayout = new QVBoxLayout();
	QHBoxLayout *placementLayout = new QHBoxLayout();
	placementLayout->addWidget(createButton("Add droids", SLOT(droidButtonClicked()), this));
	placementLayout->addWidget(createButton("Add structures", SLOT(structButtonClicked()), this));
	placementLayout->addWidget(createButton("Add features", SLOT(featButtonClicked()), this));
	mainLayout->addLayout(placementLayout);
	QHBoxLayout *miscLayout = new QHBoxLayout();
	miscLayout->addWidget(createButton("Research all", SLOT(researchButtonClicked()), this));
	miscLayout->addWidget(createButton("Show sensors", SLOT(sensorsButtonClicked()), this));
	miscLayout->addWidget(createButton("Shadows", SLOT(shadowButtonClicked()), this));
	miscLayout->addWidget(createButton("Fog", SLOT(fogButtonClicked()), this));
	mainLayout->addLayout(miscLayout);
	QHBoxLayout *worldLayout = new QHBoxLayout();
	worldLayout->addWidget(createButton("Show all", SLOT(deityButtonClicked()), this));
	worldLayout->addWidget(createButton("Weather", SLOT(weatherButtonClicked()), this));
	worldLayout->addWidget(createButton("Reveal mode", SLOT(revealButtonClicked()), this));
	mainLayout->addLayout(worldLayout);
	QHBoxLayout *selectedPlayerLayout = new QHBoxLayout();
	QLabel *selectPlayerLabel = new QLabel("Selected Player:");
	QComboBox *playerComboBox = new QComboBox;
	for (int i = 0; i < game.maxPlayers; i++)
	{
		playerComboBox->addItem(QString::number(i));
	}
	connect(playerComboBox, SIGNAL(activated(int)), this, SLOT(playerButtonClicked(int)));
	selectedPlayerLayout->addWidget(selectPlayerLabel);
	selectedPlayerLayout->addWidget(playerComboBox);
	mainLayout->addLayout(selectedPlayerLayout);
	QHBoxLayout *powerLayout = new QHBoxLayout();
	QLabel *powerLabel = new QLabel("Power:");
	QLineEdit *powerLineEdit = new QLineEdit;
	powerLineEdit->setText(QString::number(getPower(selectedPlayer)));
	connect(powerLineEdit, SIGNAL(textEdited(const QString&)), this, SLOT(powerEditing(const QString&)));
	connect(powerLineEdit, SIGNAL(returnPressed()), this, SLOT(powerEditingFinished()));
	powerLayout->addWidget(powerLabel);
	powerLayout->addWidget(powerLineEdit);
	mainLayout->addLayout(powerLayout);
	mainWidget->setLayout(mainLayout);
	tab.addTab(mainWidget, "Main");

	// Add globals
	for (MODELMAP::const_iterator i = models.constBegin(); i != models.constEnd(); ++i)
	{
		QWidget *dummyWidget = new QWidget(this);
		QScriptEngine *engine = i.key();
		QStandardItemModel *m = i.value();
		m->setParent(this); // take ownership to avoid memory leaks
		QTreeView *view = new QTreeView(this);
		view->setSelectionMode(QAbstractItemView::NoSelection);
		view->setModel(m);
		QString scriptName = engine->globalObject().property("scriptName").toString();
		int player = engine->globalObject().property("me").toInt32();
		QLineEdit *lineEdit = new QLineEdit(this);
		QVBoxLayout *layout = new QVBoxLayout();
		QHBoxLayout *layout2 = new QHBoxLayout();
		QPushButton *updateButton = new QPushButton("Update", this);
		QPushButton *button = new QPushButton("Run", this);
		connect(button, SIGNAL(pressed()), signalMapper, SLOT(map()));
		connect(updateButton, SIGNAL(pressed()), this, SLOT(updateModels()));
		signalMapper->setMapping(button, engine);
		editMap.insert(engine, lineEdit); // store this for slot
		layout->addWidget(view);
		layout2->addWidget(updateButton);
		layout2->addWidget(lineEdit);
		layout2->addWidget(button);
		layout->addLayout(layout2);

		dummyWidget->setLayout(layout);
		tab.addTab(dummyWidget, scriptName + ":" + QString::number(player));
	}
	connect(signalMapper, SIGNAL(mapped(QObject *)), this, SLOT(runClicked(QObject *)));

	// Add triggers
	triggerModel->setParent(this); // take ownership to avoid memory leaks
	triggerView.setModel(triggerModel);
	triggerView.resizeColumnToContents(0);
	triggerView.setSelectionMode(QAbstractItemView::NoSelection);
	triggerView.setSelectionBehavior(QAbstractItemView::SelectRows);
	tab.addTab(&triggerView, "Triggers");

	// Add labels
	labelModel = createLabelModel();
	labelModel->setParent(this); // take ownership to avoid memory leaks
	labelView.setModel(labelModel);
	labelView.resizeColumnToContents(0);
	labelView.setSelectionMode(QAbstractItemView::SingleSelection);
	labelView.setSelectionBehavior(QAbstractItemView::SelectRows);
	connect(&labelView, SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(labelClickedIdx(const QModelIndex &)));
	QPushButton *button = new QPushButton("Show", this);
	connect(button, SIGNAL(pressed()), this, SLOT(labelClicked()));
	QVBoxLayout *labelLayout = new QVBoxLayout(this);
	labelLayout->addWidget(&labelView);
	labelLayout->addWidget(button);
	QWidget *dummyWidget = new QWidget(this);
	dummyWidget->setLayout(labelLayout);
	tab.addTab(dummyWidget, "Labels");

	// Set up dialog
	QHBoxLayout *layout = new QHBoxLayout(this);
	layout->addWidget(&tab);
	setLayout(layout);
	resize(400, 500);
	setSizeGripEnabled(true);
	show();
	raise();
	powerLineEdit->setFocusPolicy(Qt::StrongFocus);
	powerLineEdit->setFocus();
	activateWindow();
}
Ejemplo n.º 27
0
// includes for base ecma wrapper classes
void REcmaSharedPointerObject::init(QScriptEngine& engine, QScriptValue* proto

                                   )

{

    bool protoCreated = false;
    if(proto == NULL) {
        proto = new QScriptValue(engine.newVariant(qVariantFromValue(
                                     (RObjectPointer*) 0)));
        protoCreated = true;
    }



    QScriptValue fun;

    // toString:
    REcmaHelper::registerFunction(&engine, proto, toString, "toString");

    // shared pointer support:
    REcmaHelper::registerFunction(&engine, proto, data, "data");


    REcmaHelper::registerFunction(&engine, proto, isNull, "isNull");


    // destroy:
    REcmaHelper::registerFunction(&engine, proto, destroy, "destroy");


    // get class name
    REcmaHelper::registerFunction(&engine, proto, getClassName, "getClassName");


    // conversion to all base classes (multiple inheritance):
    REcmaHelper::registerFunction(&engine, proto, getBaseClasses, "getBaseClasses");


    // properties:


    // methods:

    REcmaHelper::registerFunction(&engine, proto, clone, "clone");

    REcmaHelper::registerFunction(&engine, proto, getDocument, "getDocument");

    REcmaHelper::registerFunction(&engine, proto, setDocument, "setDocument");

    REcmaHelper::registerFunction(&engine, proto, getId, "getId");

    REcmaHelper::registerFunction(&engine, proto, getHandle, "getHandle");

    REcmaHelper::registerFunction(&engine, proto, isUndone, "isUndone");

    REcmaHelper::registerFunction(&engine, proto, setUndone, "setUndone");

    REcmaHelper::registerFunction(&engine, proto, getPropertyTypeIds, "getPropertyTypeIds");

    REcmaHelper::registerFunction(&engine, proto, getProperty, "getProperty");

    REcmaHelper::registerFunction(&engine, proto, setProperty, "setProperty");

    REcmaHelper::registerFunction(&engine, proto, hasPropertyType, "hasPropertyType");

    REcmaHelper::registerFunction(&engine, proto, isSelectedForPropertyEditing, "isSelectedForPropertyEditing");

    REcmaHelper::registerFunction(&engine, proto, getCustomProperty, "getCustomProperty");

    REcmaHelper::registerFunction(&engine, proto, setCustomProperty, "setCustomProperty");

    REcmaHelper::registerFunction(&engine, proto, removeCustomProperty, "removeCustomProperty");

    REcmaHelper::registerFunction(&engine, proto, getCustomPropertyKeys, "getCustomPropertyKeys");

    REcmaHelper::registerFunction(&engine, proto, getComplexity, "getComplexity");

    engine.setDefaultPrototype(
        qMetaTypeId<RObjectPointer>(), *proto);



    QScriptValue ctor = engine.newFunction(create, *proto, 2);

    // static methods:

    REcmaHelper::registerFunction(&engine, &ctor, init, "init");


    // static properties:

    ctor.setProperty("INVALID_ID",
                     qScriptValueFromValue(&engine, RObject::INVALID_ID),
                     QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);

    ctor.setProperty("INVALID_HANDLE",
                     qScriptValueFromValue(&engine, RObject::INVALID_HANDLE),
                     QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);

    ctor.setProperty("PropertyCustom",
                     qScriptValueFromValue(&engine, RObject::PropertyCustom),
                     QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);

    ctor.setProperty("PropertyHandle",
                     qScriptValueFromValue(&engine, RObject::PropertyHandle),
                     QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);


    // enum values:


    ctor.setProperty("X",
                     QScriptValue(RObject::X),
                     QScriptValue::ReadOnly);


    ctor.setProperty("Y",
                     QScriptValue(RObject::Y),
                     QScriptValue::ReadOnly);


    ctor.setProperty("Z",
                     QScriptValue(RObject::Z),
                     QScriptValue::ReadOnly);


    // enum conversions:

    qScriptRegisterMetaType<RObject::XYZ>(
        &engine,
        toScriptValueEnumXYZ,
        fromScriptValueEnumXYZ,
        ctor.property(QString::fromLatin1("prototype"))
    );


    // init class:
    engine.globalObject().setProperty("RObjectPointer",
                                      ctor, QScriptValue::SkipInEnumeration);

    if( protoCreated ) {
        delete proto;
    }

}
Ejemplo n.º 28
0
void tst_QScriptString::test()
{
    QScriptEngine eng;
    {
        QScriptString str;
        QVERIFY(!str.isValid());
        QVERIFY(str == str);
        QVERIFY(!(str != str));
        QVERIFY(str.toString().isNull());

        QScriptString str1(str);
        QVERIFY(!str1.isValid());

        QScriptString str2 = str;
        QVERIFY(!str2.isValid());

        QCOMPARE(str.toArrayIndex(), quint32(0xffffffff));
    }
    for (int x = 0; x < 2; ++x) {
        QString ciao = QString::fromLatin1("ciao");
        QScriptString str = eng.toStringHandle(ciao);
        QVERIFY(str.isValid());
        QVERIFY(str == str);
        QVERIFY(!(str != str));
        QCOMPARE(str.toString(), ciao);

        QScriptString str1(str);
        QCOMPARE(str, str1);

        QScriptString str2 = str;
        QCOMPARE(str, str2);

        QScriptString str3 = eng.toStringHandle(ciao);
        QVERIFY(str3.isValid());
        QCOMPARE(str, str3);

        eng.collectGarbage();

        QVERIFY(str.isValid());
        QCOMPARE(str.toString(), ciao);
        QVERIFY(str1.isValid());
        QCOMPARE(str1.toString(), ciao);
        QVERIFY(str2.isValid());
        QCOMPARE(str2.toString(), ciao);
        QVERIFY(str3.isValid());
        QCOMPARE(str3.toString(), ciao);
    }
    {
        QScriptEngine* eng2 = new QScriptEngine;
        QString one = QString::fromLatin1("one");
        QString two = QString::fromLatin1("two");
        QScriptString oneInterned = eng2->toStringHandle(one);
        QCOMPARE(oneInterned.toString(), one);
        QScriptString twoInterned = eng2->toStringHandle(two);
        QCOMPARE(twoInterned.toString(), two);
        QVERIFY(oneInterned != twoInterned);
        QVERIFY(!(oneInterned == twoInterned));

        delete eng2;
    }
}
Ejemplo n.º 29
0
void tst_QScriptClass::extension()
{
    QScriptEngine eng;
    {
        TestClass cls(&eng);
        cls.setCallableMode(TestClass::NotCallable);
        QVERIFY(!cls.supportsExtension(QScriptClass::Callable));
        QVERIFY(!cls.supportsExtension(QScriptClass::HasInstance));
    }
    // Callable
    {
        TestClass cls(&eng);
        cls.setCallableMode(TestClass::CallableReturnsSum);
        QVERIFY(cls.supportsExtension(QScriptClass::Callable));

        QScriptValue obj = eng.newObject(&cls);
        obj.setProperty("one", QScriptValue(&eng, 1));
        obj.setProperty("two", QScriptValue(&eng, 2));
        obj.setProperty("three", QScriptValue(&eng, 3));
        {
            QScriptValueList args;
            args << QScriptValue(&eng, 4) << QScriptValue(&eng, 5);
            QScriptValue ret = obj.call(obj, args);
            QCOMPARE(ret.toNumber(), qsreal(15));
        }

        cls.setCallableMode(TestClass::CallableReturnsArgument);
        {
            QScriptValue ret = obj.call(obj, QScriptValueList() << 123);
            QVERIFY(ret.isNumber());
            QCOMPARE(ret.toInt32(), 123);
        }
        {
            QScriptValue ret = obj.call(obj, QScriptValueList() << true);
            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());
        }

        cls.setCallableMode(TestClass::CallableReturnsInvalidVariant);
        {
            QScriptValue ret = obj.call(obj);
            QVERIFY(ret.isUndefined());
        }
    }
    // 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);
        {
            QScriptValue ret = eng.evaluate("hasInstanceValue instanceof HasInstanceTester");
            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());
        }
    }
}
Ejemplo n.º 30
0
void OwnCloudService::checkAppInfo(QNetworkReply *reply) {
    QString data = QString(reply->readAll());
    // qDebug() << data;

    // we have to add [], so the string can be parsed as JSON
    data = QString("[") + data + QString("]");

    QScriptEngine engine;
    QScriptValue result = engine.evaluate(data);

    bool appIsValid = result.property(0).property("versioning").toBool();
    QString appVersion = result.property(0).property("app_version").toString();
    QString serverVersion = result.property(0).property(
            "server_version").toString();

    // reset to "unknown" in case we can't test if versions
    // and trash app are enabled
    settingsDialog->setOKLabelData(6, "unknown", SettingsDialog::Unknown);
    settingsDialog->setOKLabelData(7, "unknown", SettingsDialog::Unknown);

    if (serverVersion != "") {
        VersionNumber serverAppVersion = VersionNumber(appVersion);
        VersionNumber minAppVersion = VersionNumber(QOWNNOTESAPI_MIN_VERSION);

        if (minAppVersion > serverAppVersion) {
            settingsDialog->setOKLabelData(4,
                                           "version " + appVersion + " too low",
                                           SettingsDialog::Warning);
        } else {
            settingsDialog->setOKLabelData(4, "ok", SettingsDialog::OK);
        }

        // check if versions and trash app are enabled after QOwnNotesAPI v0.3.1
        if (serverAppVersion >= VersionNumber("0.3.1")) {
            bool versionsAppEnabled = result.property(0).property(
                    "versions_app").toBool();
            bool trashAppEnabled = result.property(0).property(
                    "trash_app").toBool();

            if (versionsAppEnabled) {
                settingsDialog->setOKLabelData(6, "ok", SettingsDialog::OK);
            } else {
                settingsDialog->setOKLabelData(6, "not enabled",
                                               SettingsDialog::Failure);
            }

            if (trashAppEnabled) {
                settingsDialog->setOKLabelData(7, "ok", SettingsDialog::OK);
            } else {
                settingsDialog->setOKLabelData(7, "not enabled",
                                               SettingsDialog::Failure);
            }
        }

        // check if notes path was found after QOwnNotesAPI v0.4.1
        if (serverAppVersion >= VersionNumber("0.4.1")) {
            bool notesPathExists = result.property(0).property(
                    "notes_path_exists").toBool();

            if (notesPathExists) {
                settingsDialog->setOKLabelData(8, "ok", SettingsDialog::OK);
            } else {
                settingsDialog->setOKLabelData(8, "not found",
                                               SettingsDialog::Failure);
            }
        }
    } else {
        settingsDialog->setOKLabelData(4, "not connected",
                                       SettingsDialog::Failure);
    }

    // call callback in settings dialog
    settingsDialog->connectTestCallback(appIsValid, appVersion, serverVersion,
                                        reply->errorString());
}