void SystemComponent::runUserScript(QString script)
{
  // We take the path the user supplied and run it through fileInfo and
  // look for the fileName() part, this is to avoid people sharing keymaps
  // that tries to execute things like ../../ etc. Note that this function
  // is still not safe, people can do nasty things with it, so users needs
  // to be careful with their keymaps.
  //
  QFileInfo fi(script);
  QString scriptPath = Paths::dataDir("scripts/" + fi.fileName());

  QFile scriptFile(scriptPath);
  if (scriptFile.exists())
  {
    if (!QFileInfo(scriptFile).isExecutable())
    {
      QLOG_WARN() << "Script:" << script << "is not executable";
      return;
    }

    QLOG_INFO() << "Running script:" << scriptPath;

    if (QProcess::startDetached(scriptPath, QStringList()))
      QLOG_DEBUG() << "Script started successfully";
    else
      QLOG_WARN() << "Error running script:" << scriptPath;
  }
  else
  {
    QLOG_WARN() << "Could not find script:" << scriptPath;
  }
}
Example #2
0
void        ExcLoadDlg::on_openexc_clicked()
{
    if( m_excpath.isEmpty() ) {
        m_excpath   = m_curpath;
    }

    QTextCodec *codec = QTextCodec::codecForLocale();

    QString name = QFileDialog::getOpenFileName(this,
                   codec->toUnicode("打开异常记录文件"), m_excpath, tr("txt Files (Exc_Omp.txt Exc_pp.txt *.txt);;all files(*.*)"));
    if(!name.isEmpty()) {
        QFileInfo   file(name);
        m_curpath   = file.path();
        m_excpath   = m_curpath;

        QFile scriptFile(name);
        scriptFile.open(QIODevice::ReadOnly);
        m_ui.ExcInfo->setPlainText(scriptFile.readAll());
        scriptFile.close();

        if( m_libpath.isEmpty() ) {
            m_libpath   = m_curpath;
            m_ui.LibPath->setText(m_libpath);
        }
    }
}
	bool execute()
	{
		TFilePath fp;
		QString fileName = "helloworld.qs";
		QFile scriptFile(QString::fromStdWString(fp.getWideString()));
		if (!scriptFile.open(QIODevice::ReadOnly)) {
			DVGui::MsgBox(DVGui::WARNING, QObject::tr("File not found"));
			return false;
		} else {
			QTextStream stream(&scriptFile);
			QString contents = stream.readAll();
			scriptFile.close();
			QScriptEngine myEngine;
			QScriptEngineDebugger debugger;
			debugger.attachTo(&myEngine);

			QScriptValue fFoo = myEngine.newFunction(foo);
			QScriptValue fGetLevel = myEngine.newFunction(getLevel);

			myEngine.globalObject().setProperty("foo", fFoo);
			myEngine.globalObject().setProperty("getLevel", fGetLevel);
			debugger.action(QScriptEngineDebugger::InterruptAction)->trigger();
			myEngine.evaluate(contents, fileName);
		}
		return true;
	}
