示例#1
0
TEST_F(CScriptEnvTest, ExecuteScript)
{
  EXCEPINFO exc;
  CComVariant result;

  ASSERT_HRESULT_SUCCEEDED(ExecuteScript(_T("1+2"), &exc, &result));

  ASSERT_EQ(VT_I4, result.vt);
  ASSERT_EQ(3, result.intVal);

  ASSERT_EQ(SCRIPT_E_REPORTED, ExecuteScript(_T("nonexist"), &exc, &result));   
}
示例#2
0
int main()
{
	// Generic OS initialisation
	if (!Shell::Initialise("./") || !Shell::OpenWindow("RocketSquirrel Tests", true))
	{
		Shell::Shutdown();
		return -1;
	}

	// Rocket initialisation.
	ShellRenderInterfaceOpenGL opengl_renderer;
	Rocket::Core::SetRenderInterface(&opengl_renderer);

	// Initialise our system interface
	ShellSystemInterface system_interface;
	Rocket::Core::SetSystemInterface(&system_interface);

	Rocket::Core::RegisterPlugin(new Rocket::Core::Squirrel::Module());
	Rocket::Core::RegisterPlugin(new Rocket::Controls::Squirrel::Module());

	Rocket::Core::Initialise();

	Rocket::Controls::Initialise();

	DevelopingTests();


	// Create the main Rocket context and set it on the shell's input layer.
	Rocket::Core::Context* context = Rocket::Core::GetContext("ScriptsContext");
	if (context == NULL)
	{
		Rocket::Core::Shutdown();
		Shell::Shutdown();
		return -1;
	}

	Rocket::Debugger::Initialise(context);

	Input::SetContext(context);

	Rocket::Core::String assetsDir(ROCKETSQUIRREL_TESTS_ASSETS);
	assetsDir += "/";

	Shell::LoadFonts(assetsDir.CString());


	//Execute the script that will create the testing GUI
	ExecuteScript("LoadDocument.nut");

	Shell::EventLoop(GameLoop);

	Rocket::Core::Squirrel::CollectGarbage();

	Rocket::Core::Shutdown();

	Shell::CloseWindow();
	Shell::Shutdown();

	return 0;
}
bool TestExecuteScript()
{
	bool fail = false;
	COutStream out;

	engine = asCreateScriptEngine(ANGELSCRIPT_VERSION);
	engine->SetMessageCallback(asMETHOD(COutStream,Callback), &out, asCALL_THISCALL);
	
	RegisterStdString(engine);
	engine->RegisterGlobalFunction("void assert(bool)", asFUNCTION(Assert), asCALL_GENERIC);

	CScriptBuilder builder;

	int r = builder.StartNewModule(engine, 0);
	if( r >= 0 )
		r = builder.AddSectionFromFile("scripts/TestExecuteScript.as");
	if( r >= 0 )
		r = builder.BuildModule();
	if( r >= 0 )
	{
		fail = ExecuteScript();
	}

	engine->Release();
	engine = NULL;

	return fail;
}
示例#4
0
QScriptValue ScriptManager::GetScriptObject(QString name, ScriptComponent* component) {
    if(!HasScript(name)) {
        return QScriptValue::UndefinedValue;
    }

    // save the global object and set an empty one
    QScriptValue global(mScriptEngine->globalObject());
    mScriptEngine->setGlobalObject(mScriptEngine->newObject());

    // write script members/functions as properties into global object
    // like this we have the same engine linked, so the
    ExecuteScript(name);

    // extract the global object and reset the original one
    QScriptValue obj(mScriptEngine->globalObject());
    mScriptEngine->setGlobalObject(global);

    // Set the object's component member.
    QScriptValue componentObject = mScriptEngine->newQObject(component);
    QScriptValue prop = obj.property("component");
    if(prop.isValid()) {
        Logger::Get().Warning("Overriding member \"component\" in script \"" + name + "\" with ScriptComponent \"" + component->GetName() + "\".");
        Logger::Get().Info(" > Previous Value: " + prop.toString());
        Logger::Get().Info(" > Previous  Type: " + QString(prop.toVariant().typeName()) );
    }
    obj.setProperty("component", componentObject);

    return obj;
}
void ViewImpl::SetInputState(ViewInputState state)
{
	m_InputState = state;
	
	std::stringstream js;
	js << "if (window.__couiAndroid !== undefined) window.__couiAndroid.inputState = " << (int)state << ";";
	ExecuteScript(js.str().c_str());
}
void UICheckBox::unSelectedEvent()
{
    if (m_pUnSelectListener && m_pfnUnSelectSelector)
    {
        (m_pUnSelectListener->*m_pfnUnSelectSelector)(this);
    }
	ExecuteScript(ScriptEventCheckBoxUnSelect);
}
示例#7
0
QVariant WizWebEngineView::ExecuteFunction1(QString function, const QVariant& arg1)
{
    QString script = QString("%1(%2);")
            .arg(function)
            .arg(toArgument(arg1))
            ;
    return ExecuteScript(script);
}
示例#8
0
QVariant WizWebEngineView::ExecuteScriptFile(QString fileName)
{
    QString script;
    if (!WizLoadUnicodeTextFromFile(fileName, script)) {
        return QVariant();
    }
    return ExecuteScript(script);
}
示例#9
0
TEST_F(CScriptEnvTest, Properties)
{
  ASSERT_HRESULT_SUCCEEDED(ExecuteScript(_T("var canvas = new Context2D();")));

  EXCEPINFO exc;
  CComVariant result;

  ASSERT_HRESULT_SUCCEEDED(ExecuteScript(_T("canvas"), &exc, &result));

  ASSERT_EQ(VT_DISPATCH, result.vt);
  ASSERT_NE((IDispatch *) NULL, result.pdispVal);

  ASSERT_HRESULT_SUCCEEDED(ExecuteScript(_T("canvas.canvas"), &exc, &result));

  ASSERT_EQ(VT_DISPATCH, result.vt);
  ASSERT_EQ((IDispatch *) NULL, result.pdispVal);
}
示例#10
0
// Execute the script and fetch the Process method.
bool JsHttpRequestProcessor::Initialize(map<string, string>* opts,
                                        map<string, string>* output) {
  // Create a handle scope to hold the temporary references.
  HandleScope handle_scope(GetIsolate());

  // Create a template for the global object where we set the
  // built-in global functions.
  Local<ObjectTemplate> global = ObjectTemplate::New(GetIsolate());
  global->Set(String::NewFromUtf8(GetIsolate(), "log", NewStringType::kNormal)
                  .ToLocalChecked(),
              FunctionTemplate::New(GetIsolate(), LogCallback));

  // Each processor gets its own context so different processors don't
  // affect each other. Context::New returns a persistent handle which
  // is what we need for the reference to remain after we return from
  // this method. That persistent handle has to be disposed in the
  // destructor.
  v8::Local<v8::Context> context = Context::New(GetIsolate(), NULL, global);
  context_.Reset(GetIsolate(), context);

  // Enter the new context so all the following operations take place
  // within it.
  Context::Scope context_scope(context);

  // Make the options mapping available within the context
  if (!InstallMaps(opts, output))
    return false;

  // Compile and run the script
  if (!ExecuteScript(script_))
    return false;

  // The script compiled and ran correctly.  Now we fetch out the
  // Process function from the global object.
  Local<String> process_name =
      String::NewFromUtf8(GetIsolate(), "Process", NewStringType::kNormal)
          .ToLocalChecked();
  Local<Value> process_val;
  // If there is no Process function, or if it is not a function,
  // bail out
  if (!context->Global()->Get(context, process_name).ToLocal(&process_val) ||
      !process_val->IsFunction()) {
    return false;
  }

  // It is a function; cast it to a Function
  Local<Function> process_fun = Local<Function>::Cast(process_val);

  // Store the function in a Global handle, since we also want
  // that to remain after this call returns
  process_.Reset(GetIsolate(), process_fun);

  // All done; all went well
  return true;
}
示例#11
0
QVariant WizWebEngineView::ExecuteFunction4(QString function, const QVariant& arg1, const QVariant& arg2, const QVariant& arg3, const QVariant& arg4)
{
    QString script = QString("%1(%2, %3, %4, %5);")
            .arg(function)
            .arg(toArgument(arg1))
            .arg(toArgument(arg2))
            .arg(toArgument(arg3))
            .arg(toArgument(arg4))
            ;
    return ExecuteScript(script);
}
示例#12
0
/**
*	/remarks	
*
*	/retval		-	ERROR_SUCCESS	(sequencer keeps going)
*				-	<anything else>	(error code for build, sequencer stops)
*
*	/details	-	failaction = ignore
*						-	return ERROR_SUCCESS
*
*				-	failaction = retry
*						-	retry MAX_RETRY_ATTEMPTS times, then return
*							success || fail
*
*				-	failaction = quit
*						-	return error code directly
*
*	/note		-	modules loaded here are freed when the sequence ends
*
*/
UINT CBldAction::Execute(void)
{
	CString sMsg;
	UINT uiReturn = IDOK;

	if (L"exe" == m_strType)
		uiReturn = ExecuteExe();
		
	else if (L"dll" == m_strType)
		uiReturn = ExecuteDll();
	
	else if (L"script" == m_strType)
		uiReturn = ExecuteScript();
	
	else
	{
		sMsg.Format(L"%s unknown type, no action performed", m_strName);
		WriteToLog(sMsg);
	}

	sMsg.Format(L"return value : %d : %s", 
				uiReturn,
				CRedHelperFn::GetErrorMsg(uiReturn));
	WriteToLog(sMsg);
	
	m_iRetryAttempts++;
	if (m_iRetryAttempts > MAX_RETRY_ATTEMPTS)
	{
		m_strFailAction = "quit";
		sMsg.Format(L"max attempts reached failaction moving to: %s", m_strFailAction);
		WriteToLog(sMsg);
	}

	if (ERROR_SUCCESS != uiReturn)
	{
		sMsg.Format(L"failaction : %s", m_strFailAction);
		WriteToLog(sMsg);

		if ("ignore" == m_strFailAction)
			uiReturn = ERROR_SUCCESS;

		if ("retry" == m_strFailAction)
			uiReturn = Execute();
		
		//if ("quit" == m_strFailAction)
		//	just take return code directly

	}

	return uiReturn;

} //CBldAction::Execute()
示例#13
0
bool ModuleLoader::ExecuteScriptFromFile( v8::Isolate* isolate,
                                          const std::string& fileName  )
{
  std::string contents;

  V8Utils::GetFileContents( fileName, contents );

  if( contents.empty() )
  {
    return false;
  }

  return ExecuteScript( isolate, contents, fileName );
}
示例#14
0
v8::Handle<v8::Value> ScriptEnv::ExecuteScriptFile(const char* filePath)
{
    FILE *fp;
    long len;
    char *buf;
    fp=fopen(filePath,"rb");
    fseek(fp,0,SEEK_END); //go to end
    len=ftell(fp); //get position at end (length)
    fseek(fp,0,SEEK_SET); //go to beg.
    buf=(char *)malloc(len); //malloc buffer
    fread(buf,len,1,fp); //read into buffer
    fclose(fp);
    
    return ExecuteScript(buf, filePath, true);
}
bool
gstRecordJSContextImpl::TryExecuteScript(const KHJSScript &script,
                                         QString &ret, QString &error)
{
  try {
    ExecuteScript(script, ret);
    return true;
  } catch (const khException &e) {
    error = e.qwhat();
  } catch (const std::exception &e) {
    error = e.what();
  } catch (...) {
    error = "Unknown error";
  }
  return false;
}
示例#16
0
文件: window.cpp 项目: galek/gamegui
void base_window::callHandler(EventArgs* arg)
{
	if(!arg) return;

	HandlerMap::iterator it = m_handlers.find(arg->name);
	if (it == m_handlers.end()) return;

	std::string& handler = it->second;
	if (handler.empty()) return;

	luabind::object globals = luabind::globals(m_system.getScriptSystem().getLuaState());

	globals["eventArgs"] = arg;
	ExecuteScript(arg->name, handler);
	globals["eventArgs"] = 0;
}
示例#17
0
bool TestExecuteScript()
{
	bool ret = false;

	engine = asCreateScriptEngine(ANGELSCRIPT_VERSION);
	if( LoadScript("scripts/TestExecuteScript.as") < 0 )
	{
		engine->Release();
	    return false;
	}
	CompileScript();
	ret = ExecuteScript();

	engine->Release();
	engine = NULL;

	return ret;
}
示例#18
0
文件: window.cpp 项目: galek/gamegui
bool base_window::onGameEvent(const std::string& ev)
{
	HandlerMap::iterator it = m_handlers.find(ev);
	if (it == m_handlers.end()) return false;

	std::string& handler = it->second;
	if (handler.empty()) return false;

	EventArgs arg;
	arg.name = ev.c_str();

	luabind::object globals = luabind::globals(m_system.getScriptSystem().getLuaState());

	globals["gameEventArgs"] = &arg;
	ExecuteScript(ev, handler);
	globals["gameEventArgs"] = 0;
	return arg.handled;
}
void ServerConsole::Run()
{
    CPrintf(CON_CMDOUTPUT, COL_RED "-Server Console initialized (%s-V0.1)-\n" COL_NORMAL, appname);

    // Run any script files specified on the command line with -run=filename.
    csRef<iCommandLineParser> cmdline = csQueryRegistry<iCommandLineParser>(objreg);
    csRef<iVFS> vfs = csQueryRegistry<iVFS>(objreg);
    if (cmdline && vfs)
    {
        const char *autofile;
        for (int i = 0; (autofile = cmdline->GetOption("run", i)); i++)
        {
            csRef<iDataBuffer> script = vfs->ReadFile(autofile);
            if (script.IsValid())
                ExecuteScript(*(*script));
        }
    }

    MainLoop();
}
示例#20
0
void QueueScriptController::Run()
{
	ExecuteScript(m_script);

	SetLogPrefix(nullptr);

	if (m_markBad)
	{
		GuardedDownloadQueue downloadQueue = DownloadQueue::Guard();
		NzbInfo* nzbInfo = downloadQueue->GetQueue()->Find(m_id);
		if (nzbInfo)
		{
			PrintMessage(Message::mkWarning, "Cancelling download and deleting %s", *m_nzbName);
			nzbInfo->SetDeleteStatus(NzbInfo::dsBad);
			downloadQueue->EditEntry(m_id, DownloadQueue::eaGroupDelete, 0, nullptr);
		}
	}

	g_QueueScriptCoordinator->CheckQueue();
}
示例#21
0
void
DoScript(StandardFileReply *reply)
{
	short			result;
	FILE *			stream;
	ScriptCmd *		scriptCmds;
	
	result     = noErr;
	stream     = nil;
	scriptCmds = nil;
	
	//if ( result == noErr )
		{
		stream = OpenScript( reply );
		if ( stream == nil )
			{
			result = -1;
			}
		}
	if ( result == noErr )
		{
		scriptCmds = ParseScript( stream );
		if ( scriptCmds == nil )
			{
			result = -1;
			}
		}
	if ( result == noErr )
		{
		ExecuteScript( scriptCmds );
		}
	
	if ( scriptCmds )
		{
		DisposeScript( scriptCmds );
		}
	if ( stream )
		{
		fclose( stream );
		}
}
示例#22
0
void QueueScriptController::Run()
{
	ExecuteScript(m_pScript);

	SetLogPrefix(NULL);

	if (m_bMarkBad)
	{
		DownloadQueue* pDownloadQueue = DownloadQueue::Lock();
		NZBInfo* pNZBInfo = pDownloadQueue->GetQueue()->Find(m_iID);
		if (pNZBInfo)
		{
			PrintMessage(Message::mkWarning, "Cancelling download and deleting %s", m_szNZBName);
			pNZBInfo->SetDeleteStatus(NZBInfo::dsBad);
			pDownloadQueue->EditEntry(m_iID, DownloadQueue::eaGroupDelete, 0, NULL);
		}
		DownloadQueue::Unlock();
	}

	g_pQueueScriptCoordinator->CheckQueue();
}
示例#23
0
void NZBScriptController::ExecuteScriptList(const char* szScriptList)
{
	for (ScriptConfig::Scripts::iterator it = g_pScriptConfig->GetScripts()->begin(); it != g_pScriptConfig->GetScripts()->end(); it++)
	{
		ScriptConfig::Script* pScript = *it;

		if (szScriptList && *szScriptList)
		{
			// split szScriptList into tokens
			Tokenizer tok(szScriptList, ",;");
			while (const char* szScriptName = tok.Next())
			{
				if (Util::SameFilename(szScriptName, pScript->GetName()))
				{
					ExecuteScript(pScript);
					break;
				}
			}
		}
	}
}
  //
  // LoadState
  //
  // Load state information
  //
  void Script::Manager::LoadState(FScope *scope)
  {
    FScope *sScope;

    while ((sScope = scope->NextFunction()) != NULL)
    {
      switch (sScope->NameCrc())
      {
        case 0x99FDB869: // "RecruitId"
          recruitId = StdLoad::TypeU32(sScope);
          break;

        case 0x8810AE3C: // "Script"
        {
          // Load construction data
          const char *name = StdLoad::TypeString(sScope);
          const char *config = StdLoad::TypeString(sScope);
          U32 weighting = StdLoad::TypeU32(sScope);
          U32 priority = StdLoad::TypeU32(sScope);

          // Create the script
          Script &script = ExecuteScript(name, config, weighting, priority);
          
          // Load the script state data
          script.LoadState(sScope);

          // Do we need to add to the squad tree
          if (SquadObj *squad = script.GetSquad(FALSE))
          {
            scriptsSquad.Add(squad->Id(), &script);
          }
          break;
        }
      }
    }
  }
