Files
Mu/localTester/LocalTester/testexecutionenviroment.cpp

69 lines
1.9 KiB
C++
Raw Normal View History

2018-05-22 11:15:59 -07:00
#include <QJSEngine>
#include <QJSValue>
2018-05-22 11:15:59 -07:00
#include <QString>
2018-05-23 17:57:14 -07:00
#include <thread>
#include <chrono>
2018-05-22 11:15:59 -07:00
#include <stdint.h>
#include "testexecutionenviroment.h"
TestExecutionEnviroment::TestExecutionEnviroment(){
2018-05-23 17:57:14 -07:00
jsRunning = false;
errorFilePath = "";
2018-05-23 17:57:14 -07:00
lastProgramReturnValue = "";
2018-05-22 11:15:59 -07:00
engine = new QJSEngine();
}
TestExecutionEnviroment::~TestExecutionEnviroment(){
finish();
2018-05-22 11:15:59 -07:00
engine->collectGarbage();
delete engine;//deleting the engine frees all QObject classes passed to it automaticly
2018-05-23 17:57:14 -07:00
}
void TestExecutionEnviroment::jsThreadFunction(QString program, QString args, bool callMain){
if(callMain){
QJSValue jsGlobal = engine->globalObject();
jsGlobal.setProperty("__programArgs", QJSValue(args));
engine->evaluate(program, errorFilePath);
lastProgramReturnValue = engine->evaluate("main(__programArgs);", errorFilePath).toString();
2018-05-23 17:57:14 -07:00
}
else{
engine->evaluate(program, errorFilePath);
2018-05-23 17:57:14 -07:00
}
jsRunning = false;
2018-05-22 11:15:59 -07:00
}
void TestExecutionEnviroment::setErrorPath(QString path){
errorFilePath = path;
}
2018-05-22 11:15:59 -07:00
void TestExecutionEnviroment::clearExecutionEnviroment(){
finish();
2018-05-22 11:15:59 -07:00
engine->collectGarbage();
delete engine;//deleting the engine frees all QObject classes passed to it automaticly
engine = new QJSEngine();
}
2018-05-23 17:57:14 -07:00
void TestExecutionEnviroment::installClass(QString name, QObject* jsClass){
2018-05-22 11:15:59 -07:00
QJSValue jsGlobal = engine->globalObject();
2018-05-23 17:57:14 -07:00
jsGlobal.setProperty(name, engine->newQObject(jsClass));
2018-05-22 11:15:59 -07:00
}
2018-05-23 17:57:14 -07:00
void TestExecutionEnviroment::execute(QString program, QString args, bool callMain){
if(!jsRunning){
jsRunning = true;
jsThread = std::thread(&TestExecutionEnviroment::jsThreadFunction, this, program, args, callMain);
}
2018-05-22 11:15:59 -07:00
}
2018-05-23 17:57:14 -07:00
QString TestExecutionEnviroment::finish(){
while(jsRunning)
std::this_thread::sleep_for(std::chrono::milliseconds(1));
if(jsThread.joinable())
jsThread.join();
return lastProgramReturnValue;
2018-05-22 11:15:59 -07:00
}