Example #4
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();
}
Example #5
0
bool ScriptHandler::init()
{
    ScriptEngineInitializer::addFuctionsToScriptEngine(*mEngine);

    QFile scriptFile(mFile);
    if (!scriptFile.open(QIODevice::ReadOnly))
    {
        kError() << "could not open file" << mFile << " -> cannot evaluate script";
        return false;
    }
    QTextStream stream(&scriptFile);
    QString contents = stream.readAll();
    scriptFile.close();
#ifdef OKTETA_DEBUG_SCRIPT
    mDebugger->attachTo(mEngine);
    mDebugger->action(QScriptEngineDebugger::InterruptAction)->trigger();
#endif
    mEngine->evaluate(contents, mFile);

    if (mEngine->hasUncaughtException())
    {
        ScriptUtils::object()->logScriptError(mEngine->uncaughtExceptionBacktrace());
        return false;
    }
    return true;
}
Example #6
0
ScriptEngine::ScriptEngine(const QUrl& scriptURL,
                           AbstractControllerScriptingInterface* controllerScriptingInterface)  :
    _scriptContents(),
    _isFinished(false),
    _isRunning(false),
    _isInitialized(false),
    _engine(),
    _isAvatar(false),
    _avatarIdentityTimer(NULL),
    _avatarBillboardTimer(NULL),
    _timerFunctionMap(),
    _isListeningToAudioStream(false),
    _avatarSound(NULL),
    _numAvatarSoundSentBytes(0),
    _controllerScriptingInterface(controllerScriptingInterface),
    _avatarData(NULL),
    _scriptName(),
    _fileNameString(),
    _quatLibrary(),
    _vec3Library(),
    _uuidLibrary(),
    _animationCache(this)
{
    QString scriptURLString = scriptURL.toString();
    _fileNameString = scriptURLString;

    QUrl url(scriptURL);

    // if the scheme length is one or lower, maybe they typed in a file, let's try
    const int WINDOWS_DRIVE_LETTER_SIZE = 1;
    if (url.scheme().size() <= WINDOWS_DRIVE_LETTER_SIZE) {
        url = QUrl::fromLocalFile(scriptURLString);
    }

    // ok, let's see if it's valid... and if so, load it
    if (url.isValid()) {
        if (url.scheme() == "file") {
            QString fileName = url.toLocalFile();
            QFile scriptFile(fileName);
            if (scriptFile.open(QFile::ReadOnly | QFile::Text)) {
                qDebug() << "Loading file:" << fileName;
                QTextStream in(&scriptFile);
                _scriptContents = in.readAll();
            } else {
                qDebug() << "ERROR Loading file:" << fileName;
                emit errorMessage("ERROR Loading file:" + fileName);
            }
        } else {
            QNetworkAccessManager* networkManager = new QNetworkAccessManager(this);
            QNetworkReply* reply = networkManager->get(QNetworkRequest(url));
            qDebug() << "Downloading included script at" << url;
            QEventLoop loop;
            QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
            loop.exec();
            _scriptContents = reply->readAll();
        }
    }
}
Example #7
0
void PluginManager::preparePlugins() {
    // Ordered by load priority
    QStringList knownRoles = {"core", "service", "widget", "window"};

    QQueue<AdamantPluginInfo*> plugins;

    for (const QString role : knownRoles) {
        for (AdamantPluginInfo* data : _pluginsByRole.values(role)) {
            // Here we want to enqueue plugins to be loaded
            plugins.enqueue(data);
        }
    }

    // Clear master list
    _plugins.clear();

    // Now they should be in the correct role loading order.
    while (!plugins.isEmpty()) {
        AdamantPluginInfo* data = plugins.dequeue();

        // LOADER CODE
        data->loader = new QPluginLoader(data->file.absoluteFilePath(), this);
        bool load = data->loader->load();
        bool loaded = data->loader->isLoaded();
        QString error = data->loader->errorString();
        if (load && loaded) {
            AdamantPlugin* plugin = qobject_cast<AdamantPlugin*>(data->loader->instance());
            if (plugin != nullptr) {
                data->instance = plugin;

                // Now we inject the PluginManager
                injectPluginData(data);

                // The plugin has been created successfully, so we can execute it's script (if it exists).
                const QDir dir = data->file.absoluteDir();
                QFile scriptFile(dir.filePath(data->file.fileName() + ".qs"));
                if (scriptFile.exists() && scriptFile.open(QFile::ReadOnly)) {
                    const QString script = scriptFile.readAll();
                    scriptFile.close();

                    data->script = addScript(scriptFile.fileName(), script, data->instance);
                }

                _plugins.append(data);
                continue;
            }
        }

        // Delete if we couldn't load
        data->loader->deleteLater();
        delete data;
        data = nullptr;
    }

    _pluginsByRole.clear();

    loadAndExecuteScripts();
}
Example #8
0
bool
ScriptManager::slotRunScript( const QString &name, bool silent )
{
    DEBUG_BLOCK

    ScriptItem *item = m_scripts.value( name );
    const KUrl url = item->url;
    //load the wrapper classes
    item->engine = new QScriptEngine( this );
    connect(item->engine,
            SIGNAL(signalHandlerException(QScriptValue)),
            SLOT(handleException(QScriptValue)));

    startScriptEngine( name );
    QFile scriptFile( url.path() );
    scriptFile.open( QIODevice::ReadOnly );
    item->running = true;
    item->evaluating = true;
    if( item->info.category() == "Lyrics" )
    {
        m_lyricsScript = name;
        debug() << "lyrics script started:" << name;
        emit lyricsScriptStarted();
    }

    item->log << QString( "%1 Script started" ).arg( QTime::currentTime().toString() );
    item->engine->setProcessEventsInterval( 100 );
    item->engine->evaluate( scriptFile.readAll() );
    scriptFile.close();

    if ( item->evaluating )
    {
        item->evaluating = false;
        if ( item->engine->hasUncaughtException() )
        {
            QString errorString = QString( "Script Error: %1 (line: %2)" )
                .arg( item->engine->uncaughtException().toString() )
                .arg( item->engine->uncaughtExceptionLineNumber() );
            item->log << errorString;
            error() << errorString;
            item->engine->clearExceptions();
            slotStopScript( name );

            if( !silent )
            {
                debug() << "The Log For the script that is the borked: " << item->log;
            }
            return false;
        }

        if( item->info.category() == QLatin1String("Scriptable Service") )
            ServiceScriptCustomize( name );
    }
    else
        slotStopScript( name );

    return true;
}
Example #9
0
void Kludget::runJavaScriptFile(QWebFrame* frame, const QString &p)
{
    QFile scriptFile(p);
    if (scriptFile.open(QIODevice::ReadOnly))
    {
        QString script = QTextStream(&scriptFile).readAll();
        frame->evaluateJavaScript(script);
    }
}
Example #10
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();
}
Example #11
0
int emscriptenQtSDLMain(int argc, char *argv[])
#endif
{
    Q_INIT_RESOURCE(helloscript);
//! [0]

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

    engine = new QScriptEngine;

    QTranslator *translator = new QTranslator;
    translator->load("helloscript_la");
    app->installTranslator(translator);
    engine->installTranslatorFunctions();
//! [1]

//! [2]
    QPushButton *button = new QPushButton;
    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();
}
Example #12
0
void MainWindowImpl::doSomethingExperimental()
{
	qDebug() << "MainWindowImpl::doSomethingExperimental()";
	//new QGraphicsLineItem( 0,0, 200, 200 )
	//impl->gstate.scene()->addItem(  );
	//impl->gstate.scene()->addWidget( new QFrame );

	if(0)
	{
	    QString fileName("eval.js");
	    QFile scriptFile(fileName);
	    if (!scriptFile.open(QIODevice::ReadOnly)) return;
	    qDebug() << "[ running script"<<fileName<<"]";
	    QScriptEngine & eng( impl->gstate.jsEngine() );
	    QTextStream stream(&scriptFile);
	    QString contents = stream.readAll();
	    scriptFile.close();
	    eng.evaluate(contents, fileName);
	    qDebug() << "[ done running script"<<fileName<<"]";
	}

	if(0)
	{
	    QBoardHomeView * v = new QBoardHomeView(0);
	    v->show();
	    connect( v, SIGNAL(itemActivated(QFileInfo const &)),
		     this, SLOT(loadFile(QFileInfo const &)) );

#if 0
	    QDirModel *model = new QDirModel;
	    model->setIconProvider( impl->fb->iconProvider() );
	    QTreeView *tree = new QTreeView(0);
	    tree->setModel(model);
	    for( int i = 1; i < 4; ++i )
	    {
		tree->setColumnHidden(i, true);
	    }
	    tree->setRootIndex(model->index(QDir::currentPath()));
	    tree->show();
	    QString fn("QBoard/manual/index.html");
	    QModelIndex sel;
#define FP sel = model->index(fn); \
	    qDebug() << fn << "sel.isValid() =="<<sel.isValid() \
		     << "filePath =="<<model->filePath(sel);
	    FP;
	    fn = QString("%1/QBoard/manual/index.html").arg(qboard::home().absolutePath());
	    FP;
	    fn = "/foo";
	    FP;
#undef FP
#endif
	}
Example #13
0
bool DlgJsRoboKey::loadJSFile(const QString &file)
{
    QFile scriptFile(file);
    if (!scriptFile.open(QIODevice::ReadOnly))
    {
        return false;
    }
    // handle error
    QTextStream stream(&scriptFile);
    QString contents = stream.readAll();
    scriptFile.close();
    return loadJS(contents, file);
}
Example #14
0
bool ScriptUnit::saveToFile(const QString &filePath)
{
    QFile scriptFile(filePath);
    if (!scriptFile.open(QIODevice::WriteOnly)) {
        QString error = QString("Selected file %1 could not be opened!").arg(m_filePath);
        Log.w(error);
        return false;
    }

    QTextStream out(&scriptFile);
    out << scriptText();
    return true;
}
Example #15
0
void KWin::DeclarativeScript::run()
{
    if (running()) {
        return;
    }

    m_component->loadUrl(QUrl::fromLocalFile(scriptFile().fileName()));
    if (m_component->isLoading()) {
        connect(m_component, &QQmlComponent::statusChanged, this, &DeclarativeScript::createComponent);
    } else {
        createComponent();
    }
}
Example #16
0
void KateEngine::launch(QString fileName)
{
    qDebug() << __FILE__ << ": line " << __LINE__ ;

    QFile scriptFile(fileName);

    scriptFile.open(QIODevice::ReadOnly);
    QTextStream stream(&scriptFile);
    QString contents = stream.readAll();
    scriptFile.close();

    // 执行
    evaluate(contents,fileName) ;
}
Example #17
0
/**
 * Replace the contents of the editor with the given file
 * @param filename
 * @return True if the read succeeded, false otherwise
 */
bool ScriptFileInterpreter::readFileIntoEditor(const QString &filename) {
  m_editor->setFileName(filename);
  QFile scriptFile(filename);
  if (!scriptFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
    QMessageBox::critical(
        this, tr("MantidPlot - File error"),
        tr("Could not open file \"%1\" for reading.").arg(filename));
    return false;
  }
  m_editor->read(&scriptFile);
  m_editor->setModified(false);
  scriptFile.close();
  return true;
}
QString JavascriptInstance::LoadScript(const QString &fileName)
{
    PROFILE(JSInstance_LoadScript);
    QString filename = fileName.trimmed();

    // First check if the include was supposed to go through the Asset API.
    if (module_)
    {
        ScriptAssetPtr asset = dynamic_pointer_cast<ScriptAsset>(module_->GetFramework()->Asset()->GetAsset(fileName));
        if (asset)
            return asset->scriptContent;
    }

    /// @bug When including other scripts from startup scripts the only way to include is with relative paths.
    /// As you cannot use !rel: ref in startup scripts (loaded without EC_Script) so you cannot use local:// refs either. 
    /// You have to do engine.IncludeFile("lib/class.js") etc. and this below code needs to find the file whatever the working dir is, a plain QFile::open() wont cut it!

    // Otherwise, treat fileName as a local file to load up.
    // Check install dir and the clean rel path.
    QString pathToFile = "";
    QDir jsPluginDir(QDir::fromNativeSeparators(Application::InstallationDirectory()) + "jsmodules");
    if (jsPluginDir.exists(filename))
        pathToFile = jsPluginDir.filePath(filename);
    else if (QFile::exists(filename))
        pathToFile = filename;
    if (pathToFile.isEmpty())
    {
        LogError("JavascriptInstance::LoadScript: Failed to load script from file " + filename + "!");
        return "";
    }

    QFile scriptFile(pathToFile);
    if (!scriptFile.open(QIODevice::ReadOnly))
    {
        LogError("JavascriptInstance::LoadScript: Failed to load script from file " + filename + "!");
        return "";
    }

    QString result = scriptFile.readAll();
    scriptFile.close();

    QString trimmedResult = result.trimmed();
    if (trimmedResult.isEmpty())
    {
        LogWarning("JavascriptInstance::LoadScript: Warning Loaded script from file " + filename + ", but the content was empty.");
        return "";
    }
    return result;
}
Example #19
0
File: main.cpp Project: Fale/qtmoko
//! [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.qs");
    QFile scriptFile(fileName);
    scriptFile.open(QIODevice::ReadOnly);
    QTextStream stream(&scriptFile);
    QString contents = stream.readAll();
    scriptFile.close();
//! [3]

//! [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();
}
Example #20
0
//Load the asset from the specified file
bool GMAsset_Script::Load(const QFileInfo &file)
{

    this->GMAsset::Load(file);
    QFile scriptFile(file.absoluteFilePath());
    if (!scriptFile.exists()) return false; //File does not exist
    if (!scriptFile.open(QIODevice::ReadOnly | QIODevice::Text))
            return false; //Failed to open the file
    this->script = "";
    QTextStream in(&scriptFile);
         while (!in.atEnd()) {
             this->script.append(in.readLine()).append("\n");
         }
    return true;
}
Example #21
0
bool LuaInterfaceBase::LoadScript(const std::string& scriptPath)
{
    if(!lua.dofile(scriptPath))
    {
        script_.clear();
        if(GLOBALVARS.isTest)
            throw std::runtime_error("Could not load lua script");
        return false;
    } else
    {
        std::ifstream scriptFile(scriptPath.c_str());
        script_.assign(std::istreambuf_iterator<char>(scriptFile), std::istreambuf_iterator<char>());
        return true;
    }
}
Example #22
0
boolType LuaScript::loadScript(stringType filePath) {
  std::ifstream scriptFile (filePath);
    
  if (scriptFile.is_open()) {
    stringType stringBuffer((std::istreambuf_iterator<char>(scriptFile)),
			     std::istreambuf_iterator<char>());
    scriptFile.close();
    return this->loadString(stringBuffer, filePath);
  }
  else {
    std::cerr << "LUA_ERROR: Failed to load script --> " << filePath << std::endl;
    return false;
  }
  
}
Example #23
0
void PdbEngine::setupInferior()
{
    QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());

    QString fileName = QFileInfo(startParameters().executable).absoluteFilePath();
    QFile scriptFile(fileName);
    if (!scriptFile.open(QIODevice::ReadOnly|QIODevice::Text)) {
        showMessageBox(QMessageBox::Critical, tr("Python Error"),
            _("Cannot open script file %1:\n%2").
               arg(fileName, scriptFile.errorString()));
        notifyInferiorSetupFailed();
        return;
    }
    notifyInferiorSetupOk();
}
Example #24
0
QString EntityTreeRenderer::loadScriptContents(const QString& scriptMaybeURLorText, bool& isURL) {
    QUrl url(scriptMaybeURLorText);

    // If the url is not valid, this must be script text...
    if (!url.isValid()) {
        isURL = false;
        return scriptMaybeURLorText;
    }
    isURL = true;

    QString scriptContents; // assume empty

    // if the scheme length is one or lower, maybe they typed in a file, let's try
    const int WINDOWS_DRIVE_LETTER_SIZE = 1;
    if (url.scheme().size() <= WINDOWS_DRIVE_LETTER_SIZE) {
        url = QUrl::fromLocalFile(scriptMaybeURLorText);
    }

    // ok, let's see if it's valid... and if so, load it
    if (url.isValid()) {
        if (url.scheme() == "file") {
            QString fileName = url.toLocalFile();
            QFile scriptFile(fileName);
            if (scriptFile.open(QFile::ReadOnly | QFile::Text)) {
                qDebug() << "Loading file:" << fileName;
                QTextStream in(&scriptFile);
                scriptContents = in.readAll();
            } else {
                qDebug() << "ERROR Loading file:" << fileName;
            }
        } else {
            QNetworkAccessManager& networkAccessManager = NetworkAccessManager::getInstance();
            QNetworkReply* reply = networkAccessManager.get(QNetworkRequest(url));
            qDebug() << "Downloading script at" << url;
            QEventLoop loop;
            QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
            loop.exec();
            if (reply->error() == QNetworkReply::NoError && reply->attribute(QNetworkRequest::HttpStatusCodeAttribute) == 200) {
                scriptContents = reply->readAll();
            } else {
                qDebug() << "ERROR Loading file:" << url.toString();
            }
            delete reply;
        }
    }

    return scriptContents;
}
Example #25
0
File: main.cpp Project: cedrus/qt4
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]
}
Example #26
0
void readFile(QScriptEngine& engine, const QString& fileName) {
	QString scriptFileName(QString("/home/mrz/zen/javascript/") + fileName);
	QFile scriptFile(scriptFileName);
	if ( scriptFile.open(QIODevice::ReadOnly) ) {
		QScriptValue result = engine.evaluate(scriptFile.readAll());
		scriptFile.close();
		if ( engine.hasUncaughtException() ) {
			qDebug() << "Error in file " << fileName;
			qDebug() << "Line: " << engine.uncaughtExceptionLineNumber();
			qDebug() << engine.uncaughtExceptionBacktrace();
		}
	}
	else {
		qDebug() << "Failed to open file " << fileName;
	}
}
Example #27
0
STTwitterText::STTwitterText(QObject *parent) :
    QObject(parent)
{
    if(!g_processMutex)
        g_processMutex=new QMutex();
    QString fileName = ":/stella/res/twitter-text.js";
    QFile scriptFile(fileName);
    if (!scriptFile.open(QIODevice::ReadOnly)){
        qFatal("Couldn't open twitter-text.js from resource.");
    }

     QTextStream stream(&scriptFile);
     QString contents = stream.readAll();
     scriptFile.close();

     if(!g_engine){
         g_engine=new QScriptEngine();
     }

     QScriptValue result =g_engine->evaluate(contents, fileName);

     if(g_engine->hasUncaughtException()){
         int line = g_engine->uncaughtExceptionLineNumber();
         QByteArray str=g_engine->uncaughtException().toString().toUtf8();
         qFatal("Exception while evaluating twitter-text.js at line %d: %s", line, str.data());
     }

     {
         QScriptValue result=g_engine->evaluate("function f(text, opt){return twttr.txt.getTweetLength(text, opt);} f");

         g_tweetLengthFunction=new QScriptValue(result);
         if(!g_tweetLengthFunction->isFunction()){
             int line = g_engine->uncaughtExceptionLineNumber();
             QByteArray str=g_engine->uncaughtException().toString().toUtf8();
             qFatal("Exception while linking getTweetLength at line %d: %s", line, str.data());
         }
     }
     {
         QScriptValue result=g_engine->evaluate("function f(text){return twttr.txt.extractMentions(text);} f");
         g_extractMentionsFunction=new QScriptValue(result);
         if(!g_extractMentionsFunction->isFunction()){
             int line = g_engine->uncaughtExceptionLineNumber();
             QByteArray str=g_engine->uncaughtException().toString().toUtf8();
             qFatal("Exception while linking extractMentions at line %d: %s", line, str.data());
         }
     }
}
    bool QtScriptEngine::runScriptFile(string name, RunMode mode)
    {
        QFile scriptFile(name.c_str());

        if (!scriptFile.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            this->callEventHandlers(IScriptEngine::Error, NULL, -1, "Unable to open script file.");

            return false;
        }

        QTextStream stream(&scriptFile);
        QString contents = stream.readAll();
        scriptFile.close();

        return this->runScript(contents, QString(name.c_str()), mode);
    }