PyObject* PythonObjIntegration::ExecuteScript(const char* moduleName, const char* functionName) {
	auto args = PyTuple_New(0);
	auto result = ExecuteScript(moduleName, functionName, args);
	Py_DECREF(args);
	return result;
}
示例#26
0
// general MXP error message routine - appends a newline, and also writes to debug 
void CMUSHclientDoc::MXP_error (const int iLevel, 
                                const long iMessageNumber, 
                                CString strMessage)
  {

char * sLevel [] = 
  {
  " ",
  "E", // error
  "W", // warning
  "I", // info
  "A", // all
  };

char * p = "?";

  // turn error level into a character
  if (iLevel >= 0 && iLevel < NUMITEMS (sLevel))
    p = sLevel [iLevel];

  if (iLevel == DBG_ERROR)
    {
    m_iMXPerrors++;
    MXP_Restore_Mode (); // an error cancels secure-once mode
    } // end of error

  // call script if required
  if (m_dispidOnMXP_Error != DISPID_UNKNOWN)
    {
    long nInvocationCount = 0;

    CString strType = "MXP Error";
    CString strReason =  "processing MXP error";

    if (GetScriptEngine () && GetScriptEngine ()->IsLua ())
      {
      list<double> nparams;
      list<string> sparams;
      nparams.push_back (iMessageNumber);  // error number
      nparams.push_back (m_LineList.GetCount ());  // line
      sparams.push_back (p);    // level (a character)
      sparams.push_back ((LPCTSTR) strMessage);    // message
      bool result;
      GetScriptEngine ()->ExecuteLua (m_dispidOnMXP_Error, 
                                     m_strOnMXP_Error, 
                                     eWorldAction,
                                     strType, 
                                     strReason, 
                                     nparams,
                                     sparams, 
                                     nInvocationCount,
                                     NULL, NULL, NULL,
                                     &result);
      if (result)
         return;
      }   // end of Lua
   else
       {
      // WARNING - arguments should appear in REVERSE order to what the sub expects them!

      enum
        {
        eErrorMessage,
        eLineNumber,
        eMessageNumber,
        eErrorLevel,
        eArgCount,     // this MUST be last
        };    

      COleVariant args [eArgCount];
      DISPPARAMS params = { args, NULL, eArgCount, 0 };

      args [eErrorLevel] = p;
      args [eMessageNumber] = iMessageNumber;
      args [eLineNumber] = (long) m_LineList.GetCount ();
      args [eErrorMessage] = strMessage;

      COleVariant result;

      ExecuteScript (m_dispidOnMXP_Error,  
                     m_strOnMXP_Error,
                     eWorldAction,
                     strType, 
                     strReason,
                     params, 
                     nInvocationCount,
                     &result); 

      // if the function returns a non-zero result, don't display the message
      if (result.vt != VT_EMPTY)
        {
        result.ChangeType (VT_I4);  // make a long
        if (result.vt == VT_I4)   // conversion successful
          if (result.lVal)        // return if non-zero
            return;
        }
      }  // not Lua
    }  // end of script callback wanted


  // tell each plugin about the error tag
  if (m_bPluginProcessesError)
    SendToAllPluginCallbacks (ON_PLUGIN_MXP_ERROR, 
                              CFormat ("%s,%ld,%ld,%s",
                              (LPCTSTR) p,
                              iMessageNumber,
                              (long) m_LineList.GetCount (),
                              (LPCTSTR) strMessage));


  CString strTitle = MXP_ERROR_WINDOW;
  strTitle += " - ";
  strTitle += m_mush_name;

  if (iLevel > m_iMXPdebugLevel)   // only show required level
    return;

  CString str = CFormat ("%s %5i: (%5i) %s%s",
                      p,     // error level
                      iMessageNumber,   // actual error number
                      m_LineList.GetCount (),  // which line
                      (LPCTSTR) strMessage,     // what message
                      ENDLINE);

  AppendToTheNotepad (strTitle, 
                      str,                 // start new line
                      false,   // append
                      eNotepadMXPdebug);
  }
