Example #1
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    MagicCore SomeMagicCoreClass;

    QScriptEngine scriptEngine;

    QScriptValue scriptMagicCore = scriptEngine.newQObject (&SomeMagicCoreClass);
    Q_ASSERT (scriptMagicCore.isQObject());

    scriptEngine.globalObject().setProperty("Core", scriptMagicCore);

    ReadScriptsFromPath(QDir("./scripts/objects/"), scriptEngine);
    ReadScriptsFromPath(QDir("./scripts/levels/"), scriptEngine);

    char szLine[256];
    strcpy(szLine, "");

    std::cout << std::endl << "Entering scripting console: " << std::endl;

    while (strcmp(szLine, "exit") != 0)
    {
        // evaluate script line and store return value
        QScriptValue retVal = scriptEngine.evaluate(szLine);

        if (retVal.isUndefined() == false)
            std::cout << "ScriptEngine returns: " << retVal.toString().toStdString() << std::endl;

        // read line
        strcpy(szLine, "");
        std::cin.getline(szLine, 256);
    }


   /* QScriptValue object = scriptEngine.globalObject().property("testObject");
    Q_ASSERT(object.isValid());

    QScriptValue SlotMethod = object.property("ExampleSlot1");
    Q_ASSERT(SlotMethod.isFunction());

    bool bOk = qScriptConnect(&SomeMagicCoreClass, SIGNAL(TestSignal()), object, SlotMethod);
    Q_ASSERT(bOk);


    QScriptValue object2 = scriptEngine.globalObject().property("testObject2");
    Q_ASSERT(object2.isValid());

    QScriptValue SlotMethod2 = object2.property("ExampleSlot2");
    Q_ASSERT(SlotMethod2.isFunction());

    bool bOk2 = qScriptConnect(&SomeMagicCoreClass, SIGNAL(TestSignal()), object2, SlotMethod2);
    Q_ASSERT(bOk2);

    SomeMagicCoreClass.TriggerSignal();*/

    return 0;
    /*a.exit(0);

    return a.exec();*/
}
Example #2
0
QScriptValue PHIBaseItem::on( const QString &name, const QScriptValue &v )
{
    if ( !isClientItem() ) return self();
    PHIEventHash hash=data( DEventFunctions ).value<PHIEventHash>();
    hash.insert( name, v );
    qDebug() << "on" << name << v.toString();
    switch ( PHIDomEvent::stringToEventType( name ) ) {
    case PHIDomEvent::EMouseMove:
    case PHIDomEvent::EMouseOut:
    case PHIDomEvent::EMouseOver: _flags |= FHasHoverEventHandler; break;
    case PHIDomEvent::EClick:
    case PHIDomEvent::EDblClick:
    case PHIDomEvent::EMouseDown:
    case PHIDomEvent::EMouseUp: _flags |= FHasMouseEventHandler; break;
    case PHIDomEvent::EKeyDown:
    case PHIDomEvent::EKeyPress:
    case PHIDomEvent::EKeyUp: _flags |= FHasKeyEventHandler; break;
    case PHIDomEvent::EBlur:
    case PHIDomEvent::EFocus: _flags |= FHasFocusEventHandler; break;
    case PHIDomEvent::EChange: _flags |= FHasChangeEventHandler; break;
    case PHIDomEvent::EDrop: _flags |= FHasDropEventHandler; break;
    default:;
    }
    setData( DEventFunctions, qVariantFromValue( hash ) );
    return self();
}
void QScriptDebuggerScriptedConsoleCommandJob::start()
{
    Q_D(QScriptDebuggerScriptedConsoleCommandJob);
    QScriptEngine *engine = d->command->globalObject.engine();
    engine->setGlobalObject(d->command->globalObject);
    QScriptValueList args;
    for (int i = 0; i < d->arguments.size(); ++i)
        args.append(QScriptValue(engine, d->arguments.at(i)));
    QScriptDebuggerConsoleGlobalObject *global;
    global = qobject_cast<QScriptDebuggerConsoleGlobalObject*>(engine->globalObject().toQObject());
    Q_ASSERT(global != 0);
    global->setScheduler(this);
    global->setResponseHandler(this);
    global->setMessageHandler(d->messageHandler);
    global->setConsole(d->console);
    d->commandCount = 0;
    QScriptValue ret = d->command->execFunction.call(QScriptValue(), args);
    global->setScheduler(0);
    global->setResponseHandler(0);
    global->setMessageHandler(0);
    global->setConsole(0);
    if (ret.isError()) {
        qWarning("*** internal error: %s", qPrintable(ret.toString()));
    }
    if (d->commandCount == 0)
        finish();
}
Example #4
0
QAction *KWin::AbstractScript::scriptValueToAction(QScriptValue &value, QMenu *parent)
{
    QScriptValue titleValue = value.property("text");
    QScriptValue checkableValue = value.property("checkable");
    QScriptValue checkedValue = value.property("checked");
    QScriptValue itemsValue = value.property("items");
    QScriptValue triggeredValue = value.property("triggered");

    if (!titleValue.isValid()) {
        // title not specified - does not make any sense to include
        return NULL;
    }
    const QString title = titleValue.toString();
    const bool checkable = checkableValue.isValid() && checkableValue.toBool();
    const bool checked = checkable && checkedValue.isValid() && checkedValue.toBool();
    // either a menu or a menu item
    if (itemsValue.isValid()) {
        if (!itemsValue.isArray()) {
            // not an array, so cannot be a menu
            return NULL;
        }
        QScriptValue lengthValue = itemsValue.property("length");
        if (!lengthValue.isValid() || !lengthValue.isNumber() || lengthValue.toInteger() == 0) {
            // length property missing
            return NULL;
        }
        return createMenu(title, itemsValue, parent);
    } else if (triggeredValue.isValid()) {
        // normal item
        return createAction(title, checkable, checked, triggeredValue, parent);
    }
    return NULL;
}
void tst_QScriptContext::thisObject()
{
    QScriptEngine eng;

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

    {
        QScriptValue result = eng.evaluate("get_thisObject()");
        QCOMPARE(result.isObject(), true);
        QCOMPARE(result.toString(), QString("[object global]"));
    }

    {
        QScriptValue result = eng.evaluate("get_thisObject.apply(new Number(123))");
        QCOMPARE(result.isObject(), true);
        QCOMPARE(result.toNumber(), 123.0);
    }

    {
        QScriptValue obj = eng.newObject();
        eng.currentContext()->setThisObject(obj);
        QVERIFY(eng.currentContext()->thisObject().equals(obj));
        eng.currentContext()->setThisObject(QScriptValue());
        QVERIFY(eng.currentContext()->thisObject().equals(obj));

        QScriptEngine eng2;
        QScriptValue obj2 = eng2.newObject();
        QTest::ignoreMessage(QtWarningMsg, "QScriptContext::setThisObject() failed: cannot set an object created in a different engine");
        eng.currentContext()->setThisObject(obj2);
    }
}
Example #6
0
// Currently breaks the lint test, so use with care
static QScriptValue js_include(QScriptContext *context, QScriptEngine *engine)
{
	QString path = context->argument(0).toString();
	UDWORD size;
	char *bytes = NULL;
	if (!loadFile(path.toAscii().constData(), &bytes, &size))
	{
		debug(LOG_ERROR, "Failed to read include file \"%s\"", path.toAscii().constData());
		return false;
	}
	QString source = QString::fromAscii(bytes, size);
	free(bytes);
	QScriptSyntaxCheckResult syntax = QScriptEngine::checkSyntax(source);
	if (syntax.state() != QScriptSyntaxCheckResult::Valid)
	{
		debug(LOG_ERROR, "Syntax error in include %s line %d: %s", 
		      path.toAscii().constData(), syntax.errorLineNumber(), syntax.errorMessage().toAscii().constData());
		return false;
	}
	context->setActivationObject(engine->globalObject());
	context->setThisObject(engine->globalObject());
	QScriptValue result = engine->evaluate(source, path);
	if (engine->hasUncaughtException())
	{
		int line = engine->uncaughtExceptionLineNumber();
		debug(LOG_ERROR, "Uncaught exception at line %d, include file %s: %s",
		      line, path.toAscii().constData(), result.toString().toAscii().constData());
		return false;
	}
	return QScriptValue();
}
/*!
  The agent calls this function when an uncaught exception has
  occurred.
*/
void QScriptDebuggerBackendPrivate::exception(qint64 scriptId,
                                              const QScriptValue &exception,
                                              bool hasHandler)
{
    Q_Q(QScriptDebuggerBackend);
    if (ignoreExceptions) {
        // don't care (it's caught by us)
        return;
    }
    QScriptDebuggerEvent e(QScriptDebuggerEvent::Exception);
    e.setScriptId(scriptId);
    e.setFileName(agent->scriptData(scriptId).fileName());
    e.setMessage(exception.toString());
    e.setHasExceptionHandler(hasHandler);
    int lineNumber = -1;
    QString fileName;
    if (exception.property(QLatin1String("lineNumber")).isNumber())
        lineNumber = exception.property(QLatin1String("lineNumber")).toInt32();
    if (exception.property(QLatin1String("fileName")).isString())
        fileName = exception.property(QLatin1String("fileName")).toString();
    if (lineNumber == -1) {
        QScriptContextInfo info(q->engine()->currentContext());
        lineNumber = info.lineNumber();
        fileName = info.fileName();
    }
    if (lineNumber != -1)
        e.setLineNumber(lineNumber);
    if (!fileName.isEmpty())
        e.setFileName(fileName);
    QScriptDebuggerValue value(exception);
    e.setScriptValue(value);
    q->event(e);
}
Example #8
0
QString KateTemplateScript::invoke(KateView* view, const QString& functionName, const QString &srcText) {

  if(!setView(view))
    return QString();

  clearExceptions();
  QScriptValue myFunction = function(functionName);
  if(!myFunction.isValid()) {
    return QString();
  }

  QScriptValueList arguments;
  arguments << QScriptValue(m_engine, srcText);

  QScriptValue result = myFunction.call(QScriptValue(), arguments);
  
  if(m_engine->hasUncaughtException()) {
    displayBacktrace(result, "Error while calling helper function");
    return QString();
  }
 
  
  if (result.isNull()) {
    return QString();
  }

  return result.toString();
}
Example #9
0
QString ScriptManagerPrivate::engineError(const QScriptEnginePtr &scriptEngine)
{
    QScriptValue error = scriptEngine->evaluate(QLatin1String("Error"));
    if (error.isValid())
        return error.toString();
    return ScriptManager::tr("Unknown error");
}
Example #10
0
void ScriptablePrivate::loadScript(const QString& oName)
{
  qDebug() << "Looking for a script " << oName;
  XSqlQuery scriptq;
  scriptq.prepare("SELECT script_source, script_order"
            "  FROM script"
            " WHERE((script_name=:script_name)"
            "   AND (script_enabled))"
            " ORDER BY script_order;");
  scriptq.bindValue(":script_name", oName);
  scriptq.exec();
  while(scriptq.next())
  {
    if(engine())
    {
      QString script = scriptHandleIncludes(scriptq.value("script_source").toString());
      QScriptValue result = _engine->evaluate(script, _parent->objectName());
      if (_engine->hasUncaughtException())
      {
        int line = _engine->uncaughtExceptionLineNumber();
        qDebug() << "uncaught exception at line" << line << ":" << result.toString();
      }
    }
    else
      qDebug() << "could not initialize engine";
  }
}
Example #11
0
QVariant CBDS::getSettingsFromScript(const QString &filename)
{
    QFile f(filename);
    if (f.open(QIODevice::ReadOnly))
    {
        QString appcode(f.readAll());
        f.close();
        QScriptSyntaxCheckResult res = m_engine.checkSyntax(appcode);
        if (res.state() != QScriptSyntaxCheckResult::Valid)
        {
            emit error(QString("SyntaxCheck Failed: Line: %1 Column: %2: %3").arg(res.errorLineNumber()).arg(res.errorColumnNumber()).arg(res.errorMessage()));
            return QVariant();
        }

        QScriptContext *ctx = m_engine.pushContext();
        CBJSObject js;
        CBObjectBase cbo(&m_engine, m_roomowner);
        ctx->activationObject().setProperty("cb", m_engine.newQObject(&cbo));
        ctx->activationObject().setProperty("cbjs", m_engine.newQObject(&js));
        QScriptValue ret = m_engine.evaluate(appcode, QFileInfo(filename).fileName());
        if (ret.isError())
        {
            emit error(ret.toString());
            m_engine.popContext();
            return QVariant();
        }

        m_engine.popContext();
        return cbo.getSettingsChoices().toVariant();
    }
    emit error("Can't open file: " + filename);
    return QVariant();
}
Example #12
0
    PT convert_script_value_f_point<PT>::operator()( QScriptEngine *,
						  const QScriptValue & args ) const
    {
	typedef typename point_valtype<PT>::value_type value_type;
	value_type x = 0;
	value_type y = 0;
	QScriptValue obj;
	bool smellArray = (args.isArray() || ! args.property("length").isUndefined());
	if( smellArray )
	{
	    if(0) qDebug() << "Looks like arguments array.";
	    obj = args.property(0);
	}
	else if( args.isObject() )
	{
	    if(0) qDebug() << "Looks like an object.";
	    obj = args;
	}

	if( smellArray && !obj.isObject() )
	{
	    if(0) qDebug() << "Trying arguments array.";
	    x = value_type(args.property(0).toNumber());
	    y = value_type(args.property(1).toNumber());
	}
	else
	{
	    if(0) qDebug() << "Trying object x/y:" << obj.toString() << ":" << toSource( obj );
	    if(0) qDebug() << "obj.property(x).toNumber():"<<obj.property("x").toNumber();
	    x = value_type(obj.property("x").toNumber());
	    y = value_type(obj.property("y").toNumber());
	}
	if(0) qDebug() << "PT:"<<PT(x,y);
	return PT(x,y);
    }
