Beispiel #1
0
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

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

    QTextEdit editor;
    QTimer timer;
    QScriptValue constructor = engine.evaluate("Object");
    QScriptValueList arguments;
    arguments << engine.newQObject(&timer);
    arguments << engine.newQObject(&editor);
    QScriptValue object = constructor.construct(arguments);
    if (engine.hasUncaughtException()) {
        qDebug() << engine.uncaughtException().toString();
    }

    editor.show();
    timer.start(1000);

    return app.exec();
}
Beispiel #2
0
int main(int argc, char *argv[])
{
    Q_INIT_RESOURCE(tetrix);

//! [1]
    QApplication app(argc, argv);
    QScriptEngine engine;

    QScriptValue Qt = engine.newQMetaObject(QtMetaObject::get());
    Qt.setProperty("App", engine.newQObject(&app));
    engine.globalObject().setProperty("Qt", Qt);
//! [1]

#ifndef QT_NO_SCRIPTTOOLS
    QScriptEngineDebugger debugger;
    debugger.attachTo(&engine);
    QMainWindow *debugWindow = debugger.standardWindow();
    debugWindow->resize(1024, 640);
#endif

//! [2]
    evaluateFile(engine, ":/tetrixpiece.js");
    evaluateFile(engine, ":/tetrixboard.js");
    evaluateFile(engine, ":/tetrixwindow.js");
//! [2]

//! [3]
    TetrixUiLoader loader;
    QFile uiFile(":/tetrixwindow.ui");
    uiFile.open(QIODevice::ReadOnly);
    QWidget *ui = loader.load(&uiFile);
    uiFile.close();

    QScriptValue ctor = engine.evaluate("TetrixWindow");
    QScriptValue scriptUi = engine.newQObject(ui, QScriptEngine::ScriptOwnership);
    QScriptValue tetrix = ctor.construct(QScriptValueList() << scriptUi);
//! [3]

    QPushButton *debugButton = qFindChild<QPushButton*>(ui, "debugButton");
#ifndef QT_NO_SCRIPTTOOLS
    QObject::connect(debugButton, SIGNAL(clicked()),
                     debugger.action(QScriptEngineDebugger::InterruptAction),
                     SIGNAL(triggered()));
    QObject::connect(debugButton, SIGNAL(clicked()),
                     debugWindow, SLOT(show()));
#else
    debugButton->hide();
#endif

//! [4]
    ui->resize(550, 370);
    ui->show();

    qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
    return app.exec();
//! [4]
}
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<GyroSensorInterface>::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));
	}

	for (const auto &step : mCustomInitSteps) {
		step(engine);
	}

	evalSystemJs(engine);

	engine->setProcessEventsInterval(1);
	return engine;
}
Beispiel #4
0
void QFormScriptRunner::QFormScriptRunnerPrivate::initializeEngine(QWidget *w, const WidgetList &children, QScriptEngine &scriptEngine) {
    // Populate the script variables. This pushes a context which must be popped.
    QScriptContext *ctx = scriptEngine.pushContext();
    QScriptValue widgetObject =  scriptEngine.newQObject(w);
    QScriptValue childrenArray = scriptEngine.newArray (children.size());

    for(int i = 0; i < children.size(); i++) {
        childrenArray.setProperty(i, scriptEngine.newQObject(children[i]));
    }

    const QFormBuilderStrings &strings = QFormBuilderStrings::instance();
    ctx ->activationObject().setProperty(strings.scriptWidgetVariable, widgetObject);
    ctx ->activationObject().setProperty(strings.scriptChildWidgetsVariable, childrenArray);
}
Beispiel #5
0
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QDeclarativeView view;
    QDeclarativeContext *context = view.rootContext();
    context->setContextProperty("backgroundColor",
                                QColor(Qt::yellow));

    KDeclarative kdeclarative;
    kdeclarative.setDeclarativeEngine(view.engine());
    kdeclarative.initialize();
    //binds things like kconfig and icons
    kdeclarative.setupBindings();

    //If all gone well, the QScriptEngine has been extracted
    QScriptEngine *scriptEngine = kdeclarative.scriptEngine();
    Q_ASSERT(scriptEngine);

    //Bind a test QObject in the "QtScript way"
    QScriptValue global = scriptEngine->globalObject();
    TestObject *testObject = new TestObject();
    QScriptValue testValue = scriptEngine->newQObject(testObject);
    testValue.setScope(global);
    global.setProperty("testObject", testValue);

    view.setSource(QUrl::fromLocalFile("test.qml"));
    view.show();

    return app.exec();
}
Beispiel #6
0
 void addObject(QObject* object, const QString& name = QString()) {
     Q_ASSERT( m_engine );
     Q_ASSERT( ! m_engine->hasUncaughtException() );
     QScriptValue global = m_engine->globalObject();
     QScriptValue value = m_engine->newQObject(object, QScriptEngine::AutoOwnership);
     global.setProperty(name.isEmpty() ? object->objectName() : name, value);
 }