示例#27
0
int AI1 (SOptions &Options)
	{
	CSocket theSocket;

	//	Help

	if (!Options.bNoLogo)
		{
		printf("AI1 1.0\n");
		printf("Copyright (c) 2011-2015 by Kronosaur Productions. All Rights Reserved.\n");
		printf("\n");
		}

	if (Options.bHelp)
		{
		printf("ai1 [options] [\"command\"]\n");
		printf("\n");
		printf("  /?              Help.\n");
		printf("  /h:{filespec}   Run HexeDocument.\n");
		printf("  /l              Lisp engine top-level.\n");
		printf("  /n              No logo.\n");
		printf("  /r:{filespec}   Run script file.\n");
		printf("  /s:{hostname}   Connect to given server.\n");
		printf("  /t              Time each command.\n");
		printf("  /z              Do not connect to server.\n");
		printf("  /1              V1 authentication.\n");
		printf("  /!              V1 auth to old server.\n");

		if (Options.bNoConnect)
			return 0;

		printf("\n");
		Options.sSingleCommand = CString("help");
		}

	//	Connect (if necessary)

	if (!ConnectToArcology(STR_ARC_CONSOLE, Options, &theSocket))
		return 1;

	//	If we have a HexeDocument, run it.

	if (!Options.sHexeDocument.IsEmpty())
		return ExecuteHexeDocument(Options);

	//	If we have a script file, defer to it.

	else if (!Options.sScriptFile.IsEmpty())
		return ExecuteScript(Options);

	//	PEM file

	else if (Options.bPEMFile)
		return ExecuteDebugPEMFile(Options.sSingleCommand);

	//	If we have a single command, send it

	else if (!Options.sSingleCommand.IsEmpty())
		{
		printf("%s\n", (LPSTR)Options.sSingleCommand);

		CString sOutput = Execute(theSocket, Options, Options.sSingleCommand);
		PrintUTF8(sOutput);
		printf("\n");

		return 0;
		}

	//	Otherwise, do an interactive loop

	else
		{
		while (true)
			{
			CString sInput = GetInputLine(STR_PROMPT);

			if (strEquals(sInput, STR_QUIT))
				break;

			else if (!sInput.IsEmpty())
				{
				CString sOutput = Execute(theSocket, Options, sInput);
				PrintUTF8(sOutput);
				printf("\n");
				}
			}

		return 0;
		}
	}