Example #13
0
    QString to_source_f<QScriptValue>::operator()( QScriptValue const & x ) const
    {
	if( x.isUndefined() ) return "undefined";
	if( x.isNull() ) return "null";
	if(0) qDebug() << "to_source_f<QScriptValue>("<<x.toString()<<")";

#define TODO(A,B,C)
#define DO(IS,T,TO) \
	if( x.IS() ) {\
	    if(0) qDebug() << "to_source_f<QScriptValue>(is-a: "<<# IS<<")"; \
	    return toSource<T>( x.TO() );\
	}


	DO(isVariant,QVariant,toVariant); // must come before the others!
	DO(isBoolean,bool,toBoolean);
	DO(isNumber,qreal,toNumber);
	DO(isString,QString,toString);
	TODO(isRegExp,QRegExp,toRegExp);
	if( x.isArray() || x.isObject() )
	{
	    if(0) qDebug() << "to_source_f<QScriptValue>(is-a: array or object)";
	    return to_source_f_object()( x );
	}

#undef DO
#undef TODO
	return QString("undefined");
    }
Example #14
0
    void RexQtScriptModule::Initialize()
    {
        LogInfo("Module " + Name() + " initializing...");
		
		//XXX hack to have a ref to framework for api funcs
		RexQtScript::staticframework = framework_;

		QScriptValue res = engine.evaluate("1 + 1;");
		LogInfo("Javascript thinks 1 + 1 = " + res.toString().toStdString());

		engine.globalObject().setProperty("print", engine.newFunction(RexQtScript::Print));
		engine.globalObject().setProperty("loadUI", engine.newFunction(RexQtScript::LoadUI));

		engine.evaluate("print('Hello from qtscript');");

		char* js = "print('hello from ui loader & handler script!');"
			"ui = loadUI('dialog.ui');"
			"print(ui);"
			"function changed(v) {"
			"	print('val changed to: ' + v);"
			"}"
			"print(ui.doubleSpinBox.valueChanged);"
			"ui.doubleSpinBox['valueChanged(double)'].connect(changed);"
			"print('connecting to doubleSpinBox.valueChanged ok from js (?)');";
 
		engine.evaluate(QString::fromAscii(js));
	}