void tst_QScriptContext::qobjectAsActivationObject()
{
    QScriptEngine eng;
    QObject object;
    QScriptValue scriptObject = eng.newQObject(&object);
    QScriptContext *ctx = eng.pushContext();
    ctx->setActivationObject(scriptObject);
    QVERIFY(ctx->activationObject().equals(scriptObject));

    QVERIFY(!scriptObject.property("foo").isValid());
    eng.evaluate("function foo() { return 123; }");
    {
        QScriptValue val = scriptObject.property("foo");
        QVERIFY(val.isValid());
        QVERIFY(val.isFunction());
    }
    QVERIFY(!eng.globalObject().property("foo").isValid());

    QVERIFY(!scriptObject.property("bar").isValid());
    eng.evaluate("var bar = 123");
    {
        QScriptValue val = scriptObject.property("bar");
        QVERIFY(val.isValid());
        QVERIFY(val.isNumber());
        QCOMPARE(val.toInt32(), 123);
    }
    QVERIFY(!eng.globalObject().property("bar").isValid());

    {
        QScriptValue val = eng.evaluate("delete foo");
        QVERIFY(val.isBool());
        QVERIFY(val.toBool());
        QVERIFY(!scriptObject.property("foo").isValid());
    }
}
Beispiel #8
0
World *ScriptEvaluator::evaluate(const QString &script)
{
    QScriptEngine engine;

    World* world = new World();
    QScriptValue worldValue = engine.newQObject(world);
    engine.globalObject().setProperty("world", worldValue);

    QScriptValue directionalLightClass = engine.scriptValueFromQMetaObject<DirectionalLight>();
    engine.globalObject().setProperty("DirectionalLight", directionalLightClass);

    engine.evaluate(script);
    if (engine.hasUncaughtException())
    {
        QMessageBox messageBox;
        messageBox.setIcon(QMessageBox::Warning);
        messageBox.setWindowTitle("Script error");
        messageBox.setText("An error occurred while executing the script.");
        messageBox.setInformativeText(engine.uncaughtException().toString());
        messageBox.setDetailedText(engine.uncaughtExceptionBacktrace().join("\n"));
        messageBox.exec();
        return 0;
    }

    return world;
}
Beispiel #9
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();*/
}
Beispiel #10
0
int main(int argc, char **argv)
{
	Q_INIT_RESOURCE(rtfedit);
	
    QApplication app(argc, argv);
    QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
    QScriptEngine engine;

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

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

    QScriptValue func = engine.evaluate("RTF");
    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();
}
inline void defineFunction(ScriptEngine *se, const QString &name,
                           QScriptEngine::FunctionSignature f) {
  QScriptEngine *engine = se->getQScriptEngine();
  QScriptValue fObj     = engine->newFunction(f);
  fObj.setData(engine->newQObject(se));
  engine->globalObject().setProperty(name, fObj);
}
Beispiel #12
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QString fileName = "load.qs";

    QFile scriptFile(fileName);
    if (!scriptFile.open(QIODevice::ReadOnly))
    {
        // handle error
        qDebug()<<"File open error";
    }
    else
    {
        QFileInfo info(scriptFile);
        qDebug()<< "File Path" + info.absoluteFilePath();
    }
    QTextStream stream(&scriptFile);
    QString contents = stream.readAll();
    scriptFile.close();
    ScriptFunctions functions;
    QScriptEngine myEngine;
    QScriptValue scriptFunctions = myEngine.newQObject(&functions);
    myEngine.globalObject().setProperty("nativeFunctions", scriptFunctions);
    myEngine.globalObject().setProperty("load", myEngine.newFunction(loadScripts, /*length=*/1));


    QScriptValue result = myEngine.evaluate(contents, fileName);
     if (myEngine.hasUncaughtException()) {
         int line = myEngine.uncaughtExceptionLineNumber();
         qDebug() << "uncaught exception at line" << line << ":" << result.toString();
     }

    return a.exec();
}
Beispiel #13
0
            bool init() {
                if( m_script->action()->hadError() )
                    m_script->action()->clearError();

                delete m_engine;
                m_engine = new QScriptEngine();

                // load the Qross QScriptExtensionPlugin plugin that provides
                // us a bridge between Qross and QtScript. See here plugin.h
                m_engine->importExtension("qross");
                if( m_engine->hasUncaughtException() ) {
                    handleException();
                    delete m_engine;
                    m_engine = 0;
                    return false;
                }

                // the Qross QScriptExtensionPlugin exports the "Qross" property.
                QScriptValue global = m_engine->globalObject();
                m_qross = global.property("Qross");
                Q_ASSERT( m_qross.isQObject() );
                Q_ASSERT( ! m_engine->hasUncaughtException() );

                // Attach our Qross::Action instance to be able to access it in
                // scripts. Just like at the Kjs-backend we publish our own
                // action as "self".
                m_self = m_engine->newQObject( m_script->action() );
                global.setProperty("self", m_self, QScriptValue::ReadOnly|QScriptValue::Undeletable);

                { // publish the global objects.
                    QHash< QString, QObject* > objects = Manager::self().objects();
                    QHash< QString, QObject* >::Iterator it(objects.begin()), end(objects.end());
                    for(; it != end; ++it)
                        global.setProperty(it.key(), m_engine->newQObject( it.value() ) );
                }

                { // publish the local objects.
                    QHash< QString, QObject* > objects = m_script->action()->objects();
                    QHash< QString, QObject* >::Iterator it(objects.begin()), end(objects.end());
                    for(; it != end; ++it) {
                        copyEnumsToProperties( it.value() );
                        global.setProperty(it.key(), m_engine->newQObject( it.value() ) );
                    }
                }

                return ! m_engine->hasUncaughtException();
            }
