bool QgsPythonUtilsImpl::runString( const QString& command, QString msgOnError, bool single )
{
  bool res = runStringUnsafe( command, single );
  if ( res )
    return true;

  if ( msgOnError.isEmpty() )
  {
    // use some default message if custom hasn't been specified
    msgOnError = QObject::tr( "An error occurred during execution of following code:" ) + "\n<tt>" + command + "</tt>";
  }

  // TODO: use python implementation

  QString traceback = getTraceback();
  QString path, version;
  evalString( "str(sys.path)", path );
  evalString( "sys.version", version );

  QString str = "<font color=\"red\">" + msgOnError + "</font><br><pre>\n" + traceback + "\n</pre>"
                + QObject::tr( "Python version:" ) + "<br>" + version + "<br><br>"
                + QObject::tr( "QGIS version:" ) + "<br>" + QString( "%1 '%2', %3" ).arg( QGis::QGIS_VERSION, QGis::QGIS_RELEASE_NAME, QGis::QGIS_DEV_VERSION ) + "<br><br>"
                + QObject::tr( "Python path:" ) + "<br>" + path;
  str.replace( '\n', "<br>" ).replace( "  ", "&nbsp; " );

  qDebug() << str;
  QgsMessageOutput* msg = QgsMessageOutput::createMessageOutput();
  msg->setTitle( QObject::tr( "Python error" ) );
  msg->setMessage( str, QgsMessageOutput::MessageHtml );
  msg->showMessage();

  return res;
}
bool QgsPythonUtilsImpl::runString( const QString& command, QString msgOnError )
{
  bool res = runStringUnsafe( command );
  if ( res )
    return true;

  if ( msgOnError.isEmpty() )
  {
    // use some default message if custom hasn't been specified
    msgOnError = QObject::tr( "An error occured during execution of following code:" ) + "\n<tt>" + command + "</tt>";
  }

  QString traceback = getTraceback();
  QString path, version;
  evalString( "str(sys.path)", path );
  evalString( "sys.version", version );

  QString str = "<font color=\"red\">" + msgOnError + "</font><br><br>" + traceback + "<br>" +
                QObject::tr( "Python version:" ) + "<br>" + version + "<br><br>" +
                QObject::tr( "Python path:" ) + "<br>" + path;
  str.replace( "\n", "<br>" ).replace( "  ", "&nbsp; " );

  QgsMessageOutput* msg = QgsMessageOutput::createMessageOutput();
  msg->setTitle( QObject::tr( "Python error" ) );
  msg->setMessage( str, QgsMessageOutput::MessageHtml );
  msg->showMessage();

  return res;
}
LCPP_TestCase(Syntax_BuiltinFunctions, define_name)
{
    auto pResult = evalString("(define x (lambda () 42))");
    pResult = evalString("x");

    CUT_ASSERT.isTrue(object::hasName(pResult));
    CUT_ASSERT.isTrue(symbol::getValue(object::getName(pResult)).IsEqual("x"));
}
LCPP_TestCase(Syntax_BuiltinFunctions, define)
{
    auto pResult = LCPP_pNil;

    pResult = evalString("(define x 1)");

    CUT_ASSERT.isTrue(isVoid(pResult));

    pResult = evalString("x");

    CUT_ASSERT.isTrue(number::getInteger(pResult) == 1);
}
LCPP_TestCase(Syntax_BuiltinFunctions, define_shortHandLambdaSyntax)
{
    LCPP_TEST_DebugBreakOnExceptionsInThisScope;

    auto pResult = LCPP_pNil;

    evalString("(define (the-answer) 42)");
    pResult = evalString("(the-answer)");
    CUT_ASSERT.isTrue(number::getInteger(pResult) == 42);

    evalString("(define (something a b) 1 2 3 b a)");
    pResult = evalString("(something 5 4)");
    CUT_ASSERT.isTrue(number::getInteger(pResult) == 5);
}
    VALUE makeProtectedCall(const std::string &t_functionName, std::vector<VALUE> &t_params)
    {
      // we go through all of this because we cannot rb_protect a call to
      // rb_funcall. At least not in any way I can find.
      std::stringstream params;

      for (size_t i = 0; i < t_params.size(); ++i)
      {
        std::stringstream ss;
        ss << "$embedded_ruby_param_" << i;

        rb_define_variable(ss.str().c_str(), &t_params[i]);

        params << ss.str();
        if (i < t_params.size() - 1)
        {
          params << ", ";
        }
      }

      std::string funcall = "$embedded_ruby_return = " + t_functionName + "(" + params.str() + ")";
      evalString(funcall);

      VALUE retval = rb_gv_get("$embedded_ruby_return");
      return retval;
    } 