Example #15
0
    QScriptValue CsvHelperWrapper::Generate(const QScriptValue& List, QScriptValue Separator)
    {
        QStringList a1 = List.toVariant().toStringList();
        QChar a2 = Separator.toString()[0];
        return QScriptValue(Helper->Generate(a1,a2));

    }
Example #16
0
void HttpServer :: readClient()
{
  if (disabled) return;
  QTcpSocket *socket = (QTcpSocket*)sender();
  if( socket->canReadLine()) {

    QString request = socket->readLine();
    QStringList tokens = request.split(QRegExp("[ \r\n][ \r\n]*"));

    if( tokens[0] == "GET") {
      d->engine.globalObject().setProperty("token", tokens[1]);      
      QScriptValue reply = d->engine.evaluate("reply(token)");
      
      QTextStream os(socket);
      os.setAutoDetectUnicode(true);
      os << reply.toString().toUtf8();
      
      socket->close();
      
      QtServiceBase::instance()->logMessage("Wrote index.html");
      
      if(socket->state() == QTcpSocket::UnconnectedState) {
        delete socket;
        QtServiceBase::instance()->logMessage("Conncetion closed");
        
      }
    }
  }
}
Example #17
0
static QString safeValueToString(const QScriptValue &value)
{
    if (value.isObject())
        return QLatin1String("[object Object]");
    else
        return value.toString();
}
Example #18
0
int main(int argc, char **argv)
{
	Q_INIT_RESOURCE(table);
	
    QApplication app(argc, argv);
    QScriptEngine engine;

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

    QUiLoader loader;
    QFile uiFile(":/table.ui");
    uiFile.open(QIODevice::ReadOnly);
    QWidget *ui = loader.load(&uiFile);
    uiFile.close();

    QScriptValue func = engine.evaluate("Table");
    QScriptValue scriptUi = engine.newQObject(ui);
    QScriptValue table = func.construct(QScriptValueList() << scriptUi);
    if(engine.hasUncaughtException()) {
    	QScriptValue value = engine.uncaughtException();
    	QString lineNumber = QString("\nLine Number:%1\n").arg(engine.uncaughtExceptionLineNumber());
    	QStringList btList = engine.uncaughtExceptionBacktrace();
    	QString trace;
    	for(short i=0; i<btList.size(); ++i)
    		trace += btList.at(i);
    	QMessageBox::information(NULL, QObject::tr("Exception"), value.toString() + lineNumber + trace );
    }

    ui->show();
    return app.exec();
}
Example #19
0
static void interactive(QScriptEngine *eng)
{
    QScriptValue global = eng->globalObject();
    if (!global.property(QLatin1String("dir")).isValid())
        global.setProperty(QLatin1String("dir"), eng->newFunction(qtscript_dir));
    if (!global.property(QLatin1String("load")).isValid())
        global.setProperty(QLatin1String("load"), eng->newFunction(qtscript_load));
    if (!global.property(QLatin1String("quit")).isValid())
        global.setProperty(QLatin1String("quit"), eng->newFunction(qtscript_quit));
    if (!global.property(QLatin1String("syncdb")).isValid())
        global.setProperty(QLatin1String("syncdb"), eng->newFunction(qtscript_syncdb));
    wantsToQuit = false;

    QTextStream qin(stdin, QIODevice::ReadOnly);

    const char *qscript_prompt = "qdjango> ";
    const char *dot_prompt = ".... ";
    const char *prompt = qscript_prompt;

    QString code;

    printf("Commands:\n"
           "\tdir(obj) : print the object's properties\n"
           "\tload()   : loads a QtScript extension\n"
           "\tquit()   : exits console\n"
           "\tsyncdb() : creates database tables\n");

    forever {
        QString line;

        printf("%s", prompt);
        fflush(stdout);

        line = qin.readLine();
        if (line.isNull())
            break;

        code += line;
        code += QLatin1Char('\n');

        if (line.trimmed().isEmpty()) {
            continue;

        } else if (! eng->canEvaluate(code)) {
            prompt = dot_prompt;

        } else {
            QScriptValue result = eng->evaluate(code, QLatin1String("typein"));

            code.clear();
            prompt = qscript_prompt;

            if (! result.isUndefined())
                fprintf(stderr, "%s\n", qPrintable(result.toString()));

            if (wantsToQuit)
                break;
        }
    }
}
Example #20
0
SkinContext::SkinContext(UserSettingsPointer pConfig,
                         const QString& xmlPath)
        : m_xmlPath(xmlPath),
          m_pConfig(pConfig),
          m_pScriptEngine(new QScriptEngine()),
          m_pScriptDebugger(new QScriptEngineDebugger()),
          m_pSvgCache(new QHash<QString, QDomElement>()),
          m_pSingletons(new SingletonMap()) {
    enableDebugger(true);
    // the extensions are imported once and will be passed to the children
    // global object as properties of the parent's global object.
    importScriptExtension("console");
    importScriptExtension("svg");
    m_pScriptEngine->installTranslatorFunctions();

    // Retrieving hooks pattern from script extension
    QScriptValue global = m_pScriptEngine->globalObject();
    QScriptValue svg = global.property("svg");
    QScriptValue hooksPattern = svg.property("getHooksPattern").call(svg);
    if (!hooksPattern.isNull()) {
        m_hookRx.setPattern(hooksPattern.toString());
    }

    m_scaleFactor = 1.0;
}
void QDeclarativeExpressionPrivate::exceptionToError(QScriptEngine *scriptEngine, 
                                            QDeclarativeError &error)
{
    if (scriptEngine->hasUncaughtException() && 
        scriptEngine->uncaughtException().isError()) {

        QString fileName;
        int lineNumber = scriptEngine->uncaughtExceptionLineNumber();

        QScriptValue exception = scriptEngine->uncaughtException();
        QLatin1String fileNameProp("fileName");

        if (!exception.property(fileNameProp).toString().isEmpty()){
            fileName = exception.property(fileNameProp).toString();
        } else {
            fileName = QLatin1String("<Unknown File>");
        }

        error.setUrl(QUrl(fileName));
        error.setLine(lineNumber);
        error.setColumn(-1);
        error.setDescription(exception.toString());
    } else {
        error = QDeclarativeError();
    }
}
Example #22
0
QScriptValue SkinContext::importScriptExtension(const QString& extensionName) {
    QScriptValue out = m_pScriptEngine->importExtension(extensionName);
    if (m_pScriptEngine->hasUncaughtException()) {
        qDebug() << out.toString();
    }
    return out;
}
void tst_QScriptContext::callee()
{
    QScriptEngine eng;

    {
        QScriptValue fun = eng.newFunction(get_callee);
        fun.setProperty("foo", QScriptValue(&eng, "bar"));
        eng.globalObject().setProperty("get_callee", fun);

        QScriptValue result = eng.evaluate("get_callee()");
        QCOMPARE(result.isFunction(), true);
        QCOMPARE(result.property("foo").toString(), QString("bar"));
    }

    // callee when toPrimitive() is called internally
    {
        QScriptValue fun = eng.newFunction(store_callee_and_return_primitive);
        QScriptValue obj = eng.newObject();
        obj.setProperty("toString", fun);
        QVERIFY(!obj.property("callee").isValid());
        (void)obj.toString();
        QVERIFY(obj.property("callee").isFunction());
        QVERIFY(obj.property("callee").strictlyEquals(fun));

        obj.setProperty("callee", QScriptValue());
        QVERIFY(!obj.property("callee").isValid());
        obj.setProperty("valueOf", fun);
        (void)obj.toNumber();
        QVERIFY(obj.property("callee").isFunction());
        QVERIFY(obj.property("callee").strictlyEquals(fun));
    }
}
Example #24
0
void ExposedModel::updateElement(const QString &key, QScriptValue value)
{
    tinia::model::StateSchemaElement schemaElement = m_model->getStateSchemaElement(key.toStdString());
    std::string type = schemaElement.getXSDType();

    if(type.find("xsd:") != std::string::npos) {
        type = type.substr(4);
    }


    if (type == std::string("double")) {
        m_model->updateElement(key.toStdString(), double(value.toNumber()));
    }
    else if(type==std::string("integer"))  {
        m_model->updateElement(key.toStdString(), int(value.toNumber()));
    }
    else if(type==std::string("bool")) {
        m_model->updateElement(key.toStdString(), value.toBool());
    }
    else if(type==std::string("string")) {
        m_model->updateElement(key.toStdString(), value.toString().toStdString());
    }
    else if(type==std::string("complexType")) {
        m_model->updateElement(key.toStdString(), static_cast<Viewer*>(value.toQObject())->viewer());
    }

}
QScriptDebuggerValue::QScriptDebuggerValue(const QScriptValue &value)
    : d_ptr(0)
{
    if (value.isValid()) {
        d_ptr.reset(new QScriptDebuggerValuePrivate);
        if (value.isUndefined())
            d_ptr->type = UndefinedValue;
        else if (value.isNull())
            d_ptr->type = NullValue;
        else if (value.isNumber()) {
            d_ptr->type = NumberValue;
            d_ptr->numberValue = value.toNumber();
        } else if (value.isBoolean()) {
            d_ptr->type = BooleanValue;
            d_ptr->booleanValue = value.toBoolean();
        } else if (value.isString()) {
            d_ptr->type = StringValue;
            d_ptr->stringValue = new QString(value.toString());
        } else {
            Q_ASSERT(value.isObject());
            d_ptr->type = ObjectValue;
            d_ptr->objectId = value.objectId();
        }
        d_ptr->ref.ref();
    }
}
Example #26
0
    QDateTime ActionInstance::evaluateDateTime(bool &ok, const QString &parameterName, const QString &subParameterName)
    {
        if(!ok)
            return QDateTime();

        const SubParameter &subParameter = retreiveSubParameter(parameterName, subParameterName);
        QString result;

        if(subParameter.isCode())
        {
            QScriptValue evaluationResult = evaluateCode(ok, subParameter);
            if(evaluationResult.isDate())
                return evaluationResult.toDateTime();

            result = evaluationResult.toString();
        }
        else
            result = evaluateText(ok, subParameter);

        if(!ok)
            return QDateTime();

		QDateTime dateTime = QDateTime::fromString(result, QStringLiteral("dd/MM/yyyy hh:mm:ss"));

        if(!dateTime.isValid())
        {
            ok = false;

            return QDateTime();
        }

        return dateTime;
    }