示例#28
0
bool CMUSHclientDoc::MXP_StartTagScript  (const CString & strName, 
                     const CString & strArguments,
                     CArgumentList & ArgumentList)
  {

  // don't make it too easy to dummy up AFK replies
  if (strName == "afk")
    return false;

  if (!SendToAllPluginCallbacks (ON_PLUGIN_MXP_OPENTAG, 
                                CFormat ("%s,%s",
                                (LPCTSTR) strName,
                                (LPCTSTR) strArguments)
                                ), true)
      return true;    


  // see if main script wants to do anything
  if (m_dispidOnMXP_OpenTag == DISPID_UNKNOWN)
    return false;

  long nInvocationCount = 0;
  long iCount = ArgumentList.GetCount ();

  CString strType = "MXP open tag";
  CString strReason =  TFormat ("opening MXP tag %s", (LPCTSTR) strName);

  if (GetScriptEngine () && GetScriptEngine ()->IsLua ())
    {
    list<double> nparams;
    list<string> sparams;
    sparams.push_back ((LPCTSTR) strName);    // name of tag
    sparams.push_back ((LPCTSTR) strArguments);  // all arguments

    map <string, string> table;

    CArgument * pArgument;
    POSITION pos;

    // put the arguments into the table

    for (iCount = 0, pos = ArgumentList.GetHeadPosition (); pos; iCount++)
      {
      pArgument = ArgumentList.GetNext (pos);
      CString strName = pArgument->strName;

      // empty ones we will put there by position
      if (strName.IsEmpty ())
        strName = CFormat ("%i",
                      pArgument->iPosition);
      
      table [(LPCTSTR) strName] = pArgument->strValue;
      }      // end of looping through each argument

    bool result;
    GetScriptEngine ()->ExecuteLua (m_dispidOnMXP_OpenTag, 
                                   m_strOnMXP_OpenTag, 
                                   eWorldAction,
                                   strType, 
                                   strReason, 
                                   nparams,
                                   sparams, 
                                   nInvocationCount,
                                   NULL,
                                   &table,
                                   NULL,
                                   &result);
    return result;
    }   // end of Lua

  COleSafeArray sa;   // for wildcard list

  if (iCount) // cannot create empty array dimension
    {
    sa.CreateOneDim (VT_VARIANT, iCount);

    CArgument * pArgument;
    POSITION pos;

    // put the arguments into the array

    for (iCount = 0, pos = ArgumentList.GetHeadPosition (); pos; iCount++)
      {
      pArgument = ArgumentList.GetNext (pos);

      // the array must be a bloody array of variants, or VBscript kicks up
      COleVariant v;
      
      // empty ones we will put there by position
      if (pArgument->strName.IsEmpty ())
        v = CFormat ("%i=%s",
                      pArgument->iPosition,
                      (LPCTSTR) pArgument->strValue);
      else
        v = CFormat ("%s=%s",
                      (LPCTSTR) pArgument->strName,
                      (LPCTSTR) pArgument->strValue);
      sa.PutElement (&iCount, &v);
      }      // end of looping through each argument
    } // end of having at least one

  // WARNING - arguments should appear in REVERSE order to what the sub expects them!

  enum
    {
    eArgumentArray,
    eArguments,
    eTagName,
    eArgCount,     // this MUST be last
    };    

  COleVariant args [eArgCount];
  DISPPARAMS params = { args, NULL, eArgCount, 0 };

  args [eTagName] = strName;
  args [eArguments] = strArguments;
  args [eArgumentArray] = sa;

  COleVariant result;

  ExecuteScript (m_dispidOnMXP_OpenTag,  
                 m_strOnMXP_OpenTag,
                 eWorldAction,
                 strType, 
                 strReason,
                 params, 
                 nInvocationCount,
                 &result); 

  // if the function returns a non-zero result, don't go ahead
  if (result.vt != VT_EMPTY)
    {
    result.ChangeType (VT_I4);  // make a long
    if (result.vt == VT_I4)   // conversion successful
      if (result.lVal)        // return if non-zero
        return true;
    }

  return false;
  } // end of CMUSHclientDoc::MXP_StartTagScript 