Beispiel #7
0
void TclTextInterp::userkey_cb(const char *key_desc) {
  int indx = app->userKeys.typecode(key_desc);
  if(indx >= 0) {
    const char *cmd = app->userKeys.data(indx);
    evalString(cmd);
  }
}
Beispiel #8
0
void test_expression_evaluator_each(GLEPolish* polish, const std::string& expression, const std::string& expectedValue) {
	int cp = 0;
	int rtype = 0;
	GLEPcodeList pc_list;
	GLEPcode pcode(&pc_list);
	polish->polish(expression.c_str(), pcode, &rtype);
	GLERC<GLEArrayImpl> stk(new GLEArrayImpl());
	std::ostringstream msg;
	msg << expression << ": ";
	if (is_float(expectedValue)) {
		GLEMemoryCell* mc = evalGeneric(stk.get(), &pc_list, (int*)&pcode[0], &cp);
		gle_memory_cell_check(mc, GLEObjectTypeDouble);
		double expectedDouble = tokenizer_string_to_double(expectedValue.c_str());
		msg << mc->Entry.DoubleVal << " == " << expectedValue;
		if (expectedDouble == 0.0) {
			unit_test_msg(fabs(mc->Entry.DoubleVal) < CUTILS_REL_PREC_FINE, msg.str());
		} else {
			unit_test_msg(equals_rel_fine(mc->Entry.DoubleVal, expectedDouble), msg.str());
		}
	} else {
		GLERC<GLEString> result(evalString(stk.get(), &pc_list, (int*)&pcode[0], &cp, true));
		std::string computedString(result->toUTF8());
		msg << computedString << " == " << expectedValue;
		unit_test_msg(expectedValue == computedString, msg.str());
	}
}
LCPP_TestCase(Syntax_BuiltinFunctions, or)
{
    auto pResult = LCPP_pNil;

    pResult = evalString("(or)");
    CUT_ASSERT.isTrue(isFalse(pResult));

    pResult = evalString("(or 1)");
    CUT_ASSERT.isTrue(number::getInteger(pResult) == 1);

    pResult = evalString("(or 1 2)");
    CUT_ASSERT.isTrue(number::getInteger(pResult) == 1);

    pResult = evalString("(or #f 1 2)");
    CUT_ASSERT.isTrue(number::getInteger(pResult) == 1);
}
Beispiel #10
0
QString QgsPythonUtilsImpl::getPluginMetadata( const QString& pluginName, const QString& function )
{
  QString res;
  QString str = "qgis.utils.pluginMetadata('" + pluginName + "', '" + function + "')";
  evalString( str, res );
  //QgsDebugMsg("metadata "+pluginName+" - '"+function+"' = "+res);
  return res;
}
Beispiel #11
0
QStringList QgsPythonUtilsImpl::pluginList()
{
  runString( "qgis.utils.updateAvailablePlugins()" );

  QString output;
  evalString( "'\\n'.join(qgis.utils.available_plugins)", output );
  return output.split( QChar( '\n' ), QString::SkipEmptyParts );
}
LCPP_TestCase(Syntax_BuiltinFunctions, lambda)
{
    auto pResult = LCPP_pNil;

    //////////////////////////////////////////////////////////////////////////

    pResult = evalString("lambda");
    CUT_ASSERT.isTrue(syntax::builtin::getName(pResult) == symbol::create("lambda"));

    //////////////////////////////////////////////////////////////////////////

    pResult = evalString("(lambda () 1)");
    CUT_ASSERT.isTrue(isNil(lambda::userDefined::getName(pResult)));

    //////////////////////////////////////////////////////////////////////////

    pResult = evalString("((lambda () 1))");
    CUT_ASSERT.isTrue(number::getInteger(pResult) == 1);
}
Beispiel #13
0
static void runCustomScript(const std::string &filename)
{
	std::string scriptData;

	if (!readFileSDL(filename.c_str(), scriptData))
	{
		showMsg(std::string("Unable to open '") + filename + "'");
		return;
	}

	evalString(newStringUTF8(scriptData.c_str(), scriptData.size()),
	           newStringUTF8(filename.c_str(), filename.size()), NULL);
}
ROP_RENDER_CODE wendy_GIO_ROP::renderFrame( fpreal time, UT_Interrupt *boss )
{

    executePreFrameScript(time);
    fpreal t =CHgetManager()->getTime(this->myCurrentFrame);  //this can get the time!!!!
    now=time;


    UT_String save_geo_path;
    evalString(save_geo_path,"file",0,time);
    OP_Context		 context(time);

    UT_String _ar_dso_path;
    evalString(_ar_dso_path,"ArDso",0,time);

    save_gdp_to_disk(_ar_dso_path,context,save_geo_path);



    if (error() < UT_ERROR_ABORT)
        executePostFrameScript(time);
    return ROP_CONTINUE_RENDER;
}
LCPP_TestCase(Syntax_BuiltinFunctions, begin)
{
    auto pResult = LCPP_pNil;

    //////////////////////////////////////////////////////////////////////////

    pResult = evalString("begin");
    CUT_ASSERT.isTrue(syntax::builtin::getName(pResult) == symbol::create("begin"));

    //////////////////////////////////////////////////////////////////////////

    pResult = evalString("(begin)");
    CUT_ASSERT.isTrue(isVoid(pResult));

    //////////////////////////////////////////////////////////////////////////

    pResult = evalString("(begin 1)");
    CUT_ASSERT.isTrue(number::getInteger(pResult) == 1);

    //////////////////////////////////////////////////////////////////////////

    pResult = evalString("(begin 1 2)");
    CUT_ASSERT.isTrue(number::getInteger(pResult) == 2);
}
Beispiel #16
0
void ChessGame::onMoveMade(const Chess::Move& move)
{
	ChessPlayer* sender = qobject_cast<ChessPlayer*>(QObject::sender());
	Q_ASSERT(sender != nullptr);

	Q_ASSERT(m_gameInProgress);
	Q_ASSERT(m_board->isLegalMove(move));
	if (sender != playerToMove())
	{
		qDebug("%s tried to make a move on the opponent's turn", qPrintable(sender->name()));
		return;
	}

	m_scores[m_moves.size()] = sender->evaluation().score();
	m_moves.append(move);
	addPgnMove(move, evalString(sender->evaluation()));

	// Get the result before sending the move to the opponent
	m_board->makeMove(move);
	m_result = m_board->result();
	if (m_result.isNone())
	{
		if (m_board->reversibleMoveCount() == 0)
			m_adjudicator.resetDrawMoveCount();

		m_adjudicator.addEval(m_board, sender->evaluation());
		m_result = m_adjudicator.result();
	}
	m_board->undoMove();

	ChessPlayer* player = playerToWait();
	player->makeMove(move);
	m_board->makeMove(move);

	if (m_result.isNone())
	{
		emitLastMove();
		startTurn();
	}
	else
	{
		stop(false);
		emitLastMove();
	}
}
LCPP_TestCase(Syntax_BuiltinFunctions, if_)
{
    evalString("(if #t (define evaluated-to-true-1 #t) (define evaluated-to-false-1 #f))");

    CUT_ASSERT.throwsNothing([]{ evalString("evaluated-to-true-1"); });
    CUT_ASSERT.throws<exceptions::NoBindingFound>([]{ evalString("evaluated-to-false-1"); });

    //////////////////////////////////////////////////////////////////////////

    evalString("(if #f (define evaluated-to-true-2 #t) (define evaluated-to-false-2 #f))");

    CUT_ASSERT.throwsNothing([]{ evalString("evaluated-to-false-2"); });
    CUT_ASSERT.throws<exceptions::NoBindingFound>([]{ evalString("evaluated-to-true-2"); });
}
LCPP_TestCase(Syntax_BuiltinFunctions, set)
{
    CUT_ASSERT.throwsNothing([]{ evalString("set!"); });
    CUT_ASSERT.throws<exceptions::NoBindingFound>([]{ evalString("(set! x 1)"); });

    auto pResult = LCPP_pNil;

    evalString("(define x 1)");
    pResult = evalString("x");
    CUT_ASSERT.isTrue(number::getInteger(pResult) == 1);

    pResult = evalString("(set! x 42)");
    CUT_ASSERT.isTrue(isVoid(pResult));
    pResult = evalString("x");
    CUT_ASSERT.isTrue(number::getInteger(pResult) == 42);
}
Beispiel #19
0
bool QgsPythonUtilsImpl::startServerPlugin( QString packageName )
{
  QString output;
  evalString( "qgis.utils.startServerPlugin('" + packageName + "')", output );
  return ( output == "True" );
}
Beispiel #20
0
bool QgsPythonUtilsImpl::isPluginLoaded( const QString& packageName )
{
  QString output;
  evalString( "qgis.utils.isPluginLoaded('" + packageName + "')", output );
  return ( output == "True" );
}
Beispiel #21
0
bool QgsPythonUtilsImpl::canUninstallPlugin( const QString& packageName )
{
  QString output;
  evalString( "qgis.utils.canUninstallPlugin('" + packageName + "')", output );
  return ( output == "True" );
}
Beispiel #22
0
static void runRMXPScripts()
{
	const std::string &scriptPack = shState->rtData().config.game.scripts;

	if (scriptPack.empty())
	{
		showMsg("No game scripts specified (missing Game.ini?)");
		return;
	}

	if (!shState->fileSystem().exists(scriptPack.c_str()))
	{
		showMsg("Unable to open '" + scriptPack + "'");
		return;
	}

	VALUE scriptArray = kernelLoadDataInt(scriptPack.c_str());

	if (rb_type(scriptArray) != RUBY_T_ARRAY)
	{
		showMsg("Failed to read script data");
		return;
	}

	rb_gv_set("$RGSS_SCRIPTS", scriptArray);

	long scriptCount = RARRAY_LEN(scriptArray);

	std::string decodeBuffer;
	decodeBuffer.resize(0x1000);

	for (long i = 0; i < scriptCount; ++i)
	{
		VALUE script = rb_ary_entry(scriptArray, i);

		if (rb_type(script) != RUBY_T_ARRAY)
			continue;

		VALUE scriptName   = rb_ary_entry(script, 1);
		VALUE scriptString = rb_ary_entry(script, 2);

		int result = Z_OK;
		unsigned long bufferLen;

		while (true)
		{
			unsigned char *bufferPtr =
			        reinterpret_cast<unsigned char*>(const_cast<char*>(decodeBuffer.c_str()));
			const unsigned char *sourcePtr =
			        reinterpret_cast<const unsigned char*>(RSTRING_PTR(scriptString));

			bufferLen = decodeBuffer.length();

			result = uncompress(bufferPtr, &bufferLen,
			                    sourcePtr, RSTRING_LEN(scriptString));

			bufferPtr[bufferLen] = '\0';

			if (result != Z_BUF_ERROR)
				break;

			decodeBuffer.resize(decodeBuffer.size()*2);
		}

		if (result != Z_OK)
		{
			static char buffer[256];
			snprintf(buffer, sizeof(buffer), "Error decoding script %ld: '%s'",
			         i, RSTRING_PTR(scriptName));

			showMsg(buffer);

			break;
		}

		rb_ary_store(script, 3, rb_str_new_cstr(decodeBuffer.c_str()));
	}

	for (long i = 0; i < scriptCount; ++i)
	{
		VALUE script = rb_ary_entry(scriptArray, i);
		VALUE scriptDecoded = rb_ary_entry(script, 3);
		VALUE string = newStringUTF8(RSTRING_PTR(scriptDecoded),
		                             RSTRING_LEN(scriptDecoded));

		VALUE fname;
		if (shState->rtData().config.useScriptNames)
		{
			fname = rb_ary_entry(script, 1);
		}
		else
		{
			char buf[32];
			int len = snprintf(buf, sizeof(buf), RGSS_SECTION_STR, i);
			fname = newStringUTF8(buf, len);
		}

		int state;
		evalString(string, fname, &state);
		if (state)
			break;
	}
}
Beispiel #23
0
QStringList QgsPythonUtilsImpl::listActivePlugins()
{
  QString output;
  evalString( "'\\n'.join(qgis.utils.active_plugins)", output );
  return output.split( QChar( '\n' ), QString::SkipEmptyParts );
}
Beispiel #24
0
void TclTextInterp::help_cb(const char *topic) {
  JString cmd("help ");
  cmd += topic;
  evalString((const char *)cmd);
}
Beispiel #25
0
static void runRMXPScripts(BacktraceData &btData)
{
	const Config &conf = shState->rtData().config;
	const std::string &scriptPack = conf.game.scripts;

	if (scriptPack.empty())
	{
		showMsg("No game scripts specified (missing Game.ini?)");
		return;
	}

	if (!shState->fileSystem().exists(scriptPack.c_str()))
	{
		showMsg("Unable to open '" + scriptPack + "'");
		return;
	}

	VALUE scriptArray;

	/* We checked if Scripts.rxdata exists, but something might
	 * still go wrong */
	try
	{
		scriptArray = kernelLoadDataInt(scriptPack.c_str(), false);
	}
	catch (const Exception &e)
	{
		showMsg(std::string("Failed to read script data: ") + e.msg);
		return;
	}

	if (!RB_TYPE_P(scriptArray, RUBY_T_ARRAY))
	{
		showMsg("Failed to read script data");
		return;
	}

	rb_gv_set("$RGSS_SCRIPTS", scriptArray);

	long scriptCount = RARRAY_LEN(scriptArray);

	std::string decodeBuffer;
	decodeBuffer.resize(0x1000);

	for (long i = 0; i < scriptCount; ++i)
	{
		VALUE script = rb_ary_entry(scriptArray, i);

		if (!RB_TYPE_P(script, RUBY_T_ARRAY))
			continue;

		VALUE scriptName   = rb_ary_entry(script, 1);
		VALUE scriptString = rb_ary_entry(script, 2);

		int result = Z_OK;
		unsigned long bufferLen;

		while (true)
		{
			unsigned char *bufferPtr =
			        reinterpret_cast<unsigned char*>(const_cast<char*>(decodeBuffer.c_str()));
			const unsigned char *sourcePtr =
			        reinterpret_cast<const unsigned char*>(RSTRING_PTR(scriptString));

			bufferLen = decodeBuffer.length();

			result = uncompress(bufferPtr, &bufferLen,
			                    sourcePtr, RSTRING_LEN(scriptString));

			bufferPtr[bufferLen] = '\0';

			if (result != Z_BUF_ERROR)
				break;

			decodeBuffer.resize(decodeBuffer.size()*2);
		}

		if (result != Z_OK)
		{
			static char buffer[256];
			snprintf(buffer, sizeof(buffer), "Error decoding script %ld: '%s'",
			         i, RSTRING_PTR(scriptName));

			showMsg(buffer);

			break;
		}

		rb_ary_store(script, 3, rb_str_new_cstr(decodeBuffer.c_str()));
	}

	/* Execute preloaded scripts */
	for (std::set<std::string>::iterator i = conf.preloadScripts.begin();
	     i != conf.preloadScripts.end(); ++i)
		runCustomScript(*i);

	VALUE exc = rb_gv_get("$!");
	if (exc != Qnil)
		return;

	while (true)
	{
		for (long i = 0; i < scriptCount; ++i)
		{
			VALUE script = rb_ary_entry(scriptArray, i);
			VALUE scriptDecoded = rb_ary_entry(script, 3);
			VALUE string = newStringUTF8(RSTRING_PTR(scriptDecoded),
			                             RSTRING_LEN(scriptDecoded));

			VALUE fname;
			const char *scriptName = RSTRING_PTR(rb_ary_entry(script, 1));
			char buf[512];
			int len;

			if (conf.useScriptNames)
				len = snprintf(buf, sizeof(buf), "%03ld:%s", i, scriptName);
			else
				len = snprintf(buf, sizeof(buf), SCRIPT_SECTION_FMT, i);

			fname = newStringUTF8(buf, len);
			btData.scriptNames.insert(buf, scriptName);

			int state;
			evalString(string, fname, &state);
			if (state)
				break;
		}

		VALUE exc = rb_gv_get("$!");
		if (rb_obj_class(exc) != getRbData()->exc[Reset])
			break;

		processReset();
	}
}
Beispiel #26
0
void TclTextInterp::tcl_cb(const char *cmd) {
  evalString(cmd);
}