/** * Creates the job-script for the sun grid engine. * @return */ bool ClusterNetworkInSimEvaluationMethod::createJobScript() { TRACE("EvolutionManager::createJobScript"); bool ok = true; mJobScriptContent = ""; QTextStream script(&mJobScriptContent, QIODevice::WriteOnly | QIODevice::Truncate); QString applicationBinary = mApplication->get(); applicationBinary = applicationBinary.replace("$HOME$", QDir::currentPath()); QString applicationCall = mApplication->get() + " " + mApplicationFixedParameters->get(); applicationCall = applicationCall.replace("$HOME$", QDir::currentPath()); script << "#!" << mShellBinary->get().toStdString().c_str() << endl << endl; script << "TASK_ID=$1" << endl; script << "ARGUMENT_POSTFIX=" << endl << endl; script << "if [ \"${SGE_TASK_ID}\" != \"undefined\" -a \"x${SGE_TASK_ID}\" != \"x\" ]" << endl; script << "then TASK_ID=$SGE_TASK_ID" << endl; script << "else" << endl; script << " if [ $# -eq 0 ]" << endl; script << " then ARGUMENT_POSTFIX=\"-gui -test -toggle\"" << endl; script << " TASK_ID=1" << endl; script << " fi" << endl << endl; script << "fi" << endl; script << "EVAL_DIR=" << mEvalCurrentDirectory << "/$TASK_ID" << endl << endl; script << "if [ \"x$TASK_ID\" = \"x\" ]" << endl; script << "then exit 1" << endl; script << "fi" << endl << endl; script << "i=1" << endl; script << "MAX_RETRIES=10" << endl; script << "while [ ! -d $EVAL_DIR -a $i -le $MAX_RETRIES ]" << endl; script << "do" << endl; script << "#Wait for one second" << endl; script << "sleep 1" << endl; script << "i='expr $i + 1'" << endl; script << "done" << endl; script << "if [ ! -d $EVAL_DIR ]" << endl; script << "then exit 1" << endl; script << "fi" << endl << endl; script << "if [ $# -gt 0 ]" << endl; script << "then shift" << endl; script << "fi" << endl; script << "cd $EVAL_DIR" << endl; if(mIncludeBacktraceCodeInScripts->get()) { script << "ulimit -c unlimited" << endl; } script << applicationCall << mApplicationParameter << " -nogui -disableLogging $ARGUMENT_POSTFIX $* " << endl << endl; if(mIncludeBacktraceCodeInScripts->get()) { script << "#This segment creates a backtrace of a core dump when the application crashes." << endl; script << "if [ -f core ]" << endl; script << "then" << endl; script << " echo " << endl << " echo \"There was an error during execution.\"" << endl; script << " echo \"Creating backtrace file from dumped core.\"" << endl; script << " echo " << endl << " echo \"Please wait...\"" << endl << " echo" << endl << endl; script << " gdb " << applicationBinary << " --core core --batch --quiet -ex \"thread apply all bt full\" -ex \"quit\" >> backtrace.txt" << endl; script << " rm core;" << endl; script << "fi" << endl; } script << "exit 0" << endl; return ok; }
bool CompileFile(const std::string &inputFilePath, const std::string &outputFilePath) { bool result = false; std::string ofp; if (!outputFilePath.empty()) { ofp = outputFilePath; } else { ofp = RemoveFileExt(inputFilePath) + BYTE_CODE_FILE_EXT; } if (!JS_Init()) return false; std::cout << "Input file: " << inputFilePath << std::endl; JSRuntime * runtime = JS_NewRuntime(10 * 1024 * 1024, JS_NO_HELPER_THREADS); JSContext *cx = JS_NewContext(runtime, 10240); JS_SetOptions(cx, JSOPTION_TYPE_INFERENCE); JS::CompartmentOptions options; options.setVersion(JSVERSION_LATEST); JS::RootedObject global(cx, JS_NewGlobalObject(cx, &GlobalClass, NULL, JS::DontFireOnNewGlobalHook, options)); JS_SetErrorReporter(cx, &ReportError); { JSAutoCompartment ac(cx, global); if (JS_InitStandardClasses(cx, global)) { JS_InitReflect(cx, global); JS_FireOnNewGlobalObject(cx, global); JS::CompileOptions options(cx); options.setUTF8(true); options.setSourcePolicy(JS::CompileOptions::NO_SOURCE); std::cout << "Compiling ..." << std::endl; JS::RootedScript script(cx, JS::Compile(cx, global, options, inputFilePath.c_str())); if (script) { void *data = NULL; uint32_t length = 0; std::cout << "Encoding ..." << std::endl; data = JS_EncodeScript(cx, script, &length); if (data) { if (WriteFile(ofp, data, length)) { std::cout << "Done! " << "Output file: " << ofp << std::endl; result = true; } } } else { std::cout << "Compiled " << inputFilePath << " fails!" << std::endl; } } else { std::cout << "JS_InitStandardClasses failed! " << std::endl; } } if (cx) { JS_DestroyContext(cx); cx = NULL; } if (runtime) { JS_DestroyRuntime(runtime); runtime = NULL; } JS_ShutDown(); return result; }
//! (koshi) don't delete commented things please, they might be need in the future and i'm lazy void IBattle::GetBattleFromScript( bool loadmapmod ) { BattleOptions opts; std::stringstream ss (GetScript()); LSL::TDF::PDataList script( LSL::TDF::ParseTDF(ss) ); LSL::TDF::PDataList replayNode ( script->Find("GAME") ); if ( replayNode.ok() ) { std::string modname = replayNode->GetString("GameType"); std::string modhash = replayNode->GetString("ModHash"); if ( !modhash.empty() ) modhash = STD_STRING(MakeHashUnsigned(TowxString(modhash))); SetHostMod( modname, modhash ); //don't have the maphash, what to do? //ui download function works with mapname if hash is empty, so works for now std::string mapname = replayNode->GetString("MapName"); std::string maphash = replayNode->GetString("MapHash"); if ( !maphash.empty() ) maphash = STD_STRING(MakeHashUnsigned(TowxString(maphash))); SetHostMap( mapname, maphash ); // opts.ip = replayNode->GetString( _T("HostIP") ); // opts.port = replayNode->GetInt ( _T("HostPort"), DEFAULT_EXTERNAL_UDP_SOURCE_PORT ); opts.spectators = 0; int playernum = replayNode->GetInt("NumPlayers", 0); int usersnum = replayNode->GetInt("NumUsers", 0); if ( usersnum > 0 ) playernum = usersnum; // int allynum = replayNode->GetInt ( _T("NumAllyTeams"), 1); // int teamnum = replayNode->GetInt ( _T("NumTeams"), 1); LSL::StringVector sides; if ( loadmapmod ) { sides = LSL::usync().GetSides(modname); } IBattle::TeamVec parsed_teams = GetParsedTeamsVec(); IBattle::AllyVec parsed_allies = GetParsedAlliesVec(); //[PLAYERX] sections for ( int i = 0; i < playernum ; ++i ) { LSL::TDF::PDataList player ( replayNode->Find(stdprintf("PLAYER%d", i))); LSL::TDF::PDataList bot ( replayNode->Find(stdprintf("AI%d", i ))); if ( player.ok() || bot.ok() ) { if ( bot.ok() ) player = bot; User user(player->GetString("Name"), boost::to_upper_copy(player->GetString("CountryCode")), 0); UserBattleStatus& status = user.BattleStatus(); status.isfromdemo = true; status.spectator = player->GetInt("Spectator", 0 ); opts.spectators += user.BattleStatus().spectator; status.team = player->GetInt("Team"); if ( !status.spectator ) { PlayerJoinedTeam( status.team ); } status.sync = true; status.ready = true; if ( status.spectator ) m_opts.spectators++; else { if ( !bot.ok() ) { if ( status.ready) m_players_ready++; if ( status.sync ) m_players_sync++; if ( status.sync && status.ready ) m_players_ok++; } } //! (koshi) changed this from ServerRankContainer to RankContainer user.Status().rank = (UserStatus::RankContainer)player->GetInt("Rank", -1 ); if ( bot.ok() ) { status.aishortname = bot->GetString("ShortName"); status.aiversion = bot->GetString("Version"); int ownerindex = bot->GetInt("Host"); LSL::TDF::PDataList aiowner (replayNode->Find(stdprintf("PLAYER%d", ownerindex))); if ( aiowner.ok() ) { status.owner = aiowner->GetString("Name"); } } IBattle::TeamInfoContainer teaminfos = parsed_teams[user.BattleStatus().team]; if ( !teaminfos.exist ) { LSL::TDF::PDataList team( replayNode->Find( stdprintf("TEAM%d", user.BattleStatus().team) )); if ( team.ok() ) { teaminfos.exist = true; teaminfos.TeamLeader = team->GetInt("TeamLeader", 0 ); teaminfos.StartPosX = team->GetInt("StartPosX", -1 ); teaminfos.StartPosY = team->GetInt("StartPosY", -1 ); teaminfos.AllyTeam = team->GetInt("AllyTeam", 0 ); teaminfos.RGBColor = GetColorFromFloatStrng(TowxString(team->GetString("RGBColor"))); teaminfos.SideName = team->GetString("Side", ""); teaminfos.Handicap = team->GetInt("Handicap", 0 ); const int sidepos = LSL::Util::IndexInSequence(sides, teaminfos.SideName); teaminfos.SideNum = sidepos; parsed_teams[ user.BattleStatus().team ] = teaminfos; } } if ( teaminfos.exist ) { status.ally = teaminfos.AllyTeam; status.pos.x = teaminfos.StartPosX; status.pos.y = teaminfos.StartPosY; status.colour = teaminfos.RGBColor; status.handicap = teaminfos.Handicap; if ( !status.spectator ) { PlayerJoinedAlly( status.ally ); } if ( teaminfos.SideNum >= 0 ) status.side = teaminfos.SideNum; IBattle::AllyInfoContainer allyinfos = parsed_allies[user.BattleStatus().ally]; if ( !allyinfos.exist ) { LSL::TDF::PDataList ally( replayNode->Find(stdprintf("ALLYTEAM%d", user.BattleStatus().ally) ) ); if ( ally.ok() ) { allyinfos.exist = true; allyinfos.NumAllies = ally->GetInt("NumAllies", 0 ); allyinfos.StartRectLeft = ally->GetInt("StartRectLeft", 0 ); allyinfos.StartRectTop = ally->GetInt("StartRectTop", 0 ); allyinfos.StartRectRight = ally->GetInt("StartRectRight", 0 ); allyinfos.StartRectBottom = ally->GetInt("StartRectBottom", 0 ); parsed_allies[ user.BattleStatus().ally ] = allyinfos; AddStartRect( user.BattleStatus().ally, allyinfos.StartRectTop, allyinfos.StartRectTop, allyinfos.StartRectRight, allyinfos.StartRectBottom ); } } } AddUserFromDemo( user ); } } SetParsedTeamsVec( parsed_teams ); SetParsedAlliesVec( parsed_allies ); //MMoptions, this'll fail unless loading map/mod into wrapper first if ( loadmapmod ) { LoadScriptMMOpts("mapoptions", replayNode ); LoadScriptMMOpts("modoptions", replayNode ); } opts.maxplayers = playernum ; } SetBattleOptions( opts ); }
Director::Director(const string& scriptName, unsigned int playerCount, bool overRide) { isOverride = overRide; maximum = 0; ifstream infile(scriptName); if (!infile.is_open()) { string error = "[ERROR]: Open file fail: " + scriptName; throw CodeException(FAIL_FILE_OPEN, error.c_str()); } string currentLine; bool followingPL; int scriptCounter = 1; int lastPartDefCount = 0; regex re("^\\[scene\\][\\s]([\\w\\s]*)$"); smatch sm; regex re_config("^[\\s]*(.*.txt)[\\s]*$"); smatch sm_config; regex re_part("^[\\s]*([\\w]+)[\\s]+(.*.txt)[\\s]*$"); smatch sm_part; while (getline(infile, currentLine)) { // scan for scene titles if (regex_match(currentLine, sm, re)) { titles.push_back(sm[1]); followingPL = false; } else { // scan for scene fragment config files if (regex_match(currentLine, sm_config, re_config)) { scripts[scriptCounter] = script(); if (!followingPL) { followingPL = true; } else { titles.push_back(string()); } ifstream configFile(sm_config[1]); int partDefinitionLineCount = 0; if (!configFile.is_open()) { string temp = sm_config[1]; string error = "[ERROR]: Open file fail: " + temp; throw CodeException(FAIL_FILE_OPEN, error.c_str()); } string partDefinitionLine; while (getline(configFile, partDefinitionLine)) { // scan for part definition files if (regex_match(partDefinitionLine, sm_part, re_part)) { partDefinitionLineCount++; scripts[scriptCounter][sm_part[1]] = sm_part[2]; } } scriptCounter++; if (!isOverride) { int consecutiveSum = partDefinitionLineCount + lastPartDefCount; lastPartDefCount = partDefinitionLineCount; maximum = maximum > consecutiveSum ? maximum : consecutiveSum; } } } } //finish reading script try { play = playPtr(new Play(titles, finished.get_future())); } catch (exception& e) { throw (BAD_ALLOCATION,e); } // check the override option if (!isOverride) { maximum = maximum > (int)playerCount ? maximum : (int)playerCount; } else { maximum = (int)playerCount; } for (int i = 0; i < maximum; i++) { try { players.push_back(playerPtr(new Player(*play))); } catch (exception& e) { throw (BAD_ALLOCATION, e); } players[i]->activate(); } }
void RunScript(char * sname, int ObjID) { CExoString script(sname); g_pVirtualMachine->RunScript(&script, ObjID, 1); }
unsigned CachedScript::scriptHash() { if (m_decodingState == NeverDecoded) script(); return m_scriptHash; }
void State::updateObject(dur elapsedTime) { // Store current map in case of switch GameMap* current_map = m_map; if(!enabled) { return; } assert(engine() != NULL); // Process input controller if(engine()->hardware()) { processInput(); } if(!frameCounter) { return; } else { if(frameCounter > 0) { frameCounter--; } } // Run scripts if(script()->isRunning()) { script()->framestep(); } // Update map if(current_map != NULL) { // Make the cameraman work if(cameraman) { cameraman->update(elapsedTime); current_map->setPosition(cameraman->getCameraPosition()); } // Center map if(camTarget) { int targetX; int targetY; int camX; int camY; int curX; int curY; int localMaxCamSpeed = maxCamSpeed * elapsedTime; // Compute actual target coordinates if(camSecondaryTarget) { targetX = (camTarget->getX() + camSecondaryTarget->getX()) / 2; targetY = (camTarget->getY() + camSecondaryTarget->getY()) / 2; } else { targetX = camTarget->getX(); targetY = camTarget->getY(); } // Smooth object switching if(camSwitching) { camX = (-current_map->getX() * 3 + targetX) / 4; camY = (-current_map->getY() * 3 + targetY) / 4; curX = current_map->getX(); curY = current_map->getY(); } else { camX = targetX; camY = targetY; curX = camX; curY = camY; } // Limit camera speed if(camX + current_map->getX() > localMaxCamSpeed) { camX = -current_map->getX() + localMaxCamSpeed; } else if(-current_map->getX() - camX > localMaxCamSpeed) { camX = -current_map->getX() - localMaxCamSpeed; } if(camY + current_map->getY() > localMaxCamSpeed) { camY = -current_map->getY() + localMaxCamSpeed; } else if(-current_map->getY() - camY > localMaxCamSpeed) { camY = -current_map->getY() - localMaxCamSpeed; } // set camera position current_map->setPosition(-camX, -camY); // test if object switching is finished if(camSwitching) { if(abs(camX - targetX) < 5 && abs(camY - targetY) < 5) { camSwitching = false; } else if((curX == current_map->getX()) && (curY == current_map->getY())) { camSwitching = false; } } } // Update map current_map->update(elapsedTime); // Update mouse cursor #ifdef MOUSE_SUPPORT if(mouseCursor) { Collidable* current_mouse = mouseCursor; current_mouse->update(elapsedTime); Collision c = current_mouse->hitBy(current_map); if(c.collided()) { current_map->signal(current_mouse, MOUSE_MOVE, 0); } if(m_hud) { c = current_mouse->hitBy(m_hud); if(c.collided()) { m_hud->signal(current_mouse, MOUSE_MOVE, 0); } } } #endif } // Update hud if(m_hud != NULL) { m_hud->update(elapsedTime); } }
#include "parse.h" wifstream Parse::infile = wifstream(); script Parse::s = script(); void Parse::init() { infile.open(L"test\\start.txt"); infile.imbue(locale(".936")); } void Parse::load_the_txt(wstring filename) { infile.close(); infile.open(filename.c_str()); infile.imbue(locale(".936")); } script Parse::read_next_script() { xiayuWString temp; temp = parse(); if (temp == L"<drawbg>") { s.kind = PARSE::drawbg; temp = parse(); s.file = temp; temp = parse(); s.x = temp; temp = parse();
bool osScriptInit(){ #ifndef XSICONVERT script().run("osClock=os.clock"); LuaType* w=script().add("os"); script().add("folderExists",&luaFolderExists,w); script().add("fileExists",&luaFileExists,w); script().add("mkdir",&luaMkdir,w); script().add("folderContents",&luaFolderContents,w); script().add("exit",&luaExit,w); script().add("execute",&luaExecute,w); script().add("time",&luaTime,w); script().add("error",&luaError,w); script().add("name",&osName,w); script().add("version",&osVersion,w); #ifdef _WIN32 OSVERSIONINFO m_osinfo; m_osinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&m_osinfo); DWORD dwMinorVersion = m_osinfo.dwMinorVersion; DWORD dwMajorVersion = m_osinfo.dwMajorVersion; if(dwMajorVersion==5 && dwMinorVersion==1){ osVersion="xp"; }else if(dwMajorVersion==5 && dwMinorVersion==0){ osVersion="2000"; }else if(dwMajorVersion==4 && dwMinorVersion==0){ osVersion="nt"; }else if(dwMajorVersion==4 && dwMinorVersion==90){ osVersion="me"; }else if(dwMajorVersion==4 && dwMinorVersion==10){ osVersion="98"; }else if(dwMajorVersion==4 && dwMinorVersion==0){ osVersion="95"; }else{ osVersion=String(dwMajorVersion)+String(".")+String(dwMinorVersion); } logs().main.write("OS:Windows"); logs().main.write(String("MAJORVERSION:")+dwMajorVersion); logs().main.write(String("MINORVERSION:")+dwMinorVersion); logs().main.write("VERSION:"+osVersion); #elif LINUX logs().main.write("OS:Linux"); #else SInt32 MacVersion; logs().main.write("OS:Mac"); if (Gestalt(gestaltSystemVersion, &MacVersion) == noErr){ if(MacVersion<0x1010){ osVersion="10.0"; }else if(MacVersion<0x1020){ osVersion="10.1"; }else if(MacVersion<0x1030){ osVersion="10.2"; }else if(MacVersion<0x1040){ osVersion="10.3"; }else if(MacVersion<0x1050){ osVersion="10.4"; }else if(MacVersion<0x1060){ osVersion="10.5"; }else if(MacVersion<0x1070){ osVersion="10.6"; } } logs().main.write("VERSION:"+osVersion); #endif script().run("os.clock=osClock"); script().run("osClock=nil"); #endif return true; }
static int luaTrace(lua_State *L){ Array<LuaType> args=script().getArgs(L); if(args.size()!=3){ console().write("Trace Error: bad arguments"); return 0; } FloatVector3d from; FloatVector3d velocity; FloatVector3d rad; if(args[0].type==SCRIPT_TABLE){ if(args[0].children.size()==3){ for(int i=0; i<3; i++){ if(args[0].children[i].name=="x"){ from.x=args[0].children[i].value.ds; }else if(args[0].children[i].name=="y"){ from.y=args[0].children[i].value.ds; }else if(args[0].children[i].name=="z"){ from.z=args[0].children[i].value.ds; } } }else{ console().write("Trace Error: bad arguments, from wrong size"); return 0; } }else{ console().write("Trace Error: bad arguments, from must be a vector3d"); return 0; } if(args[1].type==SCRIPT_TABLE){ if(args[1].children.size()==3){ for(int i=0; i<3; i++){ if(args[1].children[i].name=="x"){ velocity.x=args[1].children[i].value.ds; }else if(args[1].children[i].name=="y"){ velocity.y=args[1].children[i].value.ds; }else if(args[1].children[i].name=="z"){ velocity.z=args[1].children[i].value.ds; } } }else{ console().write("Trace Error: bad arguments, velocity vector wrong size"); return 0; } }else{ console().write("Trace Error: bad arguments, velocity must be vector3d"); return 0; } if(args[2].type==SCRIPT_TABLE){ if(args[2].children.size()==3){ for(int i=0; i<3; i++){ if(args[2].children[i].name=="x"){ rad.x=args[2].children[i].value.ds; }else if(args[2].children[i].name=="y"){ rad.y=args[2].children[i].value.ds; }else if(args[2].children[i].name=="z"){ rad.z=args[2].children[i].value.ds; } } }else{ console().write("Trace Error: bad arguments, radius wrong number of arguments"); return 0; } }else{ console().write("Trace Error: bad arguments, radius vector must be vector3d"); return 0; } FloatVector3d oor=level->camera->ellipsoidRadius; level->camera->ellipsoidRadius=rad; FloatVector3d f=level->camera->GetPosition(from,velocity); level->camera->ellipsoidRadius=oor; script().resultTable(L); script().result(L,"x",f.x); script().result(L,"y",f.y); script().result(L,"z",f.z); return 1; }
void Model::load(const std::string & file) { LuaScript script(file); loadImage(script); loadTexturePack(script); setUp(); }
int wdFindElementsByCss(WebDriver* driver, WebElement* element, const wchar_t* selector, ElementCollection** out) { *out = NULL; if (!driver || !driver->ie) { return ENOSUCHDRIVER; } try { clock_t end = endAt(driver); int result = EUNHANDLEDERROR; do { // Call it std::wstring script(L"(function() { return function(){"); for (int i = 0; SIZZLE[i]; i++) { script += SIZZLE[i]; script += L"\n"; } script += L"var root = arguments[1] ? arguments[1] : document.documentElement;"; script += L"if (root['querySelectorAll']) { return root.querySelectorAll(arguments[0]); } "; script += L"var results = []; Sizzle(arguments[0], root, results);"; script += L"return results;"; script += L"};})();"; // Call it ScriptArgs* args; result = wdNewScriptArgs(&args, 2); if (result != SUCCESS) { wdFreeScriptArgs(args); continue; } result = wdAddStringScriptArg(args, selector); if (result != SUCCESS) { wdFreeScriptArgs(args); continue; } result = wdAddElementScriptArg(args, element); if (result != SUCCESS) { wdFreeScriptArgs(args); continue; } ScriptResult* queryResult; result = wdExecuteScript(driver, script.c_str(), args, &queryResult); wdFreeScriptArgs(args); // And be done if (result != SUCCESS) { wdFreeScriptResult(queryResult); return result; } ElementCollection* elements = new ElementCollection(); elements->elements = new std::vector<ElementWrapper*>(); int length; result = wdGetArrayLengthScriptResult(driver, queryResult, &length); if (result != SUCCESS) { wdFreeScriptResult(queryResult); return result; } for (long i = 0; i < length; i++) { ScriptResult* getElemRes; wdGetArrayItemFromScriptResult(driver, queryResult, i, &getElemRes); WebElement* e; wdGetElementScriptResult(getElemRes, driver, &e); elements->elements->push_back(e->element); e->element = NULL; delete e; } wdFreeScriptResult(queryResult); *out = elements; return SUCCESS; } while (clock() < end); return result; } END_TRY; }
int wdFindElementByCss(WebDriver* driver, WebElement* element, const wchar_t* selector, WebElement** out) { *out = NULL; if (!driver || !driver->ie) { return ENOSUCHDRIVER; } try { clock_t end = endAt(driver); int result = ENOSUCHELEMENT; do { std::wstring script(L"(function() { return function(){"); for (int i = 0; SIZZLE[i]; i++) { script += SIZZLE[i]; script += L"\n"; } script += L"var root = arguments[1] ? arguments[1] : document.documentElement;"; script += L"if (root['querySelector']) { return root.querySelector(arguments[0]); } "; script += L"var results = []; Sizzle(arguments[0], root, results);"; script += L"return results.length > 0 ? results[0] : null;"; script += L"};})();"; // Call it ScriptArgs* args; result = wdNewScriptArgs(&args, 2); if (result != SUCCESS) { wdFreeScriptArgs(args); continue; } result = wdAddStringScriptArg(args, selector); if (result != SUCCESS) { wdFreeScriptArgs(args); continue; } if (element) { result = wdAddElementScriptArg(args, element); } if (result != SUCCESS) { wdFreeScriptArgs(args); continue; } ScriptResult* queryResult; result = wdExecuteScript(driver, script.c_str(), args, &queryResult); wdFreeScriptArgs(args); // And be done if (result == SUCCESS) { int type = 0; result = wdGetScriptResultType(driver, queryResult, &type); if (type != TYPE_EMPTY) { result = wdGetElementScriptResult(queryResult, driver, out); } else { result = ENOSUCHELEMENT; wdFreeScriptResult(queryResult); continue; } } wdFreeScriptResult(queryResult); return result; } while (clock() < end); return result; } END_TRY; }
JSObject * GlobalObject::initFunctionAndObjectClasses(JSContext *cx) { Rooted<GlobalObject*> self(cx, this); JS_THREADSAFE_ASSERT(cx->compartment != cx->runtime->atomsCompartment); JS_ASSERT(isNative()); /* * Calling a function from a cleared global triggers this (yeah, I know). * Uncomment this once bug 470510 is fixed (if that bug doesn't remove * isCleared entirely). */ // JS_ASSERT(!isCleared()); /* If cx has no global object, make this the global object. */ if (!cx->globalObject) JS_SetGlobalObject(cx, self); RootedObject objectProto(cx); /* * Create |Object.prototype| first, mirroring CreateBlankProto but for the * prototype of the created object. */ objectProto = NewObjectWithGivenProto(cx, &ObjectClass, NULL, self); if (!objectProto || !objectProto->setSingletonType(cx)) return NULL; /* * The default 'new' type of Object.prototype is required by type inference * to have unknown properties, to simplify handling of e.g. heterogenous * objects in JSON and script literals. */ if (!objectProto->setNewTypeUnknown(cx)) return NULL; /* Create |Function.prototype| next so we can create other functions. */ RootedFunction functionProto(cx); { JSObject *functionProto_ = NewObjectWithGivenProto(cx, &FunctionClass, objectProto, self); if (!functionProto_) return NULL; functionProto = functionProto_->toFunction(); /* * Bizarrely, |Function.prototype| must be an interpreted function, so * give it the guts to be one. */ JSObject *proto = js_NewFunction(cx, functionProto, NULL, 0, JSFUN_INTERPRETED, self, NULL); if (!proto) return NULL; JS_ASSERT(proto == functionProto); functionProto->flags |= JSFUN_PROTOTYPE; const char *rawSource = "() {\n}"; size_t sourceLen = strlen(rawSource); jschar *source = InflateString(cx, rawSource, &sourceLen); if (!source) return NULL; ScriptSource *ss = cx->new_<ScriptSource>(); if (!ss) { cx->free_(source); return NULL; } ScriptSourceHolder ssh(cx->runtime, ss); ss->setSource(source, sourceLen); CompileOptions options(cx); options.setNoScriptRval(true) .setVersion(JSVERSION_DEFAULT); Rooted<JSScript*> script(cx, JSScript::Create(cx, /* enclosingScope = */ NullPtr(), /* savedCallerFun = */ false, options, /* staticLevel = */ 0, ss, 0, ss->length())); if (!script || !JSScript::fullyInitTrivial(cx, script)) return NULL; functionProto->initScript(script); functionProto->getType(cx)->interpretedFunction = functionProto; script->setFunction(functionProto); if (!functionProto->setSingletonType(cx)) return NULL; /* * The default 'new' type of Function.prototype is required by type * inference to have unknown properties, to simplify handling of e.g. * CloneFunctionObject. */ if (!functionProto->setNewTypeUnknown(cx)) return NULL; } /* Create the Object function now that we have a [[Prototype]] for it. */ RootedFunction objectCtor(cx); { JSObject *ctor = NewObjectWithGivenProto(cx, &FunctionClass, functionProto, self); if (!ctor) return NULL; objectCtor = js_NewFunction(cx, ctor, js_Object, 1, JSFUN_CONSTRUCTOR, self, CLASS_NAME(cx, Object)); if (!objectCtor) return NULL; } /* * Install |Object| and |Object.prototype| for the benefit of subsequent * code that looks for them. */ self->setObjectClassDetails(objectCtor, objectProto); /* Create |Function| so it and |Function.prototype| can be installed. */ RootedFunction functionCtor(cx); { // Note that ctor is rooted purely for the JS_ASSERT at the end RootedObject ctor(cx, NewObjectWithGivenProto(cx, &FunctionClass, functionProto, self)); if (!ctor) return NULL; functionCtor = js_NewFunction(cx, ctor, Function, 1, JSFUN_CONSTRUCTOR, self, CLASS_NAME(cx, Function)); if (!functionCtor) return NULL; JS_ASSERT(ctor == functionCtor); } /* * Install |Function| and |Function.prototype| so that we can freely create * functions and objects without special effort. */ self->setFunctionClassDetails(functionCtor, functionProto); /* * The hard part's done: now go back and add all the properties these * primordial values have. */ if (!LinkConstructorAndPrototype(cx, objectCtor, objectProto) || !DefinePropertiesAndBrand(cx, objectProto, NULL, object_methods)) { return NULL; } /* * Add an Object.prototype.__proto__ accessor property to implement that * extension (if it's actually enabled). Cache the getter for this * function so that cross-compartment [[Prototype]]-getting is implemented * in one place. */ Rooted<JSFunction*> getter(cx, js_NewFunction(cx, NULL, ProtoGetter, 0, 0, self, NULL)); if (!getter) return NULL; #if JS_HAS_OBJ_PROTO_PROP Rooted<JSFunction*> setter(cx, js_NewFunction(cx, NULL, ProtoSetter, 0, 0, self, NULL)); if (!setter) return NULL; RootedValue undefinedValue(cx, UndefinedValue()); if (!objectProto->defineProperty(cx, cx->runtime->atomState.protoAtom, undefinedValue, JS_DATA_TO_FUNC_PTR(PropertyOp, getter.get()), JS_DATA_TO_FUNC_PTR(StrictPropertyOp, setter.get()), JSPROP_GETTER | JSPROP_SETTER | JSPROP_SHARED)) { return NULL; } #endif /* JS_HAS_OBJ_PROTO_PROP */ self->setProtoGetter(getter); if (!DefinePropertiesAndBrand(cx, objectCtor, NULL, object_static_methods) || !LinkConstructorAndPrototype(cx, functionCtor, functionProto) || !DefinePropertiesAndBrand(cx, functionProto, NULL, function_methods) || !DefinePropertiesAndBrand(cx, functionCtor, NULL, NULL)) { return NULL; } /* Add the global Function and Object properties now. */ jsid objectId = NameToId(CLASS_NAME(cx, Object)); if (!self->addDataProperty(cx, objectId, JSProto_Object + JSProto_LIMIT * 2, 0)) return NULL; jsid functionId = NameToId(CLASS_NAME(cx, Function)); if (!self->addDataProperty(cx, functionId, JSProto_Function + JSProto_LIMIT * 2, 0)) return NULL; /* Heavy lifting done, but lingering tasks remain. */ /* ES5 15.1.2.1. */ RootedId id(cx, NameToId(cx->runtime->atomState.evalAtom)); JSObject *evalobj = js_DefineFunction(cx, self, id, IndirectEval, 1, JSFUN_STUB_GSOPS); if (!evalobj) return NULL; self->setOriginalEval(evalobj); /* ES5 13.2.3: Construct the unique [[ThrowTypeError]] function object. */ RootedFunction throwTypeError(cx, js_NewFunction(cx, NULL, ThrowTypeError, 0, 0, self, NULL)); if (!throwTypeError) return NULL; if (!throwTypeError->preventExtensions(cx)) return NULL; self->setThrowTypeError(throwTypeError); RootedObject intrinsicsHolder(cx, JS_NewObject(cx, NULL, NULL, self)); if (!intrinsicsHolder) return NULL; self->setIntrinsicsHolder(intrinsicsHolder); if (!JS_DefineFunctions(cx, intrinsicsHolder, intrinsic_functions)) return NULL; /* * The global object should have |Object.prototype| as its [[Prototype]]. * Eventually we'd like to have standard classes be there from the start, * and thus we would know we were always setting what had previously been a * null [[Prototype]], but right now some code assumes it can set the * [[Prototype]] before standard classes have been initialized. For now, * only set the [[Prototype]] if it hasn't already been set. */ if (self->shouldSplicePrototype(cx) && !self->splicePrototype(cx, objectProto)) return NULL; /* * Notify any debuggers about the creation of the script for * |Function.prototype| -- after all initialization, for simplicity. */ js_CallNewScriptHook(cx, functionProto->script(), functionProto); return functionProto; }
HRESULT ComObject::invoke (const Method &method, bool isProperty, REFIID /*riid*/, LCID /*lcid*/, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pReturnValue, EXCEPINFO *pExcepInfo, UINT *pArgErr) { HRESULT hresult; try { // Construct Tcl script to invoke operation on the servant. TclObject script(m_servant); // Get the method or property to invoke on the servant. std::string operation; if ((wFlags & DISPATCH_PROPERTYGET) != 0 && isProperty) { operation = getPrefix + method.name(); } else if (wFlags & (DISPATCH_PROPERTYPUT | DISPATCH_PROPERTYPUTREF)) { operation = setPrefix + method.name(); } else if (wFlags & DISPATCH_METHOD) { operation = method.name(); } else { return DISP_E_MEMBERNOTFOUND; } script.lappend( Tcl_NewStringObj(const_cast<char *>(operation.c_str()), -1)); // Set the argument error pointer in case we need to use it. UINT argErr; if (pArgErr == 0) { pArgErr = &argErr; } // Convert arguments to Tcl values. // TODO: Should handle named arguments differently than positional // arguments. const Method::Parameters ¶meters = method.parameters(); int argIndex = pDispParams->cArgs - 1; Method::Parameters::const_iterator pParam; for (pParam = parameters.begin(); pParam != parameters.end(); ++pParam, --argIndex) { // Append argument value. VARIANT *pArg = &(pDispParams->rgvarg[argIndex]); try { script.lappend(getArgument(pArg, *pParam)); } catch (_com_error &) { *pArgErr = argIndex; throw; } } if (wFlags & (DISPATCH_PROPERTYPUT | DISPATCH_PROPERTYPUTREF)) { VARIANT *pArg = &(pDispParams->rgvarg[argIndex]); try { TclObject value(pArg, method.type(), m_interp); script.lappend(value); } catch (_com_error &) { *pArgErr = argIndex; throw; } } // Execute the Tcl script. TclObject result; int completionCode = eval(script, &result); if (completionCode == TCL_OK) { hresult = S_OK; } else { if (m_isSink) { Tcl_BackgroundError(m_interp); } hresult = hresultFromErrorCode(); if (FAILED(hresult)) { fillExcepInfo( pExcepInfo, hresult, m_servant.c_str(), result.c_str()); hresult = DISP_E_EXCEPTION; } } // Copy values to out arguments. argIndex = pDispParams->cArgs - 1; for (pParam = parameters.begin(); pParam != parameters.end(); ++pParam, --argIndex) { VARIANT *pArg = &(pDispParams->rgvarg[argIndex]); if ((pParam->flags() & PARAMFLAG_FOUT) && (V_VT(pArg) & VT_BYREF)) { // Get name of Tcl variable that holds out value. TclObject varName = getOutVariableName(*pParam); // Copy variable value to out argument. TclObject value; if (getVariable(varName, value) == TCL_OK) { putOutVariant(m_interp, pArg, value, pParam->type()); } } } // Convert return value. if (pReturnValue != 0 && method.type().vartype() != VT_VOID) { // Must increment reference count of interface pointers returned // from methods. result.toVariant(pReturnValue, method.type(), m_interp, true); } } catch (_com_error &e) { fillExcepInfo(pExcepInfo, e.Error(), m_servant.c_str(), 0); hresult = DISP_E_EXCEPTION; } return hresult; }
int main() { sf::RenderWindow window(sf::VideoMode(800, 640), "Scripting"); Lua lua; auto global = lua.GetGlobalEnvironment(); lua.LoadStandardLibraries(); std::ifstream file("Entity.lua"); std::string script((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); file.close(); auto keyPressed = lua.CreateFunction<bool(int)>([&](int key) { return sf::Keyboard::isKeyPressed(sf::Keyboard::Key(key)); }); global.Set("keyPressed", keyPressed); global.Set("A", (int)sf::Keyboard::A); global.Set("D", (int)sf::Keyboard::D); global.Set("W", (int)sf::Keyboard::W); global.Set("S", (int)sf::Keyboard::S); global.Set("Up", (int)sf::Keyboard::Up); global.Set("Down", (int)sf::Keyboard::Down); global.Set("Left", (int)sf::Keyboard::Left); global.Set("Right", (int)sf::Keyboard::Right); auto entity = Entity::createEntity(lua, "Entity_01"); global.Set("entity", entity); lua.RunScript(script); auto tick = global.Get<LuaFunction<void(float)>>("tick"); auto init = global.Get<LuaFunction<void()>>("init"); init.Invoke(); sf::Clock deltaClock; while (window.isOpen()) { sf::Event evt; while (window.pollEvent(evt)) { if (evt.type == sf::Event::Closed || evt.key.code == sf::Keyboard::Escape) { window.close(); } if (evt.key.code == sf::Keyboard::R) { file.open("Entity.lua"); script = std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); lua.RunScript(script); tick = global.Get<LuaFunction<void(float)>>("tick"); file.close(); } } float dt = deltaClock.restart().asSeconds(); tick.Invoke(dt); window.clear(); window.draw(*entity.GetPointer()); window.display(); } return 0; }
bool CWebPageDef::WebPageUpdate( bool fNow, LPCTSTR pszDstName, CTextConsole * pSrc ) { ADDTOCALLSTACK("CWebPageDef::WebPageUpdate"); // Generate the status web pages. // Read in the Base status page "*STATUSBASE.HTM" // Filter the XML type tags. // Output the status page "*.HTM" // Server name // Server email // Number of clients, items, NPC's if ( ! fNow ) { if ( m_iUpdatePeriod <= 0 ) return false; if ( CServTime::GetCurrentTime() < m_timeNextUpdate ) return true; // should stilll be valid } ASSERT(pSrc); m_timeNextUpdate = CServTime::GetCurrentTime() + m_iUpdatePeriod; if ( pszDstName == NULL ) { pszDstName = m_sDstFilePath; } if ( m_type != WEBPAGE_TEMPLATE || *pszDstName == '\0' || m_sSrcFilePath.IsEmpty()) return false; CScript FileRead; if ( ! FileRead.Open( m_sSrcFilePath, OF_READ|OF_TEXT|OF_DEFAULTMODE )) { return false; } CScriptFileContext context( &FileRead ); // set this as the context. CFileConsole FileOut; if ( ! FileOut.m_FileOut.Open( pszDstName, OF_WRITE|OF_TEXT )) { DEBUG_ERR(( "Can't open web page output '%s'\n", static_cast<LPCTSTR>(pszDstName) )); return false; } bool fScriptMode = false; while ( FileRead.ReadTextLine( false )) { TCHAR *pszTmp = Str_GetTemp(); strcpy( pszTmp, FileRead.GetKey()); TCHAR * pszHead = strstr( pszTmp, "<script language=\"Sphere\">" ); if ( pszHead != NULL ) { // Deal with the stuff preceding the scripts. *pszHead = '\0'; pszHead += 26; ParseText( pszTmp, pSrc, 1 ); FileOut.SysMessage( pszTmp ); fScriptMode = true; } else { pszHead = pszTmp; } // Look for the end of </script> if ( fScriptMode ) { GETNONWHITESPACE(pszHead); TCHAR * pszFormat = pszHead; pszHead = strstr( pszFormat, "</script>" ); if ( pszHead != NULL ) { *pszHead = '\0'; pszHead += 9; fScriptMode = false; } if ( pszFormat[0] != '\0' ) { // Allow if/then logic ??? OnTriggerRun( CScript &s, TRIGRUN_SINGLE_EXEC, &FileOut ) CScript script( pszFormat ); if ( ! r_Verb( script, &FileOut )) { DEBUG_ERR(( "Web page source format error '%s'\n", static_cast<LPCTSTR>(pszTmp) )); continue; } } if ( fScriptMode ) continue; } // Look for stuff we can displace here. %STUFF% ParseText( pszHead, pSrc, 1 ); FileOut.SysMessage( pszHead ); } return( true ); }
bool executeCommand(const UINT cmd, const csWStringList& files) { const csWString parallel = regReadParallel(); const DWORD parallelCount = regReadParallelCount(); const bool hasParallel = !parallel.empty() && parallelCount > 1; const DWORD flags = regReadFlags(); const bool isBatch = testFlags(flags, CMD_FLAG_BATCH); const bool isParallel = testFlags(flags, CMD_FLAG_PARALLEL) && hasParallel; const bool isUnc = testFlags(flags, CMD_FLAG_UNC) && cmd != Cmd_List; const bool isUnix = testFlags(flags, CMD_FLAG_UNIX); const csWString scriptPath = regReadScriptsPath(); const csWStringList scripts = regReadScripts(); if( cmd == Cmd_List || cmd == Cmd_ListWithPath || cmd == Cmd_ListWithPathTabular ) { int size = 0; for(csWStringList::const_iterator it = files.begin(); it != files.end(); it++) { wchar_t *uncName = 0; if( isUnc && (uncName = resolveUNC(it->c_str())) != 0 ) { size += lenFN(csWString(uncName), cmd); delete[] uncName; } else { size += lenFN(*it, cmd); } } wchar_t *text = new wchar_t[size+1]; if( text == 0 ) { return false; } int pos = 0; for(csWStringList::const_iterator it = files.begin(); it != files.end(); it++) { wchar_t *uncName = 0; if( isUnc && (uncName = resolveUNC(it->c_str())) != 0 ) { catFN(text, pos, csWString(uncName), cmd); delete[] uncName; } else { catFN(text, pos, *it, cmd); } } text[size] = L'\0'; if( files.size() == 1 ) { // Overwrite trailing <CR><LF> text[size-1] = text[size-2] = L'\0'; } if( isUnix ) { replace(text, size, L'\\', L'/'); } setClipboardText(text); delete[] text; return true; } else if( cmd == Cmd_CreateSymbolicLink ) { csWString symLink; IFileSaveDialog *saveDialog = NULL; HRESULT hr = CoCreateInstance(CLSID_FileSaveDialog, NULL, CLSCTX_INPROC_SERVER, IID_IFileSaveDialog, (LPVOID*)&saveDialog); if( hr == S_OK ) { saveDialog->SetTitle(L"Create symbolic link"); const int index = files.front().lastIndexOf(L'\\'); if( index >= 0 ) { const csWString path = files.front().mid(0, index); const csWString name = files.front().mid(index+1); PIDLIST_ABSOLUTE pidl = NULL; SHParseDisplayName(path.c_str(), NULL, &pidl, 0, NULL); if( pidl != NULL ) { IShellItem *item = NULL; SHCreateItemFromIDList(pidl, IID_IShellItem, (LPVOID*)&item); if( item != NULL ) { saveDialog->SetFolder(item); item->Release(); } CoTaskMemFree(pidl); } saveDialog->SetFileName(name.c_str()); } const COMDLG_FILTERSPEC filterSpec = { L"All files", L"*.*" }; saveDialog->SetFileTypes(1, &filterSpec); const FILEOPENDIALOGOPTIONS opts = FOS_OVERWRITEPROMPT | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST | FOS_CREATEPROMPT | FOS_NOREADONLYRETURN | FOS_NODEREFERENCELINKS | FOS_DONTADDTORECENT; saveDialog->SetOptions(opts); if( saveDialog->Show(NULL) == S_OK ) { IShellItem *item = NULL; if( saveDialog->GetResult(&item) == S_OK ) { wchar_t *filename = NULL; if( item->GetDisplayName(SIGDN_FILESYSPATH, &filename) == S_OK ) { symLink = filename; CoTaskMemFree(filename); } item->Release(); } } saveDialog->Release(); } if( !symLink.empty() ) { if( csFileExists(symLink.c_str()) ) { MessageBoxW(NULL, L"Symbolic link target already exists!", L"Error", MB_OK | MB_ICONERROR); return false; } const DWORD linkFlags = csIsDirectory(files.front().c_str()) ? SYMBOLIC_LINK_FLAG_DIRECTORY : 0; if( CreateSymbolicLinkW(symLink.c_str(), files.front().c_str(), linkFlags) == 0 ) { const DWORD lastError = GetLastError(); csWString msg(L"ERROR(0x"); msg += csWString::number(lastError, 16); msg += L"): "; msg += formatError(lastError); MessageBoxW(NULL, msg.c_str(), L"Error", MB_OK | MB_ICONERROR); return false; } } return true; } else if( cmd == Cmd_CheckBatchProcessing ) { regWriteFlags(flags ^ CMD_FLAG_BATCH); return true; } else if( cmd == Cmd_CheckParallelExecution ) { regWriteFlags(flags ^ CMD_FLAG_PARALLEL); return true; } else if( cmd == Cmd_CheckResolveUncPaths ) { regWriteFlags(flags ^ CMD_FLAG_UNC); return true; } else if( cmd == Cmd_CheckUnixPathSeparators ) { regWriteFlags(flags ^ CMD_FLAG_UNIX); return true; } else if( Cmd_ExecuteScripts <= cmd && cmd < Cmd_ExecuteScripts+scripts.size() ) { csWString script(scriptPath + L"\\"); UINT i = 0; for(csWStringList::const_iterator it = scripts.begin(); it != scripts.end(); it++) { if( i == cmd-Cmd_ExecuteScripts ) { script += *it; break; } i++; } if( isParallel ) { csWStringList args(files); args.push_front(script); args.push_front(csWString::number(parallelCount)); ShellExecuteW(NULL, L"open", parallel.c_str(), joinFileNames(args).c_str(), NULL, SW_SHOWNORMAL); } else { // DO NOT use parallelizer if( isBatch ) { const csWString args = joinFileNames(files); ShellExecuteW(NULL, L"open", script.c_str(), args.c_str(), NULL, SW_SHOWNORMAL); } else { // NO batch processing for(csWStringList::const_iterator it = files.begin(); it != files.end(); it++) { ShellExecuteW(NULL, L"open", script.c_str(), quoteFileName(*it).c_str(), NULL, SW_SHOWNORMAL); } } } return true; } return false; }
void EnvSettingsPrivate::unset() { QFile script(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + "/plasma-workspace/env/kimtoy-env.sh"); script.remove(); }
bool WebView::popupSpellMenu(QContextMenuEvent *event) { // return false if not handled if (!ReKonfig::automaticSpellChecking()) return false; QWebElement element(m_contextMenuHitResult.element()); if (element.isNull()) return false; int selStart = element.evaluateJavaScript("this.selectionStart").toInt(); int selEnd = element.evaluateJavaScript("this.selectionEnd").toInt(); if (selEnd != selStart) return false; // selection, handle normally // No selection - Spell Checking only // Get word QString text = element.evaluateJavaScript("this.value").toString(); QRegExp ws("\\b"); int s1 = text.lastIndexOf(ws, selStart); int s2 = text.indexOf(ws, selStart); QString word = text.mid(s1, s2 - s1).trimmed(); // sanity check if (word.isEmpty()) return false; kDebug() << s1 << ":" << s2 << ":" << word << ":"; Sonnet::Speller spellor; if (spellor.isCorrect(word)) return false; // no need to popup spell menu // find alternates QStringList words = spellor.suggest(word); // Construct popup menu QMenu mnu(this); // Add alternates if (words.isEmpty()) { QAction *a = mnu.addAction(i18n("No suggestions for %1", word)); a->setEnabled(false); } else { QStringListIterator it(words); while (it.hasNext()) { QString w = it.next(); QAction *aWord = mnu.addAction(w); aWord->setData(w); } } // Add dictionary options mnu.addSeparator(); QAction *aIgnore = mnu.addAction(i18n("Ignore")); QAction *aAddToDict = mnu.addAction(i18n("Add to Dictionary")); QAction *aSpellChoice = mnu.exec(event->globalPos()); if (aSpellChoice) { if (aSpellChoice == aAddToDict) spellor.addToPersonal(word); else if (aSpellChoice == aIgnore) { // Ignore :) } else { // Choose a replacement word QString w = aSpellChoice->data().toString(); if (!w.isEmpty()) { // replace word QString script(QL1S("this.value=this.value.substring(0,")); script += QString::number(s1); script += QL1S(") + \'"); script += w.replace('\'', "\\\'"); // Escape any Quote marks in replacement word script += QL1C('\'') + QL1S("+this.value.substring("); script += QString::number(s2); script += QL1C(')'); element.evaluateJavaScript(script); // reposition cursor element.evaluateJavaScript("this.selectionEnd=this.selectionStart=" + QString::number(selStart) + QL1C(';')); } } } return true; }
bool WorkerGlobalScope::idleNotification() { return script()->idleNotification(); }
char *gettxt_fig(char *s) { char *p; int i, c; char *script(char *s, int i); while (*s && *s != '"') ++s; if (*s++ == '\0') return (s - 1); for (p = s, nsub = i = 0; *s && (*s != '"' || *(s + 1) == '"'); ++s) { if (*s == '\\') { /* escape sequence */ if ((c = greek(s + 1)) >= 0) { s += strlen(grk[c]); c += 193; } else { switch (c = *++s) { case 'b': c = 0x08; break; case 'n': c = 0x0a; break; case 'r': c = 0x0d; break; case '^': c = '^'; break; case '_': c = '_'; break; case '\\': c = '\\'; break; case 'd': case 'u': s = script(s, i); c = ' '; break; default: sscanf(s, "%3d", &c); s += 2; break; } } p[i++] = c; } else if ((c = *s) == '^' || c == '_') { if (*(s + 1) == '{') { for (*++s = c; *(s + 1) != '}'; p[i++] = ' ') { s = script(s, i); *s = c; } ++s; } else { s = script(s, i); p[i++] = ' '; } } else { if (*s == '"') ++s; p[i++] = *s; } } sub[nsub] = p[i] = '\0'; while (p + i < s) p[++i] = ' '; return (p); }
void VlcEncodingSystem::_DoEncode(const QString ¶mFile) { QFileInfo videoFile(QFileInfo(QFileInfo(paramFile).completeBaseName()).completeBaseName()); QDir dir(VlcStreamerApp::Instance()->DocumentRoot()); QString name; if(dir.exists(videoFile.completeBaseName())) { for(unsigned i = 1; i != ~0U; ++i) { if(dir.exists(videoFile.completeBaseName() + "_" + QString::number(i)) == false) { name = videoFile.completeBaseName() + "_" + QString::number(i); break; } } } else { name = videoFile.completeBaseName(); } if(name.isEmpty() == false) { dir.mkdir(name); dir.cd(name); dir.rename(paramFile, "params.txt"); #ifdef Q_WS_WIN QFileInfo scriptInfo(dir.path() + "/encode.bat"); #else QFileInfo scriptInfo(dir.path() + "/encode.sh"); #endif QFile script(scriptInfo.filePath()); QFile params(dir.path() + "/params.txt"); if(params.open(QIODevice::ReadWrite)) { QString paramData = params.readAll(); params.close(); bool ok; QJson::Parser parser; QVariantMap map = parser.parse(paramData.toAscii(), &ok).toMap(); if(ok && script.open(QIODevice::WriteOnly)) { QString scriptData; //#!/bin/bash //vlc -I dummy --ignore-config "/home/paulm/Videos/troops.avi" // '--sout=#transcode{vcodec=h264,soverlay,acodec=mp3,channels=2,venc=x264{profile=baseline,level=2.2,keyint=30,bframes=0,ref=1,nocabac},width=480,vb=200,ab=40,fps=25,deinterlace}: // std{access=livehttp{seglen=10,index="/home/paulm/.Hobbyist_Software/VLC_Streamer/Root/troops/stream.m3u8",index-url=stream-###.ts}, // mux=ts{use-key-frames}, // dst="/home/paulm/.Hobbyist_Software/VLC_Streamer/Root/troops/stream-###.ts"}' // vlc://quit scriptData = "#!/bin/bash\n"; QString temp = map.value("sout").toString(); temp.replace("##dest##", dir.path()); scriptData += "vlc -I dummy --ignore-config " + map.value("args").toString() + " \"" + map.value("file").toString() + "\" vlc://quit " + "'" + temp + "' -vvv\n"; script.write(scriptData.toAscii()); script.close(); script.setPermissions(QFile::ReadUser | QFile::WriteUser | QFile::ExeUser); VlcEncoder *encoder = new VlcEncoder(scriptInfo.filePath()); QThreadPool::globalInstance()->start(encoder); } else { qDebug() << "Not ok or script didn't open" << ok << script.error(); } } } }
void GuiWindowDef::constructFromTokens(parser::DefTokeniser& tokeniser) { // The windowDef keyword has already been parsed, so expect a name plus an opening brace here name = tokeniser.nextToken(); tokeniser.assertNextToken("{"); while (tokeniser.hasMoreTokens()) { std::string token = tokeniser.nextToken(); boost::algorithm::to_lower(token); if (token == "rect") { rect = parseVector4(tokeniser); } else if (token == "visible") { visible = parseBool(tokeniser); } else if (token == "notime") { notime = parseBool(tokeniser); } else if (token == "forecolor") { forecolor = parseVector4(tokeniser); } else if (token == "backcolor") { backcolor = parseVector4(tokeniser); } else if (token == "bordercolor") { bordercolor = parseVector4(tokeniser); } else if (token == "matcolor") { matcolor = parseVector4(tokeniser); } else if (token == "rotate") { rotate = parseFloat(tokeniser); } else if (token == "text") { setText(parseString(tokeniser)); } else if (token == "font") { font = parseString(tokeniser); // Cut off the "fonts/" part boost::algorithm::replace_first(font, "fonts/", ""); } else if (token == "textscale") { textscale = parseFloat(tokeniser); } else if (token == "textalign") { textalign = parseInt(tokeniser); } else if (token == "textalignx") { textalignx = parseFloat(tokeniser); } else if (token == "textaligny") { textaligny = parseFloat(tokeniser); } else if (token == "forceaspectwidth") { forceaspectwidth = parseFloat(tokeniser); } else if (token == "forceaspectheight") { forceaspectheight = parseFloat(tokeniser); } else if (token == "background") { background = parseString(tokeniser); } else if (token == "noevents") { noevents = parseBool(tokeniser); } else if (token == "nocursor") { nocursor = parseBool(tokeniser); } else if (token == "noclip") { noclip = parseBool(tokeniser); } else if (token == "nowrap") { nowrap = parseBool(tokeniser); } else if (token == "modal") { noevents = parseBool(tokeniser); } else if (token == "menugui") { menugui = parseBool(tokeniser); } else if (token == "windowdef") { // Child windowdef GuiWindowDefPtr window(new GuiWindowDef(_owner)); window->constructFromTokens(tokeniser); addWindow(window); } else if (token == "ontime") { std::string timeStr = tokeniser.nextToken(); // Check the time for validity std::size_t time = string::convert<std::size_t>( timeStr, std::numeric_limits<std::size_t>::max() ); if (time == std::numeric_limits<std::size_t>::max()) { rWarning() << "Invalid time encountered in onTime event in " << name << ": " << timeStr << std::endl; } // Allocate a new GuiScript GuiScriptPtr script(new GuiScript(*this)); script->constructFromTokens(tokeniser); _timedEvents.insert(TimedEventMap::value_type(time, script)); } else if (token == "onnamedevent") { std::string eventName = tokeniser.nextToken(); // Parse the script GuiScriptPtr script(new GuiScript(*this)); script->constructFromTokens(tokeniser); // TODO: Save event } else if (token == "onevent") { GuiScriptPtr script(new GuiScript(*this)); script->constructFromTokens(tokeniser); // TODO } else if (token == "onesc") { GuiScriptPtr script(new GuiScript(*this)); script->constructFromTokens(tokeniser); // TODO } else if (token == "onmouseenter" || token == "onmouseexit") { GuiScriptPtr script(new GuiScript(*this)); script->constructFromTokens(tokeniser); // TODO } else if (token == "onaction") { GuiScriptPtr script(new GuiScript(*this)); script->constructFromTokens(tokeniser); // TODO } else if (token == "float" || token == "definefloat") { // TODO: Add variable std::string variableName = tokeniser.nextToken(); } else if (token == "definevec4") { // TODO: Add variable std::string variableName = tokeniser.nextToken(); parseVector4(tokeniser); } else if (token == "}") { break; } else { rWarning() << "Unknown token encountered in GUI: " << token << std::endl; } } }
void YumScriptJob::process(){try{ rwfile rw(QString("scripts/%1.src").arg(number)); TASSUME(rw.issue.isEmpty(),rw.issue); ImasScript script(&rw); TASSUME(script.issue.isEmpty(),QString("scripts/%1.src: %2").arg(number).arg(script.issue)); ImasScriptText text(file); TASSUME(text.issue.isEmpty(),text.issue); int lineno=0; for(int i=0;i<script.nodes.count();i++){ QString errstr; ImasScriptNode *node=script.nodes.value(i); if(node->group==SCIPT_GROUP_TEXT){ if(text.lines.count()<=lineno){ issue="Not enough lines in script file you supplied"; state=JOB_STATE_FAILED; return; } node->text=text_encode(text.line(lineno),&errstr); if(!errstr.isEmpty()){ output.append(QString("line %1: couldn't encode text: %2") .arg(text.lineno(lineno)) .arg(errstr)); } lineno++; } else if(node->group>=SCIPT_GROUP_NAME){ int nameno=node->group-SCIPT_GROUP_NAME; if(text.names.count()<nameno){ issue="Not enough names in script file you supplied"; state=JOB_STATE_FAILED; return; } node->text=text_encode(text.name(nameno),&errstr); if(!errstr.isEmpty()){ output.append(QString("Couldn't encode name ``%1'': %2") .arg(text.name(nameno)) .arg(errstr)); } } } if(text.lines.count()!=lineno) output.append("Too many lines in script file you supplied"); QByteArray bytes=script.spit(); TASSUME(script.issue.isEmpty(),script.issue); Yum y(isofile,number); TASSUME(y.issue.isEmpty(),y.issue); y.spit(bytes.data(),bytes.size()); TASSUME(y.issue.isEmpty(),y.issue); if(output.isEmpty()){ state=JOB_STATE_OK; } else{ state=JOB_STATE_WARNINGS; } } catch(QString ss){ state=JOB_STATE_FAILED; }}
void MatWindow::processMat(QTreeWidgetItem* currentItem) { if(!currentItem) return; return; //clean old values strAllMat = ""; matText->clear(); textureLbl->setPixmap(QPixmap("")); textureLbl->setText("Texture Unavailable"); //We'll seek for the material to include it in matText. QDir dir(scriptPath); QStringList listFiles(dir.entryList(QStringList() << "*.material", QDir::Files)); for(int i = 0; i < listFiles.size(); i++) { QFile file(dir.path() + QDir::separator() + listFiles.at(i)); if(file.open(QIODevice::ReadOnly)) { QTextStream script(&file); //Search our mat QString strMat = script.readAll(); QString nameMat("material "+currentItem->text(0)); posMat = strMat.indexOf(nameMat); if(posMat != -1) { matText->setPlainText(strMat);//insert all the text and keep it in strAllMat strAllMat = matText->toPlainText(); matText->clear();//clear it so the user don't see anything //Process: we cut the beginning of the string. Then we cut all others material //So we only have the material wich interest us strMat.remove(0, posMat);//we cut the firt part of the string nextMat = strMat.indexOf("material ", 8);//search the next material at pos 8 because we want the next material (not the first one) if(nextMat != -1) strMat.remove(nextMat, strMat.size());//we cut from this next material to the end so we only have the material we want //Processing strMat for(int i=0; i<strMat.size(); ++i) { if(strMat.at(i) == '\t') strMat.replace(i, 1, " "); } matText->setPlainText(strMat); QFont f("Arial", 8); matText->setFont(f); //Now we're looking for the texture int posText = strMat.indexOf("texture "); if(posText != -1) { QString textureName; for(int i=posText+8; i<strMat.size(); ++i) { textureName += strMat.at(i); } textureName.truncate(textureName.indexOf('.')); QPixmap img; if(img.load(texturePath+textureName)) { img = img.scaled(150, 150); textureLbl->setText(textureName); textureLbl->setPixmap(img); } else { textureLbl->setText("Image Unavailable"); } } matFile.setFileName(file.fileName());//Finally we keep matFile in memory so that we can open the file later --> saveMat() } } file.close(); } }
v8::Handle<v8::Value> PoiMergerJs::jsPoiMerge(const v8::Arguments& args) { HandleScope scope; try{ if (args.Length() != 2) { return v8::ThrowException(HootExceptionJs::create(IllegalArgumentException( "Expected exactly two arguments to 'poiMerge'."))); } // Argument 1: script -- note second param is directory to search under (~/hoot/rules) const QString scriptPath = ConfPath::search(toCpp<QString>(args[0]), "rules"); // Argument 2: Map with POIs OsmMapJs* mapJs = node::ObjectWrap::Unwrap<OsmMapJs>(args[1]->ToObject()); // Pull out internal POI map OsmMapPtr map( mapJs->getMap() ); // Instantiate script merger shared_ptr<PluginContext> script(new PluginContext()); v8::HandleScope handleScope; v8::Context::Scope context_scope(script->getContext()); script->loadScript(scriptPath, "plugin"); v8::Handle<v8::Object> global = script->getContext()->Global(); if (global->Has(String::New("plugin")) == false) { return v8::ThrowException(HootExceptionJs::create(IllegalArgumentException( "Expected the script to have exports."))); } v8::Handle<v8::Value> pluginValue = global->Get(String::New("plugin")); v8::Persistent<v8::Object> plugin = v8::Persistent<v8::Object>::New(v8::Handle<v8::Object>::Cast(pluginValue)); if (plugin.IsEmpty() || plugin->IsObject() == false) { return v8::ThrowException(HootExceptionJs::create(IllegalArgumentException( "Expected plugin to be a valid object."))); } // Got in Map with POIs A, B, C, D, E // // Make a set of pairs to indicate all are same object: // A->B, A->C, A->D, A->E // // ...then pass those pairs one at a time through the merger, since it only merges pairs OsmMap::NodeMap nodes = map->getNodeMap(); OsmMapPtr mergedMap(map); const ElementId firstId = ElementId::node((*(nodes.constBegin()))->getId()); //LOG_DEBUG("First ID: " << firstId.getId()); for (OsmMap::NodeMap::const_iterator it = nodes.constBegin() + 1; it != nodes.constEnd(); ++it) { const boost::shared_ptr<const Node>& n = it.value(); std::set< std::pair< ElementId, ElementId> > matches; matches.insert(std::pair<ElementId,ElementId>(firstId, ElementId::node(n->getId()))); // Now create scriptmerger, and invoke apply method which will apply apply merge transformation, reducing the POIs down to one ScriptMerger merger(script, plugin, matches); OsmMapPtr mergedMap(map); std::vector< std::pair< ElementId, ElementId > > replacedNodes; merger.apply(mergedMap, replacedNodes ); if ( replacedNodes.size() == 1 ) { /* LOG_DEBUG("POI merge: replacing node #" << replacedNodes[0].first.getId() << " with updated version of node #" << replacedNodes[0].second.getId() ); */ mergedMap->replaceNode(replacedNodes[0].first.getId(), replacedNodes[0].second.getId()); } } // Hand merged POIs back to caller in OsmMap v8::Handle<v8::Object> returnMap = OsmMapJs::create(mergedMap); return scope.Close(returnMap); } catch ( const HootException& e ) { return v8::ThrowException(HootExceptionJs::create(e)); } }
void Config::read() { if (d->configPath.isEmpty()) return; LOG_AS("Config::read"); // Current version. Version verInfo = Version::currentBuild(); QScopedPointer<ArrayValue> version(new ArrayValue); *version << NumberValue(verInfo.major) << NumberValue(verInfo.minor) << NumberValue(verInfo.patch) << NumberValue(verInfo.build); File &scriptFile = App::rootFolder().locate<File>(d->configPath); bool shouldRunScript = App::commandLine().has("-reconfig"); try { // If we already have a saved copy of the config, read it. d->refuge.read(); LOG_DEBUG("Found serialized Config:\n") << objectNamespace(); // If the saved config is from a different version, rerun the script. if (objectNamespace().has("__version__")) { Value const &oldVersion = objectNamespace()["__version__"].value(); d->setOldVersion(oldVersion); if (oldVersion.compare(*version)) { // Version mismatch: store the old version in a separate variable. d->config.globals().add(new Variable("__oldversion__", oldVersion.duplicate(), Variable::AllowArray | Variable::ReadOnly)); shouldRunScript = true; } else { // Versions match. LOG_MSG("") << d->refuge.path() << " matches version " << version->asText(); } } else { // Don't know what version this is, run script to be sure. shouldRunScript = true; } // Also check the timestamp of written config vs. the config script. // If script is newer, it should be rerun. if (scriptFile.status().modifiedAt > d->refuge.lastWrittenAt()) { LOG_MSG("%s is newer than %s, rerunning the script") << d->configPath << d->refuge.path(); shouldRunScript = true; } // Check the container, too. if (!shouldRunScript && Package::containerOfFileModifiedAt(scriptFile) > d->refuge.lastWrittenAt()) { LOG_MSG("Package '%s' is newer than %s, rerunning the script") << Package::identifierForContainerOfFile(scriptFile) << d->refuge.path(); shouldRunScript = true; } } catch (Archive::NotFoundError const &) { // It is missing from persist.pack if the config hasn't been written yet. shouldRunScript = true; } catch (IByteArray::OffsetError const &) { // Empty or missing serialization? shouldRunScript = true; } catch (Error const &error) { LOG_WARNING(error.what()); // Something is wrong, maybe rerunning will fix it. shouldRunScript = true; } // The version of libcore is automatically included in the namespace. d->config.globals().add(new Variable("__version__", version.take(), Variable::AllowArray | Variable::ReadOnly)); if (shouldRunScript) { // Read the main configuration. Script script(scriptFile); d->config.run(script); d->config.execute(); } }
bool Game::initialize(ENetAddress *address, const char *baseKey){ if (enet_initialize () != 0) return false; atexit(enet_deinitialize); _server = enet_host_create(address, 32, 0, 0); if(_server == NULL) return false; std::string key = base64_decode(baseKey); if(key.length() <= 0) return false; _blowfish = new BlowFish((uint8*)key.c_str(), 16); initHandlers(); map = new SummonersRift(this); //TODO: better lua implementation LuaScript script(false); script.loadScript("../../lua/config.lua"); // sol::state lua; // lua.open_libraries(sol::lib::base, sol::lib::table); // lua.open_file("../../lua/config.lua"); sol::table playerList = script.getTable("players"); for (int i=1;i<12;i++) { try { std::string playerIndex = "player"+toString(i); sol::table playerData = playerList.get<sol::table>(playerIndex); std::string rank = playerData.get<std::string>("rank"); std::string name = playerData.get<std::string>("name"); std::string champion = playerData.get<std::string>("champion"); std::string team = playerData.get<std::string>("team"); int skin = playerData.get<int>("skin"); int ribbon = playerData.get<int>("ribbon"); int icon = playerData.get<int>("icon"); std::string summoner1 = playerData.get<std::string>("summoner1"); std::string summoner2 = playerData.get<std::string>("summoner2"); ClientInfo* player = new ClientInfo(rank, ((team == "BLUE") ? TEAM_BLUE : TEAM_PURPLE), ribbon, icon); player->setName(name); player->setSkinNo(skin); static int id = 1; player->userId = id; // same as StartClient.bat id++; player->setSummoners(strToId(summoner1), strToId(summoner2)); Champion* c = ChampionFactory::getChampionFromType(champion, map, GetNewNetID(), player->userId); float respawnX, respawnY; std::tie(respawnX, respawnY) = c->getRespawnPosition(); c->setPosition(respawnX, respawnY); c->setSide((team == "BLUE") ? 0 : 1); c->levelUp(); map->addObject(c); player->setChampion(c); players.push_back(player); } catch(sol::error e) { //printf("Error loading champion: \n%s", e.what()); break; } } // Uncomment the following to get 2-players /*ClientInfo* player2 = new ClientInfo("GOLD", TEAM_PURPLE); player2->setName("tseT"); Champion* c2 = ChampionFactory::getChampionFromType("Ezreal", map, GetNewNetID()); c2->setPosition(100.f, 273.55f); c2->setSide(1); map->addObject(c2); player2->setChampion(c2); player2->setSkinNo(4); player2->userId = 2; // same as StartClient.bat player2->setSummoners(SPL_Ignite, SPL_Flash); players.push_back(player2);*/ return _isAlive = true; }
nsresult ProxyAutoConfig::SetupJS() { mJSNeedsSetup = false; NS_ABORT_IF_FALSE(!sRunning, "JIT is running"); delete mJSRuntime; mJSRuntime = nullptr; if (mPACScript.IsEmpty()) return NS_ERROR_FAILURE; mJSRuntime = JSRuntimeWrapper::Create(); if (!mJSRuntime) return NS_ERROR_FAILURE; JSContext* cx = mJSRuntime->Context(); JSAutoRequest ar(cx); JSAutoCompartment ac(cx, mJSRuntime->Global()); // check if this is a data: uri so that we don't spam the js console with // huge meaningless strings. this is not on the main thread, so it can't // use nsIRUI scheme methods bool isDataURI = nsDependentCSubstring(mPACURI, 0, 5).LowerCaseEqualsASCII("data:", 5); sRunning = this; JS::Rooted<JSObject*> global(cx, mJSRuntime->Global()); JS::CompileOptions options(cx); options.setFileAndLine(mPACURI.get(), 1); JS::Rooted<JSScript*> script(cx, JS_CompileScript(cx, global, mPACScript.get(), mPACScript.Length(), options)); if (!script || !JS_ExecuteScript(cx, global, script, nullptr)) { nsString alertMessage(NS_LITERAL_STRING("PAC file failed to install from ")); if (isDataURI) { alertMessage += NS_LITERAL_STRING("data: URI"); } else { alertMessage += NS_ConvertUTF8toUTF16(mPACURI); } PACLogToConsole(alertMessage); sRunning = nullptr; return NS_ERROR_FAILURE; } sRunning = nullptr; mJSRuntime->SetOK(); nsString alertMessage(NS_LITERAL_STRING("PAC file installed from ")); if (isDataURI) { alertMessage += NS_LITERAL_STRING("data: URI"); } else { alertMessage += NS_ConvertUTF8toUTF16(mPACURI); } PACLogToConsole(alertMessage); // we don't need these now mPACScript.Truncate(); mPACURI.Truncate(); return NS_OK; }