示例#29
0
文件: window.cpp 项目: galek/gamegui
void base_window::draw(const point& offset, const Rect& clip)
{
	if(m_visible)
	{
		if(m_area.getWidth() < 1.f)
			return;

		Rect destrect(m_area);
		destrect.offset(offset);
		Rect cliprect(destrect);
		cliprect = cliprect.getIntersection(clip);

		//if (m_invalidated)
		{
			m_system.getRenderer().startCaptureForCache(this);


			render(destrect, cliprect); // render self first
			m_system.getRenderer().endCaptureForCache(this);		
			m_invalidated = false;
		}
		//else 
		//{
		//	//if (!m_system.getRenderer().isExistInCache(this))
		//	//{
		//	//	m_system.getRenderer().startCaptureForCache(this);			
		//	//	if(m_customDraw && !m_drawhandler.empty())
		//	//	{
		//	//		EventArgs a;
		//	//		a.name = "On_Draw";
		//	//		luabind::globals (m_system.getScriptSystem().LuaState())["eventArgs"] = &a;
		//	//		ExecuteScript(a.name, m_drawhandler);
		//	//		luabind::globals (m_system.getScriptSystem().LuaState())["eventArgs"] = 0;
		//	//	}

		//	//	render(destrect, cliprect); // render self first
		//	//	m_system.getRenderer().endCaptureForCache(this);
		//	//}
		//	//else 
		//		m_system.getRenderer().drawFromCache(this);
		//}

		child_iter i = m_children.begin();
		child_iter end = m_children.end();
		while(i != end)
		{
			(*i)->draw(destrect.getPosition(), cliprect);
			++i;
		}

		if (m_customDraw && !m_drawhandler.empty())
		{
			EventArgs a;
			a.name = "On_Draw";

			luabind::object globals = luabind::globals(m_system.getScriptSystem().getLuaState());

			globals["eventArgs"] = &a;
			ExecuteScript(a.name, m_drawhandler);
			globals["eventArgs"] = 0;
		}

		// теперь скажем, что тут коллбак при отрисовке нужно сделать
		CallAfterRenderCallback(destrect,cliprect);
	}	
}
示例#30
0
void CMUSHclientDoc::CheckTimerList (CTimerMap & TimerMap)
  {
CTimer * timer_item;
CString strTimerName;
CmcDateTime tNow = CmcDateTime::GetTimeNow();
CmcDateTimeSpan tsOneDay (1, 0, 0, 0);

// check for deleted chat sessions

  for (POSITION chatpos = m_ChatList.GetHeadPosition (); chatpos; )
    {
    POSITION oldpos = chatpos;
    CChatSocket * pSocket = m_ChatList.GetNext (chatpos);
    if (pSocket->m_bDeleteMe)
      {
      m_ChatList.RemoveAt (oldpos);
      delete pSocket;
      break;    // list is no longer valid
      }
    }

  set <string> firedTimersList;
  POSITION pos;

// iterate through all timers for this document - first build list of them

  for (pos = TimerMap.GetStartPosition(); pos; )
    {


    TimerMap.GetNextAssoc (pos, strTimerName, timer_item);

    if (!timer_item->bEnabled)    // ignore un-enabled timers
      continue;

    // no timer activity whilst closed or in the middle of connecting, or if not enabled

    if (!timer_item->bActiveWhenClosed)
      if (m_iConnectPhase != eConnectConnectedToMud)
        continue;

    // if not ready to fire yet, ignore it

    if (timer_item->tFireTime > tNow)
      continue;

    firedTimersList.insert ((LPCTSTR) strTimerName);       // add to list of fired timers
    }


  // now process list, checking timer still exists in case a script deleted one
  // see: http://www.gammon.com.au/forum/?id=10358

  for (set <string>::iterator it = firedTimersList.begin ();
       it != firedTimersList.end ();
       it++)
    {
    // get next fired timer from list
    strTimerName = it->c_str ();

    // check still exists, get pointer if so
    if (!TimerMap.Lookup (strTimerName, timer_item))
      continue;

    timer_item->nMatched++;   // count timer matches
    timer_item->tWhenFired = tNow;  // when it fired

    m_iTimersFiredCount++;
    m_iTimersFiredThisSessionCount++;

//    TRACE1 ("Fired at = %10.8f\n", timer_item->tWhenFired.m_dt);

    if (timer_item->strLabel.IsEmpty ())
      Trace ("Fired unlabelled timer ");
    else
      Trace ("Fired timer %s", (LPCTSTR) timer_item->strLabel);

//    TRACE1 ("Fire time = %10.8f\n", timer_item->tFireTime.m_dt);

// update fire time - before calling the script, in case it takes a long time

    if (timer_item->iType == CTimer::eAtTime)
      timer_item->tFireTime += tsOneDay;
    else
      timer_item->tFireTime += CmcDateTimeSpan (0,    // add the interval
                                          timer_item->iEveryHour, 
                                          timer_item->iEveryMinute, 
                                          timer_item->fEverySecond);

    // in case clock changes or some such thing, make sure timer will be due to
    // fire in the future, not the past, or it might go mad and keep firing

    if (timer_item->tFireTime <= tNow)
      ResetOneTimer (timer_item);

    // if one-shot, disable it, so if the timer routine finds it again while
    // it is still executing (eg. due to a syntax error dialog box) then
    // it won't fire again.

    if (timer_item->bOneShot)
      timer_item->bEnabled = false;


// send timer message, if this timer list is "active"

    CString strExtraOutput;

    timer_item->bExecutingScript = true;     // cannot be deleted now
    m_iCurrentActionSource = eTimerFired;
    SendTo (timer_item->iSendTo, 
            timer_item->strContents, 
            timer_item->bOmitFromOutput, // omit from output
            timer_item->bOmitFromLog,    // omit from log
            TFormat ("Timer: %s", (LPCTSTR) timer_item->strLabel),
            timer_item->strVariable,
            strExtraOutput
            );
    m_iCurrentActionSource = eUnknownActionSource;
    timer_item->bExecutingScript = false;     // can be deleted now

    // display any stuff sent to output window

    if (!strExtraOutput.IsEmpty ())
       DisplayMsg (strExtraOutput, strExtraOutput.GetLength (), COMMENT);

// invoke script subroutine, if any

    if (!timer_item->strProcedure.IsEmpty ())
      if (CheckScriptingAvailable ("Timer", timer_item->dispid, timer_item->strProcedure))
         continue;

    if (timer_item->dispid != DISPID_UNKNOWN)        // if we have a dispatch id
      {
      
      CString strType = "timer";
      CString strReason =  TFormat ("processing timer \"%s\"", 
                                    (LPCTSTR) timer_item->strLabel);

      // get unlabelled timer's internal name
      const char * pLabel = timer_item->strLabel;
      if (pLabel [0] == 0)
        pLabel = GetTimerRevMap () [timer_item].c_str ();

      if (GetScriptEngine () && GetScriptEngine ()->IsLua ())
        {
        list<double> nparams;
        list<string> sparams;
        sparams.push_back (pLabel);
        timer_item->bExecutingScript = true;     // cannot be deleted now
        GetScriptEngine ()->ExecuteLua (timer_item->dispid, 
                                       timer_item->strProcedure, 
                                       eTimerFired,
                                       strType, 
                                       strReason,
                                       nparams,
                                       sparams, 
                                       timer_item->nInvocationCount);
        timer_item->bExecutingScript = false;     // can be deleted now
        }   // end of Lua
      else
        {
        // prepare for the arguments (so far, 1 which is the timer name)
  
        // WARNING - arguments should appear in REVERSE order to what the sub expects them!

        enum
          {
          eTimerName,
          eArgCount,     // this MUST be last
          };    

        COleVariant args [eArgCount];
        DISPPARAMS params = { args, NULL, eArgCount, 0 };

  //      args [eTimerName] = strTimerName;
        args [eTimerName] = pLabel;
        timer_item->bExecutingScript = true;     // cannot be deleted now
        ExecuteScript (timer_item->dispid,  
                       timer_item->strProcedure,
                       eTimerFired,
                       strType, 
                       strReason,
                       params, 
                       timer_item->nInvocationCount);
        timer_item->bExecutingScript = false;     // can be deleted now

        } // not Lua
      }     // end of having a dispatch ID


    // If they passed the wrong arguments to the timer routine, the dialog box
    // might appear, and the timer be deleted, before we get a chance to
    // do this code, in which case the timer has gone.
    // Just get it again to be sure ...  [#430]

    if (!TimerMap.Lookup (strTimerName, timer_item))
      return;

// if one-shot timer, delete from list

    if (timer_item->bOneShot)
      {
      TimerMap.RemoveKey (strTimerName);
      delete timer_item;
      SortTimers ();
      }
    }   // end of processing each timer

  } // end of CMUSHclientDoc::CheckTimerMap