Beispiel #14
0
// Perhaps shpw entire example for getting debugger up with script
int main(int argv, char **args)
{
    QApplication app(argv, args);

     QString fileName("helloscript.qs");
     QFile scriptFile(fileName);
     scriptFile.open(QIODevice::ReadOnly);
     QTextStream stream(&scriptFile);
     QString contents = stream.readAll();
     scriptFile.close();

    QScriptEngine *engine = new QScriptEngine();

    QScriptEngineDebugger *debugger = new QScriptEngineDebugger();
    debugger->attachTo(engine);

    // Set up configuration with only stack and code
    QWidget *widget = new QWidget;
//![0]
    QWidget *codeWindow = debugger->widget(QScriptEngineDebugger::CodeWidget);
    QWidget *stackWidget = debugger->widget(QScriptEngineDebugger::StackWidget);

    QLayout *layout = new QHBoxLayout;
    layout->addWidget(codeWindow);
    layout->addWidget(stackWidget);
//![0]

//![1]
    QAction *continueAction = debugger->action(QScriptEngineDebugger::ContinueAction);
    QAction *stepOverAction = debugger->action(QScriptEngineDebugger::StepOverAction);
    QAction *stepIntoAction = debugger->action(QScriptEngineDebugger::StepIntoAction);

    QToolBar *toolBar = new QToolBar;
    toolBar->addAction(continueAction);
//![1]
    toolBar->addAction(stepOverAction);
    toolBar->addAction(stepIntoAction);

    layout->addWidget(toolBar);
    continueAction->setIcon(QIcon("copy.png"));

    debugger->setAutoShowStandardWindow(false);

    widget->setLayout(layout);
    widget->show();

     QPushButton button;
     QScriptValue scriptButton = engine->newQObject(&button);
     engine->globalObject().setProperty("button", scriptButton);

//![2]
     debugger->action(QScriptEngineDebugger::InterruptAction)->trigger();
     engine->evaluate(contents, fileName);
//![2]

    return app.exec();
}
bool TCPNetworkServerPlugin::ConfigureScriptEngine(QScriptEngine &engine)
{
	QScriptValue TCPNetworkServerProto = engine.newQObject(TCPNetworkServerObject);
	engine.setDefaultPrototype(qMetaTypeId<TCPNetworkServer*>(), TCPNetworkServerProto);
	QScriptValue TCPNetworkServerCtor = engine.newFunction(TCPNetworkServer::ctor__extensionname, TCPNetworkServerProto);
	engine.globalObject().setProperty(PLUGIN_SCRIPTOBJECT_NAME, TCPNetworkServerCtor);
    //int nRes = 
		qRegisterMetaType<TCPNetworkServer>(PLUGIN_SCRIPTOBJECT_NAME);
	//FinalizeScriptObjectScriptContext(engine, TCPNetworkServerObject);
	return true;
}
Beispiel #16
0
int main(int argc, char *argv[])
{
//! [0]
    QScriptEngine engine;
    QObject *someObject = new MyObject;
    QScriptValue objectValue = engine.newQObject(someObject);
    engine.globalObject().setProperty("myObject", objectValue);
//! [0]
    qDebug() << "myObject's calculate() function returns"
             << engine.evaluate("myObject.calculate(10)").toNumber();
    return 0;
}
Beispiel #17
0
//! [0]
int main(int argc, char *argv[])
{
    Q_INIT_RESOURCE(helloscript);
//! [0]

//! [1]
    QApplication app(argc, argv);

    QScriptEngine engine;

    QTranslator translator;
    translator.load("helloscript_la");
    app.installTranslator(&translator);
    engine.installTranslatorFunctions();
//! [1]

//! [2]
    QPushButton button;
    QScriptValue scriptButton = engine.newQObject(&button);
    engine.globalObject().setProperty("button", scriptButton);
//! [2]

//! [3]
    QString fileName(":/helloscript.js");
    QFile scriptFile(fileName);
    scriptFile.open(QIODevice::ReadOnly);
    QTextStream stream(&scriptFile);
    QString contents = stream.readAll();
    scriptFile.close();
//! [3]

#ifdef Q_OS_SYMBIAN
    contents.replace("button.show()", "button.showMaximized()");
#endif

//! [4]
    QScriptValue result = engine.evaluate(contents, fileName);
//! [4]

//! [5]
    if (result.isError()) {
        QMessageBox::critical(0, "Hello Script",
                              QString::fromLatin1("%0:%1: %2")
                              .arg(fileName)
                              .arg(result.property("lineNumber").toInt32())
                              .arg(result.toString()));
        return -1;
    }
//! [5]

//! [6]
    return app.exec();
}
Beispiel #18
0
void Oboy::handle(QHttpRequest *req, QHttpResponse *res)
{
    QScriptEngine *engine = m_callback.engine();
    Q_ASSERT(engine);
    
    QScriptValue reqWrapper = engine->newQObject(req, QScriptEngine::ScriptOwnership);
    QScriptValue resWrapper = engine->newQObject(res, QScriptEngine::ScriptOwnership);

    resWrapper.setProperty("writeHead", engine->newFunction(mapHeader));

    m_callback.call(QScriptValue(), QScriptValueList() << reqWrapper << resWrapper);
}
Beispiel #19
0
Datei: main.cpp Projekt: BGmot/Qt
int main(int argc, char **argv)
{
    Q_INIT_RESOURCE(defaultprototypes);

    QApplication app(argc, argv);
//! [1]
    QScriptEngine engine;

    ListWidgetItemPrototype lwiProto;
    engine.setDefaultPrototype(qMetaTypeId<QListWidgetItem*>(),
                               engine.newQObject(&lwiProto));

    ListWidgetPrototype lwProto;
    engine.setDefaultPrototype(qMetaTypeId<QListWidget*>(),
                               engine.newQObject(&lwProto));
//! [1]

//! [2]
    QListWidget listWidget;
    engine.globalObject().setProperty("listWidget",
                                      engine.newQObject(&listWidget));
//! [2]

    QFile file(":/code.js");
    file.open(QIODevice::ReadOnly);
    QScriptValue result = engine.evaluate(file.readAll());
    file.close();
    if (engine.hasUncaughtException()) {
        int lineNo = engine.uncaughtExceptionLineNumber();
        qWarning() << "line" << lineNo << ":" << result.toString();
    }

#if defined(Q_OS_SYMBIAN)
    listWidget.showMaximized();
#else
    listWidget.show();
#endif
    return app.exec();
}
Beispiel #20
0
void PlugScript::slNewPiece(InterfaceTetris tpD)
{


    ifTetris=&tpD;
//    QByteArray     tpCur( tpD.aBoard);
    iWaiting=0;

    QScriptEngine scrptEngine;
    QFile         file("d:\\ETK\\Projects\\qt\\tetrisqt\\tetris.js");
    if (!file.open(QFile::ReadOnly)) {
        QMessageBox::critical(0,
                              QString("File open error"),
                               "Can not open the script file:"+file.fileName() ,
                              QMessageBox::Yes
                             );

    }
    QLabel  lb;
    QScriptValue objTetris=scrptEngine.newQObject(&lb);
    scrptEngine.globalObject().setProperty("objTetris", objTetris);

    //objTetris.setProperty("mBoard",tpCur);
    //scrptEngine.globalObject().setProperty("iTetris",interfaceTetris);
    //QScriptValue val=scrptEngine.evaluate("");
    QString str=QLatin1String(file.readAll());



    scrptEngine.globalObject().setProperty("foo", 123);

    QScriptValue result =
        scrptEngine.evaluate(str);


//    Q_ASSERT(result);

    if (result.isError()) {
        QMessageBox::critical(0,
                              "Evaluating error",
                              result.toString(),
                              QMessageBox::Yes
                             );
    }



    iLines++;
    emit sgDbg(result.toInteger());

}
Beispiel #21
0
int main(int argc, char **argv)
{
    Q_INIT_RESOURCE(calculator);

    QApplication app(argc, argv);
//! [0a]
    QScriptEngine engine;
//! [0a]

#if !defined(QT_NO_SCRIPTTOOLS)
    QScriptEngineDebugger debugger;
    debugger.attachTo(&engine);
    QMainWindow *debugWindow = debugger.standardWindow();
    debugWindow->resize(1024, 640);
#endif

//! [0b]
    QString scriptFileName(":/calculator.js");
    QFile scriptFile(scriptFileName);
    scriptFile.open(QIODevice::ReadOnly);
    engine.evaluate(scriptFile.readAll(), scriptFileName);
    scriptFile.close();
//! [0b]

//! [1]
    QUiLoader loader;
    QFile uiFile(":/calculator.ui");
    uiFile.open(QIODevice::ReadOnly);
    QWidget *ui = loader.load(&uiFile);
    uiFile.close();
//! [1]

//! [2]
    QScriptValue ctor = engine.evaluate("Calculator");
    QScriptValue scriptUi = engine.newQObject(ui, QScriptEngine::ScriptOwnership);
    QScriptValue calc = ctor.construct(QScriptValueList() << scriptUi);
//! [2]

#if !defined(QT_NO_SCRIPTTOOLS)
    QLineEdit *display = qFindChild<QLineEdit*>(ui, "display");
    QObject::connect(display, SIGNAL(returnPressed()),
                     debugWindow, SLOT(show()));
#endif
//! [3]
    ui->show();
    return app.exec();
//! [3]
}
//! [46]
int main(int argc, char **argv)
{
    QApplication app(argc, argv);

    QScriptEngine eng;
    QPlainTextEdit edit;

    QScriptValue fun = eng.newFunction(myPrintFunction);
    fun.setData(eng.newQObject(&edit));
    eng.globalObject().setProperty("print", fun);

    eng.evaluate("print('hello', 'world')");

    edit.show();
    return app.exec();
}
Beispiel #23
0
int main(int argc, char *argv[])
{

    if(argc<3)
    {
    	printf("%s file.ui file.js\n",argv[0]);
    	return 0;
    }

    QApplication app(argc, argv);

    QScriptEngine engine;

	QUiLoader loader;
	QFile file(argv[1]);
     	file.open(QFile::ReadOnly);

     	QWidget *formWidget = loader.load(&file);
     	file.close();

    QScriptValue scriptWidget = engine.newQObject(formWidget);
    engine.globalObject().setProperty("widget", scriptWidget);
    
    QFile ifile(argv[2]);
    ifile.open(QFile::ReadOnly);
    QByteArray code=ifile.readAll();
    ifile.close();

	if( !engine.canEvaluate(code) )
	{
		printf("Error\n");
		return 1;
	}

    engine.evaluate("widget.show()");
    QScriptValue result = engine.evaluate(code);
    
    if (engine.hasUncaughtException())
    {
         int line = engine.uncaughtExceptionLineNumber();
         qDebug() << "uncaught exception at line" << line << ":" << result.toString();
    }

    return app.exec();
}
Beispiel #24
0
bool JSScript::execute(TWScriptAPI *tw) const
{
	QFile scriptFile(m_Filename);
	if (!scriptFile.open(QIODevice::ReadOnly)) {
		// handle error
		return false;
	}
	QTextStream stream(&scriptFile);
	stream.setCodec(m_Codec);
	QString contents = stream.readAll();
	scriptFile.close();
	
	QScriptEngine engine;
	QScriptValue twObject = engine.newQObject(tw);
	engine.globalObject().setProperty("TW", twObject);
	
	QScriptValue val;

#if QT_VERSION >= 0x040500
	QSETTINGS_OBJECT(settings);
	if (settings.value("scriptDebugger", false).toBool()) {
		QScriptEngineDebugger debugger;
		debugger.attachTo(&engine);
		val = engine.evaluate(contents, m_Filename);
	}
	else {
		val = engine.evaluate(contents, m_Filename);
	}
#else
	val = engine.evaluate(contents, m_Filename);
#endif

	if (engine.hasUncaughtException()) {
		tw->SetResult(engine.uncaughtException().toString());
		return false;
	}
	else {
		if (!val.isUndefined()) {
			tw->SetResult(convertValue(val));
		}
		return true;
	}
}
Beispiel #25
0
void QCATs::Register(QScriptEngine& engine)
{
    QObject* p_obj = new QCATs;
    QScriptValue objectValue = engine.newQObject(p_obj);
    engine.globalObject().setProperty("CATs", objectValue);

    QScriptValue fun;
    fun = engine.newFunction(QCATs::printf);
    engine.globalObject().setProperty("printf", fun);

    fun = engine.newFunction(QCATs::print);
    engine.globalObject().setProperty("print", fun);

    fun = engine.newFunction(QCATs::sprintf);
    engine.globalObject().setProperty("sprintf", fun);

    fun = engine.newFunction(QCATs::exit);
    engine.globalObject().setProperty("exit", fun);
}
Beispiel #26
0
void JavascriptAnimation::prepInstance()
{
    QScriptEngine *engine = AnimationScriptEngine::globalEngine();
    m_instance.setProperty("__plasma_javascriptanimation", engine->newQObject(this),
                          QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
    ADD_ENUM_VALUE(m_instance, Plasma::Animator, FadeAnimation);
    ADD_ENUM_VALUE(m_instance, Plasma::Animator, AppearAnimation);
    ADD_ENUM_VALUE(m_instance, Plasma::Animator, DisappearAnimation);
    ADD_ENUM_VALUE(m_instance, Plasma::Animator, ActivateAnimation);
    ADD_ENUM_VALUE(m_instance, Plasma::Animator, FadeAnimation);
    ADD_ENUM_VALUE(m_instance, Plasma::Animator, GrowAnimation);
    ADD_ENUM_VALUE(m_instance, Plasma::Animator, PulseAnimation);
    ADD_ENUM_VALUE(m_instance, Plasma::Animator, RotationAnimation);
    ADD_ENUM_VALUE(m_instance, Plasma::Animator, RotationStackedAnimation);
    ADD_ENUM_VALUE(m_instance, Plasma::Animator, SlideAnimation);
    ADD_ENUM_VALUE(m_instance, Plasma::Animator, GeometryAnimation);
    ADD_ENUM_VALUE(m_instance, Plasma::Animator, ZoomAnimation);
    ADD_ENUM_VALUE(m_instance, Plasma::Animator, PixmapTransitionAnimation);
    ADD_ENUM_VALUE(m_instance, JavascriptAnimation, PauseAnimation);
    ADD_ENUM_VALUE(m_instance, JavascriptAnimation, PropertyAnimation);
}
Beispiel #27
0
void TextImportDialog::doImport()
{
	// Get settings from UI
	
	QString fileName;
	QString pastedTempfile;
	
	if(m_ui->tabWidget->currentIndex() == 1)
	{
		// copy/paste buffer
		QString text = m_ui->plainTextEdit->toPlainText();
	
		pastedTempfile = tr("%1/dviz-textimportdialog-pasted.txt").arg(QDir::tempPath());
		
		QFile file(pastedTempfile);
		if(!file.open(QIODevice::WriteOnly))
		{
			QMessageBox::critical(this,tr("Can't Wriite Temp File"),QString(tr("Unable to write temp file %1")).arg(pastedTempfile));
			return;
		}
	
		QTextStream stream(&file);
		stream << text;
		file.close();
		
		fileName = pastedTempfile;
		
		qDebug() << "Wrote temp file: "<<pastedTempfile;
	}
	else
	{
		fileName = m_ui->filename->text();
		AppSettings::setPreviousPath("textimport",fileName);
	}
	
	// Store the originally-given file for the group name later
	QString originalFileName = fileName;
	
	bool isPlainText = m_ui->fmtPlain->isChecked();
	QSettings().setValue("textimport/plaintext",isPlainText);
	
	QString scriptFilename = m_ui->scriptFile->text();
	AppSettings::setPreviousPath("script",scriptFilename);
	
	QString preprocFilename = m_ui->preprocFile->text();
	AppSettings::setPreviousPath("preproc",preprocFilename);
	
	
	// Setup progress dialog
	QProgressDialog progress(QString(tr("Loading %1...")).arg(fileName),"",0,0);
	progress.setWindowModality(Qt::WindowModal);
	progress.setCancelButton(0); // hide cancel button
	progress.setWindowIcon(QIcon(":/data/icon-d.png"));
	progress.setWindowTitle(QString(tr("Loading %1")).arg(fileName));
	progress.show();
	m_progress = &progress;
	QApplication::processEvents();
	
	
	
	qDebug() << "TextImportDialog::doImport(): Start, file:"<<fileName<<", isPLain? "<<isPlainText<<", script:"<<scriptFilename<<", preproc:"<<preprocFilename;
	
	QString tempFilename;
	if(!preprocFilename.isEmpty())
	{
		tempFilename = tr("%1/dviz-textimportdialog-temp.txt").arg(QDir::tempPath());
		
		QProcess proc;
		proc.start(preprocFilename, QStringList() << fileName << tempFilename);
		
		bool result = proc.waitForFinished();
		if(!result)
		{
			QMessageBox::critical(this,tr("Pre-Processor Problem"),QString(tr("Preproc %1 didn't finish properly. Check the console - not sure why.")).arg(fileName));
			return;
		}
		
		fileName = tempFilename;
		qDebug() << "TextImportDialog::doImport(): Preprocessor completed, using preproc temp file: "<<tempFilename;
	}
	
	// Load text file
	QFile file(fileName);
	if(!file.open(QIODevice::ReadOnly))
	{
		QMessageBox::critical(this,tr("Can't Read File"),QString(tr("Unable to open %1")).arg(fileName));
		return;
	}

	QTextStream stream(&file);
	QString fileContents = stream.readAll();
	
	if(!tempFilename.isEmpty())
		file.remove(); // file is closed before it is removed
		
	// Remove the paste buffer
	//if(!pastedTempfile.isEmpty())
	//	QFile(pastedTempfile).remove();
		
	// Load script file
	QScriptEngine scriptEngine;
	if(!scriptFilename.isEmpty())
	{
		// For debug output
		static_currentScriptFile = scriptFilename;
		 
		// Install some custom functions for the script
		QScriptValue fDebug        = scriptEngine.newFunction(TextImportDialog_script_qDebug);
		QScriptValue fFindTextItem = scriptEngine.newFunction(TextImportDialog_script_findTextItem);
		QScriptValue fChangeFntSz  = scriptEngine.newFunction(TextImportDialog_script_changeFontSize);
		QScriptValue fFindFntSz    = scriptEngine.newFunction(TextImportDialog_script_findFontSize);
		QScriptValue fCntrTextBox  = scriptEngine.newFunction(TextImportDialog_script_intelligentCenterTextbox);
		QScriptValue fFileList     = scriptEngine.newFunction(TextImportDialog_script_getFileList);
		QScriptValue fChangeBg     = scriptEngine.newFunction(TextImportDialog_script_changeSlideBackground);
		QScriptValue fGuessTimeout = scriptEngine.newFunction(TextImportDialog_script_guessSlideTimeout);
		
		scriptEngine.globalObject().setProperty("debug",          fDebug);
		scriptEngine.globalObject().setProperty("findTextItem",   fFindTextItem);
		scriptEngine.globalObject().setProperty("changeFontSize", fChangeFntSz);
		scriptEngine.globalObject().setProperty("findFontSize",   fFindFntSz);
		scriptEngine.globalObject().setProperty("intelligentCenterTextbox", fCntrTextBox);
		scriptEngine.globalObject().setProperty("getFileList",    fFileList);
		scriptEngine.globalObject().setProperty("changeSlideBackground", fChangeBg);
		scriptEngine.globalObject().setProperty("guessSlideTimeout", fGuessTimeout);
		
		scriptEngine.globalObject().setProperty("InPrimaryGroup", true);
	
		QScriptValue scriptBibleBrowser = scriptEngine.newQObject(MainWindow::mw()->bibleBrowser());
		scriptEngine.globalObject().setProperty("BibleBrowser", scriptBibleBrowser);
		
 		// Read the file
		QFile scriptFile(scriptFilename);
		if(!scriptFile.open(QIODevice::ReadOnly))
		{
			QMessageBox::critical(this,tr("Can't Read Script"),QString(tr("Unable to open script %1")).arg(fileName));
			return;
		}
		
		// Evaulate the contents of the file
		QTextStream stream(&scriptFile);
		QString contents = stream.readAll();
		scriptFile.close();
		QScriptValue scriptResult = scriptEngine.evaluate(contents, fileName);
		
		// Alert user of syntax error in script
		if (scriptEngine.hasUncaughtException()) 
		{
			int line = scriptEngine.uncaughtExceptionLineNumber();
			//qDebug() << "uncaught exception at line" << line << ":" << result.toString();
			QMessageBox::critical(this,tr("Script Exception"),QString(tr("Uncaught Exception in file %1, line %2: \n\t%3\n\nImport canceled. Please fix script and try again."))
				.arg(scriptFilename)
				.arg(line)
				.arg(scriptResult.toString()));
			return;
		}
	}
	
	// Generate the slides and set the group title
	qDebug() << "TextImportDialog::doImport(): Creating template and slides for primary group";
	SlideGroup *templateGroup = getTemplate();
	SlideGroup *group = generateSlideGroup(templateGroup, fileContents, isPlainText, scriptEngine, scriptFilename);
	if(!group)
	{
		// script error or other error, cancel import
		return;
	}
	
	
	// Apply group title using the original file name, just in case we used a pre-processor
	if(group->groupTitle().isEmpty())
		group->setGroupTitle(AbstractItem::guessTitle(QFileInfo(originalFileName).baseName()));
	
	
	qDebug() << "TextImportDialog::doImport(): Checking for alternate groups";
	
	// Set a flag so scripts can respond differently for alternate groups
	if(!scriptFilename.isEmpty())
		scriptEngine.globalObject().setProperty("InPrimaryGroup", false);
	
	// Create alternate groups for outputs if present in template
	QList<Output*> allOut = AppSettings::outputs();
	foreach(Output *out, allOut)
	{
		SlideGroup *outputTemplate = templateGroup->altGroupForOutput(out);
		if(outputTemplate)
		{
			SlideGroup *existingAlt = group->altGroupForOutput(out);
			
			qDebug() << "TextImportDialog::doImport(): [prep] Creating alternate group from template for output: "<<out->name()<<", existingAlt: "<<existingAlt;
			
			SlideGroup *altGroup = generateSlideGroup(outputTemplate, fileContents, isPlainText, scriptEngine, scriptFilename, existingAlt, group);
			if(!altGroup)
			{
				// script error or other error, cancel import
				delete group;
				return;
			}
			
			altGroup->setGroupTitle(tr("Alternate %1 for %2").arg(group->groupTitle()).arg(out->name()));
			
			group->setAltGroupForOutput(out, altGroup);
		}
	}
Beispiel #28
0
void Agent::run() {
    NodeList::getInstance()->setOwnerType(NODE_TYPE_AGENT);
    NodeList::getInstance()->setNodeTypesOfInterest(&NODE_TYPE_VOXEL_SERVER, 1);
    
    QNetworkAccessManager manager;
    
    // figure out the URL for the script for this agent assignment
    QString scriptURLString("http://%1:8080/assignment/%2");
    scriptURLString = scriptURLString.arg(NodeList::getInstance()->getDomainIP().toString(),
                                         this->getUUIDStringWithoutCurlyBraces());
    QUrl scriptURL(scriptURLString);
    
    qDebug() << "Attemping download of " << scriptURL << "\n";
    
    QNetworkReply* reply = manager.get(QNetworkRequest(scriptURL));
    
    QEventLoop loop;
    QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();
    
    QString scriptString = QString(reply->readAll());
    
    QScriptEngine engine;
    
    QScriptValue agentValue = engine.newQObject(this);
    engine.globalObject().setProperty("Agent", agentValue);
    
    VoxelScriptingInterface voxelScripter;
    QScriptValue voxelScripterValue =  engine.newQObject(&voxelScripter);
    engine.globalObject().setProperty("Voxels", voxelScripterValue);
    
    qDebug() << "Downloaded script:" << scriptString << "\n";
    qDebug() << "Evaluated script:" << engine.evaluate(scriptString).toString() << "\n";
    
    timeval thisSend;
    timeval lastDomainServerCheckIn = {};
    int numMicrosecondsSleep = 0;
    
    const long long DATA_SEND_INTERVAL_USECS = (1 / 60.0f) * 1000 * 1000;
    
    sockaddr_in senderAddress;
    unsigned char receivedData[MAX_PACKET_SIZE];
    ssize_t receivedBytes;
    
    while (!_shouldStop) {
        // update the thisSend timeval to the current time
        gettimeofday(&thisSend, NULL);
        
        // if we're not hearing from the domain-server we should stop running
        if (NodeList::getInstance()->getNumNoReplyDomainCheckIns() == MAX_SILENT_DOMAIN_SERVER_CHECK_INS) {
            break;
        }
        
        // send a check in packet to the domain server if DOMAIN_SERVER_CHECK_IN_USECS has elapsed
        if (usecTimestampNow() - usecTimestamp(&lastDomainServerCheckIn) >= DOMAIN_SERVER_CHECK_IN_USECS) {
            gettimeofday(&lastDomainServerCheckIn, NULL);
            NodeList::getInstance()->sendDomainServerCheckIn();
        }
        
        // allow the scripter's call back to setup visual data
        emit preSendCallback();
        // flush the voxel packet queue
        voxelScripter.getVoxelPacketSender()->process();
        
        if (NodeList::getInstance()->getNodeSocket()->receive((sockaddr*) &senderAddress, receivedData, &receivedBytes)) {
            NodeList::getInstance()->processNodeData((sockaddr*) &senderAddress, receivedData, receivedBytes);
        }
        
        // sleep for the correct amount of time to have data send be consistently timed
        if ((numMicrosecondsSleep = DATA_SEND_INTERVAL_USECS - (usecTimestampNow() - usecTimestamp(&thisSend))) > 0) {
            usleep(numMicrosecondsSleep);
        }
    }
    
}
Beispiel #29
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);
}
Beispiel #30
0
void setup::setCurrentIndex(XTreeWidgetItem* item)
{
  QString uiName = item->data(0, Xt::RawRole).toString();
  QString label = "<span style=\" font-size:14pt; font-weight:600;\">%1</span></p></body></html>";

  if (_itemMap.contains(uiName) && _itemMap.value(uiName).index >= 0)
  {
    _stack->setCurrentIndex(_itemMap.value(uiName).index);
    _stackLit->setText(label.arg(item->text(0)));
    return;
  }
  else if (_itemMap.contains(uiName) && !item->isDisabled())
  {
    // First look for a class...
    QWidget *w = xtGetScreen(uiName, this);

    if (w)
      _itemMap[uiName].implementation = w;
    else
    {
      // No class, so look for an extension
      XSqlQuery screenq;
      screenq.prepare("SELECT * "
                      "  FROM uiform "
                      " WHERE((uiform_name=:uiform_name)"
                      "   AND (uiform_enabled))"
                      " ORDER BY uiform_order DESC"
                      " LIMIT 1;");
      screenq.bindValue(":uiform_name", uiName);
      screenq.exec();
      if (screenq.first())
      {     
        QUiLoader loader;
        QByteArray ba = screenq.value("uiform_source").toByteArray();
        QBuffer uiFile(&ba);
        if (!uiFile.open(QIODevice::ReadOnly))
          QMessageBox::critical(0, tr("Could not load UI"),
                                tr("<p>There was an error loading the UI Form "
                                   "from the database."));
        w = loader.load(&uiFile);
        w->setObjectName(uiName);
        uiFile.close();

        // Load scripts if applicable
        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", uiName);
        scriptq.exec();

        QScriptEngine* engine = new QScriptEngine();
        if (_preferences->boolean("EnableScriptDebug"))
        {
          QScriptEngineDebugger* debugger = new QScriptEngineDebugger(this);
          debugger->attachTo(engine);
        }
        omfgThis->loadScriptGlobals(engine);
        QScriptValue mywindow = engine->newQObject(w);
        engine->globalObject().setProperty("mywindow", mywindow);

        while(scriptq.next())
        {
          QString script = scriptHandleIncludes(scriptq.value("script_source").toString());
          QScriptValue result = engine->evaluate(script, uiName);
          if (engine->hasUncaughtException())
          {
            int line = engine->uncaughtExceptionLineNumber();
            qDebug() << "uncaught exception at line" << line << ":" << result.toString();
          }
        }
        _itemMap[uiName].implementation = engine;
      }
    }

    if (w)
    {
      // Hide buttons out of context here
      QWidget* close = w->findChild<QWidget*>("_close");
      if (close)
        close->hide();
      QWidget* buttons = w->findChild<QDialogButtonBox*>();
      if (buttons)
        buttons->hide();

      //Set mode if applicable
      int mode = _itemMap.value(uiName).mode;
      if (mode && w->inherits("XDialog"))
      {
        XWidget* x = dynamic_cast<XWidget*>(w);
        ParameterList params;
        if (mode == cEdit)
          params.append("mode", "edit");
        else if (mode == cView)
          params.append("mode", "view");
        if (x)
          x->set(params);
      }

      int idx = _stack->count();
      _itemMap[uiName].index = idx;
      _stack->addWidget(w);
      _stack->setCurrentIndex(idx);

      _stackLit->setText(label.arg(item->text(0)));
      return;
    }
  }

  // Nothing here so try the next one
  XTreeWidgetItem* next = dynamic_cast<XTreeWidgetItem*>(_tree->itemBelow(item));
  if (next)
    setCurrentIndex(next);
}