/**
 * Saves a JSON script file
 *
 * @param browser Selected browser
 * @param script JSON native messaging script object
 * @return bool Write succeeds
 */
bool HostInstaller::saveFile(SupportedBrowsers browser, const QJsonObject& script)
{
    QString path = getPath(browser);
    QString installDir = getInstallDir(browser);
    QDir dir(installDir);
    if (!dir.exists()) {
        QDir().mkpath(installDir);
    }

    QFile scriptFile(path);
    if (!scriptFile.open(QIODevice::WriteOnly)) {
        return false;
    }

    QJsonDocument doc(script);
    return scriptFile.write(doc.toJson()) >= 0;
}
Example #30
0
void
QtScriptResolver::init()
{
    QFile scriptFile( filePath() );
    if( !scriptFile.open( QIODevice::ReadOnly ) )
    {
        qWarning() << "Failed to read contents of file:" << filePath() << scriptFile.errorString();
        return;
    }
    const QByteArray scriptContents = scriptFile.readAll();

    m_engine->mainFrame()->setHtml( "<html><body></body></html>" );

    // add c++ part of tomahawk javascript library
    m_engine->mainFrame()->addToJavaScriptWindowObject( "Tomahawk", m_resolverHelper );

    // add rest of it
    m_engine->setScriptPath( "tomahawk.js" );
    QFile jslib( RESPATH "js/tomahawk.js" );
    jslib.open( QIODevice::ReadOnly );
    m_engine->mainFrame()->evaluateJavaScript( jslib.readAll() );
    jslib.close();

    // add resolver
    m_engine->setScriptPath( filePath() );
    m_engine->mainFrame()->evaluateJavaScript( scriptContents );

    // init resolver
    resolverInit();

    QVariantMap m = resolverSettings();
    m_name    = m.value( "name" ).toString();
    m_weight  = m.value( "weight", 0 ).toUInt();
    m_timeout = m.value( "timeout", 25 ).toUInt() * 1000;

    // load config widget and apply settings
    loadUi();
    QVariantMap config = resolverUserConfig();
    fillDataInWidgets( config );

    qDebug() << "JS" << filePath() << "READY," << "name" << m_name << "weight" << m_weight << "timeout" << m_timeout;

    m_ready = true;
    Tomahawk::Pipeline::instance()->addResolver( this );
}