Example #27
0
static QScriptValue DEFINE_CUSTOM_OBJECT(QScriptContext *context, QScriptEngine *engine)
{
   QScriptValue a = context->argument(0);
   QScriptValue b = context->argument(1);
   QScriptValue c = context->argument(2);

   scriptType_t v;

   v.desc = a.toString();
   v.name = b.toString();
   v.guiType = c.toInt32();

   scriptNewTypes.append(v);

   return QScriptValue();
}
Example #28
0
void netease_encrypt::initializeContext()
{
  m_engine = new QScriptEngine();

  QString PATH = QDir::currentPath(); 

  QString PATH2 = QCoreApplication::applicationDirPath(); 

  // 改为相对路径
  m_file_name = PATH2 + "/" + "netease.js";
  //m_file_name = "E:/projects/myproject/autobots/autobots/netease_encrypt/netease_encrypt/netease_encrypt.js";

  QFile scriptFile(m_file_name);  
  //m_file_name = scriptFile.fileName();
  if (!scriptFile.open(QIODevice::ReadOnly))
  {
    QMessageBox::critical(0, "js file error", QStringLiteral("js脚本文件错误")+m_file_name);
    return ;
  }
  QTextStream stream(&scriptFile);  
  m_js_content = stream.readAll();  
  scriptFile.close();  

  QScriptValue result = m_engine->evaluate(m_js_content, m_file_name);

  if(result.isError()) {//解析js文件是否有错误  
    QMessageBox::critical(0, "Hello Script",  
      QString::fromLatin1("%0:%1: %2")  
      .arg(m_file_name)//文件名  
      .arg(result.property("lineNumber").toInt32())//错误行号  
      .arg(result.toString()));//错误信息  
    return ;  
  }  
}
void QScriptDebuggerScriptedConsoleCommandJob::handleResponse(
    const QScriptDebuggerResponse &response,
    int commandId)
{
    Q_D(QScriptDebuggerScriptedConsoleCommandJob);
    // ### generalize
    QScriptEngine *engine = d->command->globalObject.engine();
    engine->setGlobalObject(d->command->globalObject);
    QScriptValueList args;
    args.append(engine->toScriptValue(response));
    args.append(QScriptValue(engine, commandId));
    QScriptDebuggerConsoleGlobalObject *global;
    global = qobject_cast<QScriptDebuggerConsoleGlobalObject*>(d->command->globalObject.toQObject());
    Q_ASSERT(global != 0);
    global->setScheduler(this);
    global->setResponseHandler(this);
    global->setMessageHandler(d->messageHandler);
    global->setConsole(d->console);
    d->commandCount = 0;
    QScriptValue ret = d->command->responseFunction.call(QScriptValue(), args);
    global->setScheduler(0);
    global->setResponseHandler(0);
    global->setMessageHandler(0);
    global->setConsole(0);
    if (ret.isError()) {
        qWarning("*** internal error: %s", qPrintable(ret.toString()));
    }
    if (d->commandCount == 0)
        finish();
}
Example #30
0
void ScriptEngine::importProgram(const QScriptProgram &program, const QScriptValue &scope,
                               QScriptValue &targetObject)
{
    QSet<QString> globalPropertyNames;
    {
        QScriptValueIterator it(globalObject());
        while (it.hasNext()) {
            it.next();
            globalPropertyNames += it.name();
        }
    }

    pushContext();
    if (scope.isObject())
        currentContext()->pushScope(scope);
    QScriptValue result = evaluate(program);
    QScriptValue activationObject = currentContext()->activationObject();
    if (scope.isObject())
        currentContext()->popScope();
    popContext();
    if (Q_UNLIKELY(hasErrorOrException(result)))
        throw ErrorInfo(tr("Error when importing '%1': %2").arg(program.fileName(), result.toString()));

    // If targetObject is already an object, it doesn't get overwritten but enhanced by the
    // contents of the .js file.
    // This is necessary for library imports that consist of multiple js files.
    if (!targetObject.isObject())
        targetObject = newObject();

    // Copy every property of the activation object to the target object.
    // We do not just save a reference to the activation object, because QScriptEngine contains
    // special magic for activation objects that leads to unanticipated results.
    {
        QScriptValueIterator it(activationObject);
        while (it.hasNext()) {
            it.next();
            if (debugJSImports)
                qDebug() << "[ENGINE] Copying property " << it.name();
            targetObject.setProperty(it.name(), it.value());
        }
    }

    // Copy new global properties to the target object and remove them from
    // the global object. This is to support direct variable assignments
    // without the 'var' keyword in JavaScript files.
    QScriptValueIterator it(globalObject());
    while (it.hasNext()) {
        it.next();
        if (globalPropertyNames.contains(it.name()))
            continue;

        if (debugJSImports) {
            qDebug() << "[ENGINE] inserting global property "
                     << it.name() << " " << it.value().toString();
        }

        targetObject.setProperty(it.name(), it.value());
        it.remove();
    }
}