Esempio n. 1
0
bool ProgramScriptAction::check(const QString &xmlFile, const TypeRule *rule,
                                SymFactory *factory)
{
    Q_UNUSED(rule);
    Q_UNUSED(factory);

    // Delete old program
    if (_program) {
        delete _program;
        _program = 0;
    }

    QScriptSyntaxCheckResult result =
            QScriptEngine::checkSyntax(_srcCode);
    if (result.state() != QScriptSyntaxCheckResult::Valid) {
        typeRuleError2(xmlFile,
                       srcLine() + result.errorLineNumber() - 1,
                       result.errorColumnNumber(),
                       QString("Syntax error: %1")
                            .arg(result.errorMessage()));
    }
    else {
        // Wrap the code into a function so that the return statement
        // is available to the code
        QString code = QString("function %1() {\n%2\n}")
                .arg(js::inlinefunc).arg(_srcCode);
        _program = new QScriptProgram(code, xmlFile, srcLine() - 1);
    }

    return true;
}
Esempio n. 2
0
bool Terminal::execFile(QString filePath) {
    if(!Utils::isExtension(filePath, QString("js"))) {
        std::cout << "File Invalid..."
                  << std::endl
                  << "Acceptable extension *.js";
        return false;
    }

    QString script = Utils::getContent(filePath);

    if(script.isEmpty()) { return false; }

    QScriptSyntaxCheckResult result = this->m_engine->checkSyntax(script);

    if(result.state() == QScriptSyntaxCheckResult::Error) {
        QString error("Error on line %1 column %2\nMessage: %3");
        error = error.arg(QString::number(result.errorLineNumber()),
                          QString::number(result.errorColumnNumber()),
                          result.errorMessage());

        std::cout << error.toAscii().constData() << std::endl;
        return false;
    }

    Jsws *jsws = new Jsws(this->m_engine, script,parent());
    QScriptValue value = this->m_engine->newQObject(jsws);
    this->m_engine->globalObject().setProperty("WS", value);
    this->m_engine->evaluate(script);
    return true;
}
Esempio n. 3
0
bool FuncCallScriptAction::check(const QString &xmlFile, const TypeRule *rule,
                                 SymFactory *factory)
{
    Q_UNUSED(rule);
    Q_UNUSED(factory);

    // Delete old program
    if (_program) {
        delete _program;
        _program = 0;
    }

    // Read the contents of the script file
    QFile scriptFile(_scriptFile);
    if (!scriptFile.open(QFile::ReadOnly))
        ioError(QString("Error opening file \"%1\" for reading.")
                    .arg(_scriptFile));
    _program = new QScriptProgram(scriptFile.readAll(), _scriptFile);

    // Basic syntax check
    QScriptSyntaxCheckResult result =
            QScriptEngine::checkSyntax(_program->sourceCode());
    if (result.state() != QScriptSyntaxCheckResult::Valid) {
        typeRuleError2(xmlFile, srcLine(), -1,
                       QString("Syntax error in file %1 line %2 column %3: %4")
                               .arg(ShellUtil::shortFileName(_scriptFile))
                               .arg(result.errorLineNumber())
                               .arg(result.errorColumnNumber())
                               .arg(result.errorMessage()));
    }
    // Check if the function exists
    ScriptEngine eng(0);
    ScriptEngine::FuncExistsResult ret =
            eng.functionExists(_function, *_program);
    if (ret == ScriptEngine::feRuntimeError) {
        QString err;
        if (eng.hasUncaughtException()) {
            err = QString("Uncaught exception at line %0: %1")
                    .arg(eng.uncaughtExceptionLineNumber())
                    .arg(eng.lastError());
            QStringList bt = eng.uncaughtExceptionBacktrace();
            for (int i = 0; i < bt.size(); ++i)
                err += "\n    " + bt[i];
        }
        else
            err = eng.lastError();
        typeRuleError2(xmlFile, srcLine(), -1,
                       QString("Runtime error in file %1: %2")
                               .arg(ShellUtil::shortFileName(_scriptFile))
                               .arg(err));
    }
    else if (ret == ScriptEngine::feDoesNotExist) {
        typeRuleError2(xmlFile, srcLine(), -1,
                       QString("Function \"%1\" is not defined in file \"%2\".")
                               .arg(_function)
                               .arg(ShellUtil::shortFileName(_scriptFile)));
    }

    return true;
}
Esempio n. 4
0
Script::Script(QString script)
{
    setObjectName(metaObject()->className());
    
    addOutputPort("ERROR");

    //From http://www.qtcentre.org/threads/10425-QtScript-newFunction-won-t-work
        
    QScriptValue that = scriptEngine.newQObject(this, QScriptEngine::QtOwnership, QScriptEngine::ExcludeChildObjects
		| QScriptEngine::ExcludeSuperClassMethods | QScriptEngine::ExcludeSuperClassProperties);
    scriptEngine.globalObject().setProperty("self",that);
    //Log in console
    scriptEngine.evaluate("function echo(str){self.scriptEcho(str);};");
    //Add input 
    scriptEngine.evaluate("function addInputPort(str){self.scriptAddInputPort(str);};");
    //Add output
    scriptEngine.evaluate("function addOutputPort(str){self.scriptAddOutputPort(str);};");
    //Set self starting
    scriptEngine.evaluate("function setSelfStarting(str){self.scriptSetSelfStarting(str);};");
    //Receive
    scriptEngine.evaluate("function receive(str){return self.scriptReceive(str);};");
    //Send
    scriptEngine.evaluate("function send(str, val){self.scriptSend(str, val);};");
    //Read file
    scriptEngine.evaluate("function readFile(str){return self.scriptReadFile(str);};");
    
    //------------------------------------------------------------------
    // EVALUATE THE SCRIPT 
    //------------------------------------------------------------------
    QScriptSyntaxCheckResult check = scriptEngine.checkSyntax(script);
    if(check.state() != QScriptSyntaxCheckResult::Valid)
    {
        std::cerr << QString("Error in script line %1, column %2: %3")
                .arg(check.errorLineNumber())
                .arg(check.errorColumnNumber())
                .arg(check.errorMessage())
                .toStdString() << std::endl;
    }
    else if(!scriptEngine.canEvaluate(script))
    {
        std::cerr << QString("Can't evaluate script: unknown error.")
                .toStdString() << std::endl;
    }
    else
    {        
        scriptEngine.evaluate(script);
        scriptEngine.evaluate("init()");
    }
}
Esempio n. 5
0
QScriptValue EntityTreeRenderer::loadEntityScript(EntityItem* entity) {
    if (!entity) {
        return QScriptValue(); // no entity...
    }
    
    EntityItemID entityID = entity->getEntityItemID();
    if (_entityScripts.contains(entityID)) {
        EntityScriptDetails details = _entityScripts[entityID];
        
        // check to make sure our script text hasn't changed on us since we last loaded it
        if (details.scriptText == entity->getScript()) {
            return details.scriptObject; // previously loaded
        }
        
        // if we got here, then we previously loaded a script, but the entity's script value
        // has changed and so we need to reload it.
        _entityScripts.remove(entityID);
    }
    if (entity->getScript().isEmpty()) {
        return QScriptValue(); // no script
    }
    
    QString scriptContents = loadScriptContents(entity->getScript());
    
    QScriptSyntaxCheckResult syntaxCheck = QScriptEngine::checkSyntax(scriptContents);
    if (syntaxCheck.state() != QScriptSyntaxCheckResult::Valid) {
        qDebug() << "EntityTreeRenderer::loadEntityScript() entity:" << entityID;
        qDebug() << "   " << syntaxCheck.errorMessage() << ":"
                          << syntaxCheck.errorLineNumber() << syntaxCheck.errorColumnNumber();
        qDebug() << "    SCRIPT:" << entity->getScript();
        return QScriptValue(); // invalid script
    }
    
    QScriptValue entityScriptConstructor = _entitiesScriptEngine->evaluate(scriptContents);
    
    if (!entityScriptConstructor.isFunction()) {
        qDebug() << "EntityTreeRenderer::loadEntityScript() entity:" << entityID;
        qDebug() << "    NOT CONSTRUCTOR";
        qDebug() << "    SCRIPT:" << entity->getScript();
        return QScriptValue(); // invalid script
    }

    QScriptValue entityScriptObject = entityScriptConstructor.construct();
    EntityScriptDetails newDetails = { entity->getScript(), entityScriptObject };
    _entityScripts[entityID] = newDetails;

    return entityScriptObject; // newly constructed
}
void DroneshareUploadDialog::vehicleQueryComplete(const QString &jsonResponse)
{
    QLOG_DEBUG() << "droneshare: Vehicle Query Complete"/* << jsonResponse*/;

    QScriptSyntaxCheckResult syntaxCheck = QScriptEngine::checkSyntax(jsonResponse);
    QScriptEngine engine;
    QScriptValue result = engine.evaluate("("+jsonResponse+")");

    if (engine.hasUncaughtException()){
        QLOG_ERROR() << "Error evaluating version object";
        QLOG_ERROR() << "Error @line#" << engine.uncaughtExceptionLineNumber();
        QLOG_ERROR() << "Backtrace:" << engine.uncaughtExceptionBacktrace();
        QLOG_ERROR() << "Syntax Check:" << syntaxCheck.errorMessage();
        QLOG_ERROR() << "Syntax Check line:" << syntaxCheck.errorLineNumber()
                     << " col:" << syntaxCheck.errorColumnNumber();
        return;
    }
    ui->statusLabel->setText("Vehicle Query Complete.");
    QMap<QString,QString> vehicleList;

    QScriptValue entries = result.property("vehicles");
    QScriptValueIterator it(entries);
    while (it.hasNext()){
        it.next();
        QScriptValue entry = it.value();
        QString uuid = entry.property("uuid").toString();
        QString name = entry.property("name").toString();
        vehicleList.insert(name,uuid);
    }

    bool ok = false;
    QString item = QInputDialog::getItem(this, tr("Vehicle Selection"),tr("vehicle"),vehicleList.keys(),1,
                                                          false, &ok, Qt::Dialog, Qt::ImhNone);
    if (ok){
        startLogUpload(vehicleList.value(item));
    }

    m_droneshareQuery->deleteLater();
    m_droneshareQuery = NULL;
}
Esempio n. 7
0
bool ScriptManager::AddScript(QString script, QString name) {
    if(name == "") {
        Logger::Get().Error("Cannot add script without name.");
        return false;
    }

    if(HasScript(name)) {
        Logger::Get().Error("Cannot add script \"" + name + "\": a script with this name already exists.");
        return false;
    }

    // check the syntax
    QScriptSyntaxCheckResult syntax = mScriptEngine->checkSyntax(script);
    if(syntax.state() != QScriptSyntaxCheckResult::Valid) {
        Logger::Get().Error("Syntax error in script \"" + name + "\" at line "
                            + Utils::ToString(syntax.errorLineNumber()) + " column "
                            + Utils::ToString(syntax.errorColumnNumber()) + ":");
        Logger::Get().Error("    " +  syntax.errorMessage());
    } else {
        Logger::Get().Debug("Adding script \"" + name + "\".");
        mScripts[name] = QScriptProgram(script, name);
    }
    return true;
}
void DroneshareUploadDialog::uploadComplete(const QString& jsonResponse)
{
    QLOG_DEBUG() << "droneshare: upload success: " << jsonResponse;
    m_droneshareUpload->deleteLater();
    m_droneshareUpload = NULL;

    QScriptSyntaxCheckResult syntaxCheck = QScriptEngine::checkSyntax(jsonResponse);
    QScriptEngine engine;
    QScriptValue result = engine.evaluate("("+jsonResponse+")");

    if (engine.hasUncaughtException()){
        QLOG_ERROR() << "Error evaluating version object";
        QLOG_ERROR() << "Error @line#" << engine.uncaughtExceptionLineNumber();
        QLOG_ERROR() << "Backtrace:" << engine.uncaughtExceptionBacktrace();
        QLOG_ERROR() << "Syntax Check:" << syntaxCheck.errorMessage();
        QLOG_ERROR() << "Syntax Check line:" << syntaxCheck.errorLineNumber()
                     << " col:" << syntaxCheck.errorColumnNumber();
        return;
    }

    QString viewURL = result.property(0).property("viewURL").toString();
    ui->statusLabel->setOpenExternalLinks(true);
    ui->statusLabel->setText(tr("<html><head/><body><p>Upload Suceeded!<br><a href=\"%1\"><span style=\" text-decoration: underline; color:#0000ff;\">Click to view on Droneshare</span></a></p></body></html>").arg(viewURL));
}
void DroneshareUploadDialog::uploadFailed(const QString& jsonResponse, const QString& errorString)
{
    QLOG_DEBUG() << "droneshare: upload failed: " << errorString
                    << "JSON response:" << jsonResponse;
    m_droneshareUpload->deleteLater();
    m_droneshareUpload = NULL;

    QScriptSyntaxCheckResult syntaxCheck = QScriptEngine::checkSyntax(jsonResponse);
    QScriptEngine engine;
    QScriptValue result = engine.evaluate("("+jsonResponse+")");

    if (engine.hasUncaughtException()){
        QLOG_ERROR() << "Error evaluating version object";
        QLOG_ERROR() << "Error @line#" << engine.uncaughtExceptionLineNumber();
        QLOG_ERROR() << "Backtrace:" << engine.uncaughtExceptionBacktrace();
        QLOG_ERROR() << "Syntax Check:" << syntaxCheck.errorMessage();
        QLOG_ERROR() << "Syntax Check line:" << syntaxCheck.errorLineNumber()
                     << " col:" << syntaxCheck.errorColumnNumber();
        return;
    }

    QString message = result.property("message").toString();
    ui->statusLabel->setText(tr("Upload Failed!\n%1").arg(message));
}
Esempio n. 10
0
QScriptValue EntityTreeRenderer::loadEntityScript(EntityItem* entity) {
    if (!entity) {
        return QScriptValue(); // no entity...
    }

    // NOTE: we keep local variables for the entityID and the script because
    // below in loadScriptContents() it's possible for us to execute the
    // application event loop, which may cause our entity to be deleted on
    // us. We don't really need access the entity after this point, can
    // can accomplish all we need to here with just the script "text" and the ID.
    EntityItemID entityID = entity->getEntityItemID();
    QString entityScript = entity->getScript();

    if (_entityScripts.contains(entityID)) {
        EntityScriptDetails details = _entityScripts[entityID];

        // check to make sure our script text hasn't changed on us since we last loaded it
        if (details.scriptText == entityScript) {
            return details.scriptObject; // previously loaded
        }

        // if we got here, then we previously loaded a script, but the entity's script value
        // has changed and so we need to reload it.
        _entityScripts.remove(entityID);
    }
    if (entityScript.isEmpty()) {
        return QScriptValue(); // no script
    }

    bool isURL = false; // loadScriptContents() will tell us if this is a URL or just text.
    QString scriptContents = loadScriptContents(entityScript, isURL);

    QScriptSyntaxCheckResult syntaxCheck = QScriptEngine::checkSyntax(scriptContents);
    if (syntaxCheck.state() != QScriptSyntaxCheckResult::Valid) {
        qDebug() << "EntityTreeRenderer::loadEntityScript() entity:" << entityID;
        qDebug() << "   " << syntaxCheck.errorMessage() << ":"
                 << syntaxCheck.errorLineNumber() << syntaxCheck.errorColumnNumber();
        qDebug() << "    SCRIPT:" << entityScript;
        return QScriptValue(); // invalid script
    }

    if (isURL) {
        _entitiesScriptEngine->setParentURL(entity->getScript());
    }
    QScriptValue entityScriptConstructor = _sandboxScriptEngine->evaluate(scriptContents);

    if (!entityScriptConstructor.isFunction()) {
        qDebug() << "EntityTreeRenderer::loadEntityScript() entity:" << entityID;
        qDebug() << "    NOT CONSTRUCTOR";
        qDebug() << "    SCRIPT:" << entityScript;
        return QScriptValue(); // invalid script
    } else {
        entityScriptConstructor = _entitiesScriptEngine->evaluate(scriptContents);
    }

    QScriptValue entityScriptObject = entityScriptConstructor.construct();
    EntityScriptDetails newDetails = { entityScript, entityScriptObject };
    _entityScripts[entityID] = newDetails;

    if (isURL) {
        _entitiesScriptEngine->setParentURL("");
    }

    return entityScriptObject; // newly constructed
}
Esempio n. 11
0
void ScriptingAsset::load()
{
    if( !isLoaded() )
    {
        QFile script( file().toLocalFile() );
        if( script.open( QIODevice::ReadOnly ) )
        {
            d->script = script.readAll();
            mimeData()->setText( d->script );
        }
        // Don't attempt to do anything if the script is empty
        if( d->script.isEmpty() )
            return;

        QScriptSyntaxCheckResult result = ScriptingEngine::instance()->registerAsset( this );
        if( result.state() != QScriptSyntaxCheckResult::Valid )
        {
            debug( tr( "Script error %1 (%2,%3): %4" ).arg( fullyQualifiedName() ).arg( result.errorLineNumber() ).arg( result.errorColumnNumber() ).arg( result.errorMessage() ) );
        }
        else
        {
            Asset::load();
        }
    }
}
Esempio n. 12
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();
}
Esempio n. 13
0
void ScriptRunner::tests()
{
    QFile file(m_testScriptFileName);

    if (m_doExit) return;

    TestFunctionResult *tf = m_resultLogger->getTestFunctionResult("initTestCase");
    if (!tf)
        tf = m_resultLogger->createTestFunctionResult("initTestCase");

    if(file.open(QIODevice::ReadOnly)) {
        QString scriptContent = file.readAll();

        if (scriptContent.length() <= 0) {
            tf->addError("Can't evaluate empty script from file: '" + m_testScriptFileName +"'");
            stop();
            return;
        }

        QScriptSyntaxCheckResult result = QScriptEngine::checkSyntax(scriptContent);
        if (result.state() != QScriptSyntaxCheckResult::Valid)
        {
            QString err = "Can't evaluate script content from file. Check syntax of script on file: '" + m_testScriptFileName +"'"
                       + " Error: " + result.errorMessage()
                       + " line: " + result.errorLineNumber()
                       + " column: " + result.errorColumnNumber();
            tf->addError(err);
            stop();
            return;
        }
        if (m_doExit) return;

        QScriptValue val = m_engine->evaluate(scriptContent, m_testScriptFileName);
        if(m_engine->hasUncaughtException()) {
            QString err = "Can't evaluate script content from file. Check syntax of script on file: '" + m_testScriptFileName + "'"
                       + " Error: " + m_engine->uncaughtExceptionBacktrace().join(" ")
                       + " at line " + m_engine->uncaughtExceptionLineNumber();
            tf->addError(err);
            stop();
            return;
        }
    }
    else {
        stop();
        tf->addError("Failed to read script from file '" + m_testScriptFileName +"'");
        return;
    }

    if (m_doExit) return;

    QScriptValue ctor = m_engine->evaluate("Tests");
    QScriptValue script = m_engine->newQObject(this, QScriptEngine::QtOwnership);
    QScriptValue scripttests = ctor.construct(QScriptValueList() << script);
    if(m_engine->hasUncaughtException()) {
        QString err = "Can't evaluate script content from file. Check syntax of script on file: '" + m_testScriptFileName +"'"
                 + " Error: " + m_engine->uncaughtExceptionBacktrace().join(" ");
        tf->addError(err);
        stop();
        return;
    }
}