Example #1
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    network_ = new Network(this);
    connect(network_,SIGNAL(listUpdated()),
            this,SLOT(onRedraw()));
    this->setFixedSize(this->size());
    //QTextCodec::setCodecForLocale(QTextCodec::codecForName("CP-866"));
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
    ui->listWidget->setContextMenuPolicy(Qt::CustomContextMenu);

    QAction *act;
    modeMenu_ = new QMenu(this);

    act = new QAction(tr("Telnet mode"),this);
    connect(act,SIGNAL(triggered()),this,SLOT(runTelnet()));
    modeMenu_->addAction(act);

    act = new QAction(tr("File mode"),this);
    connect(act,SIGNAL(triggered()),this,SLOT(runFile()));
    modeMenu_->addAction(act);

    act = new QAction(tr("Graphics mode"),this);
    connect(act,SIGNAL(triggered()),this,SLOT(runGraph()));
    modeMenu_->addAction(act);

    modeMenu_->addSeparator();

    act = new QAction(tr("Options"),this);
    connect(act,SIGNAL(triggered()),this,SLOT(runOptions()));
    modeMenu_->addAction(act);
}
Example #2
0
int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QMainWindow::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: about(); break;
        case 1: newFile(); break;
        case 2: openFile((*reinterpret_cast< const QString(*)>(_a[1]))); break;
        case 3: openFile(); break;
        case 4: saveFile(); break;
        case 5: saveFileAs((*reinterpret_cast< const QString(*)>(_a[1]))); break;
        case 6: saveFileAs(); break;
        case 7: runFile(); break;
        case 8: inspect(); break;
        case 9: append((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2]))); break;
        case 10: onEngineStarted(); break;
        case 11: onEngineStopped(); break;
        case 12: onEnginePanic((*reinterpret_cast< Atom(*)>(_a[1])),(*reinterpret_cast< Word(*)>(_a[2])),(*reinterpret_cast< const QString(*)>(_a[3])),(*reinterpret_cast< const QString(*)>(_a[4]))); break;
        default: ;
        }
        _id -= 13;
    }
    return _id;
}
Example #3
0
int main(int argc, const char* argv[])
{
  if (argc == 1) return runRepl();
  if (argc == 2) return runFile(argv[1]);

  fprintf(stderr, "Usage: wren [file]");
  return 1;
}
void V8Engine::init()
{
    Logging::log(Logging::DEBUG, "V8Engine::init:\r\n");
    INDENT_LOG(Logging::DEBUG);

    HandleScope handleScope;

    // Create a template for the global object.
    Logging::log(Logging::DEBUG, "Creating global\r\n");

//    _global = ObjectTemplate::New();

    Logging::log(Logging::DEBUG, "Creating context\r\n");

    context = Context::New(); //NULL, _global);

    context->Enter();

    // Create our internal wrappers

    Logging::log(Logging::DEBUG, "Creating wrapper for global\r\n");

    globalValue = ScriptValuePtr(new V8Value(this, context->Global()));

#if 0
    // Setup debugger, if required - XXX Doesn't work

//    Debug::SetDebugEventListener(debuggerListener);
//    runFile("src/thirdparty/v8/src/debug-delay.js"); // FIXME: remove hardcoded src/..
    runFile("src/javascript/intensity/V8Debugger.js"); // FIXME: remove hardcoded src/javascript
             
    v8::Handle<v8::Value> result =
        ((V8Value*)(getGlobal()->getProperty("__debuggerListener").get()))->value;
    assert(result->IsObject());
    Local<Object> debuggerListener = result->ToObject();
    assert(debuggerListener->IsFunction());

    Debug::SetDebugEventListener(debuggerListener);

    runScript("Debug.setBrzzzzzzzzzeakOnException()");

    Local<String> source = String::New(
        "temp = function () { Debug.setBreakOnException(); return 5098; } "
    );
    Local<Script> code = Script::Compile(source);
    Local<Value> result2 = code->Run();
    printV8Value(result2, true);
    assert(result2->IsObject());
    Local<Object> obj = result2->ToObject();
    assert(obj->IsFunction());
    Local<Function> func = Function::Cast(*obj);
    Handle<Value> output = Debug::Call(func);
    printV8Value(output, true);
assert(0);
#endif

    Logging::log(Logging::DEBUG, "V8Engine::init complete.\r\n");
}
Example #5
0
Engine::ExitStatus Engine::runFile( const KJS::UString &fileName )
{
    dptr->m_currentResult = runFile( dptr->m_interpreter, fileName );

    if( dptr->m_currentResult.complType() == KJS::Normal )
        return Engine::Success;
    else if ( dptr->m_currentResult.complType() == KJS::ReturnValue)
        return Engine::Success;
    else
        return Engine::Failure;
}
Example #6
0
void SchematicMap::loadDraftSchematicFile() {
	runFile("scripts/managers/crafting/schematics.lua");

	// Read and create all the items in the config unless they
	// were already loaded from database.

	LuaObject serverScriptCRCList = getGlobalObject("schematics");

	int size = serverScriptCRCList.getTableSize();
	int count = 0;

	lua_State* L = serverScriptCRCList.getLuaState();

	for (int i = 0; i < size; ++i) {

		lua_rawgeti(L, -1, i + 1);
		LuaObject luaObject(L);

		String path = luaObject.getStringField("path");
		uint32 servercrc = path.hashCode();

		Reference<DraftSchematic*> schematic = schematicCrcMap.get(servercrc);

		luaObject.pop();

		if (schematic == NULL) {
			try {
				schematic = dynamic_cast<DraftSchematic*> (objectManager->createObject(servercrc, 1, "draftschematics"));

				if(schematic == NULL) {
					error("Could not create schematic with crc: " + String::valueOf(servercrc));
					continue;
				}

			} catch (Exception& e) {
				error(e.getMessage());
				error("Could not create schematic with template: " + path);
				continue;
			}
			if(!schematicCrcMap.contains(schematic->getServerObjectCRC()))
				schematicCrcMap.put(schematic->getServerObjectCRC(), schematic);

			if(!schematicCrcMap.contains(schematic->getClientObjectCRC()))
				schematicCrcMap.put(schematic->getClientObjectCRC(), schematic);

			count++;

		}
	}

	info("Loaded " + String::valueOf(count) + " schematics from scripts", true);

	serverScriptCRCList.pop();
}
Example #7
0
int main(){
	char fileName[20];
	char errorLogFileName[20];
	createBotDirectory(errorLogFileName);
	createFileName(fileName, 1);
	genFile(fileName);
	if(buildFile(fileName, errorLogFileName)!=-1){
		runFile(fileName, errorLogFileName);
	}else{
		printf("Build error\n");
	}
}
Example #8
0
int main(int argc, const char* argv[])
{
  if (argc != 2)
  {
    fprintf(stderr, "Usage: wren <test>\n");
    return 64; // EX_USAGE.
  }

  testName = argv[1];
  setTestCallbacks(bindForeignMethod, bindForeignClass, afterLoad);
  runFile(testName);
  return 0;
}
Example #9
0
bool Radio::runCommand(std::string input){
    std::string command = "";
    unsigned int i = 0;
    for(i = 0; i < input.length() && input[i] != ' '; ++ i){
	command = command + input[i];
    }
    ++ i;
    std::string restStr = "";
    if(i < input.length()){
	restStr = input.substr(i);	
    }
    if(command == "QUIT"){
	return false;
    }
    if(command == "INIT"){
	init(restStr);
	return true;
    }
    if(command == "ADD"){
	addSong(restStr);
	return true;
    }
    if(command == "RUN"){
	int result = 0;
	result = runFile(restStr);
	if(result == 0){
	    return false;
	}else{
	    return true;
	}
    }
    if(command == "REST"){
	rest(restStr);
	return true;
    }
    if(command == "PLAY"){
	play(restStr);
	return true;
    }
    if(command == "LIKE"){
	like(restStr);
	return true;
    }
    if(command == "DISLIKE"){
	dislike(restStr);
	return true;
    }
    return false;
}
Example #10
0
void Regioner::createCohorList4Run(){
	// read in a list of cohorts to run

	//netcdf error
	NcError err(NcError::silent_nonfatal);

	//open file and check if valid
	string filename = md.runchtfile;
	NcFile runFile(filename.c_str(), NcFile::ReadOnly);
 	if(!runFile.is_valid()){
 		string msg = filename+" is not valid";
 		char* msgc = const_cast< char* > ( msg.c_str());
 		throw Exception(msgc, I_NCFILE_NOT_EXIST);
 	}
 	
 	NcDim* chtD = runFile.get_dim("CHTID");
 	if(!chtD->is_valid()){
 		string msg="CHT Dimension is not valid in createCohortList4Run";
 		char* msgc = const_cast<char*> (msg.c_str());
 		throw Exception(msgc, I_NCDIM_NOT_EXIST);
 	}
 	
 	NcVar* chtV = runFile.get_var("CHTID");
 	if(chtV==NULL){
 		string msg="Cannot get CHTID in createCohortList4Run ";
 		char* msgc = const_cast<char*> (msg.c_str());
 		throw Exception(msgc, I_NCVAR_NOT_EXIST);
 	}

 	int numcht = chtD->size();
 	
	int chtid  = -1;
	int chtid0 = -1;
	int chtidx = -1;
	for (int i=0; i<numcht; i++){
		chtV->set_cur(i);
   		chtV->get(&chtid, 1);
   		runchtlist.push_back(chtid);
	   	
	   	if (i==0) chtid0=chtid;
	   	if (i==numcht-1) chtidx=chtid;
   	}

	cout <<md.casename << ": " <<numcht <<"  cohorts to be run @" <<md.runstages<< "\n";
	cout <<"   from:  " <<chtid0<<"  to:  " <<chtidx <<"\n";
   
};
Example #11
0
//-----------------------------------------------------------------------------
void ctkConsolePrivate::init()
{
  Q_Q(ctkConsole);
  this->setParent(q);
  this->setTabChangesFocus(false);
  this->setAcceptDrops(false);
  this->setAcceptRichText(false);
  this->setUndoRedoEnabled(false);

  this->PromptColor = QColor(0, 0, 0);    // Black
  this->OutputTextColor = QColor(0, 150, 0);  // Green
  this->ErrorTextColor = QColor(255, 0, 0);   // Red
  this->StdinTextColor = QColor(Qt::darkGray);
  this->CommandTextColor = QColor(0, 0, 150); // Blue
  this->WelcomeTextColor = QColor(0, 0, 255); // Dark Blue

  QFont shellFont;
  shellFont.setFamily("Courier");
  shellFont.setStyleHint(QFont::TypeWriter);
  shellFont.setFixedPitch(true);

  QTextCharFormat format;
  format.setFont(shellFont);
  format.setForeground(this->OutputTextColor);
  this->setCurrentCharFormat(format);

  this->CommandHistory.append("");
  this->CommandPosition = 0;

  QAction* runFileAction = new QAction(q->tr("&Run file"),q);
  runFileAction->setShortcut(q->tr("Ctrl+r"));
  connect(runFileAction, SIGNAL(triggered()), q, SLOT(runFile()));
  q->addAction(runFileAction);

  QAction* printHelpAction = new QAction(q->tr("Print &help"),q);
  printHelpAction->setShortcut(q->tr("Ctrl+h"));
  connect(printHelpAction, SIGNAL(triggered()), q, SLOT(printHelp()));
  q->addAction(printHelpAction);

  QVBoxLayout * layout = new QVBoxLayout(q);
  layout->setMargin(0);
  layout->addWidget(this);

  connect(this->verticalScrollBar(), SIGNAL(valueChanged(int)),
          SLOT(onScrollBarValueChanged(int)));
  connect(this, SIGNAL(textChanged()), SLOT(onTextChanged()));
}
Example #12
0
File: main.c Project: lerno/coil
int main(int argc, const char *argv[])
{
	init_vm();

	switch (argc)
	{
		case 1:
			repl();
			break;
		case 2:
			runFile(argv[1]);
			break;
		default:
			fprintf(stderr, "Usage: coil [path]\n");
			exit(64);
	}
	free_vm();
	return 0;
}
Example #13
0
int main(int argc, const char* argv[])
{
  if (argc < 1 || argc > 2)
  {
    fprintf(stderr, "Usage: wren [file]\n");
    return 64; // EX_USAGE.
  }

  if (argc == 1)
  {
    runRepl();
  }
  else if (argc == 2)
  {
    runFile(NULL, argv[1]);
  }

  return 0;
}
Example #14
0
File: main.c Project: jesskay/wren
int main(int argc, const char* argv[])
{
  if (argc != 2)
  {
    fprintf(stderr, "Usage: wren <test>\n");
    return 64; // EX_USAGE.
  }

  testName = argv[1];

  // The test script is at "test/api/<test>.wren".
  char testPath[256];
  strcpy(testPath, "test/api/");
  strcat(testPath, testName);
  strcat(testPath, ".wren");

  setForeignCallbacks(bindForeignMethod, bindForeignClass);
  runFile(testPath);
  return 0;
}
Example #15
0
int main(int argc, char *argv[])
{
#if PY_MAJOR_VERSION >= 3
    int i, len;
    wchar_t** argv_ex = NULL;
    argv_ex = (wchar_t**) malloc(sizeof(wchar_t*) * argc);
    for(i=0 ; i<argc ; ++i)
    {
        len = mbstowcs(NULL, argv[i], 0);
        argv_ex[i] = (wchar_t*) malloc(sizeof(wchar_t) * (len+1));
        mbstowcs(argv_ex[i], argv[i], len);
        argv_ex[i][len] = 0;
    }
#else
    char** argv_ex = argv;
#endif

    Py_SetProgramName(argv_ex[0]);  /* optional but recommended */
    Py_Initialize();

    if(argc >= 2)
    {
        PySys_SetArgv(argc-1, argv_ex+1);
        runFile(argv[1]);
    }

    Py_Finalize();

#if PY_MAJOR_VERSION >= 3
    for(i=0 ; i<argc ; ++i)
    {
        free(argv_ex[i]);
    }
    free(argv_ex);
#endif
    return 0;
}
Example #16
0
void PolycodePlayer::loadFile(const char *fileName) {
	
	FILE *t = fopen("C:\\out.txt", "a");
	fwrite(fileName, strlen(fileName), 1, t);
	fclose(t);

	String mainFile = "";
	String basePath = fileName;
	
	Number red = 0.2f;
	Number green = 0.2f;
	Number blue = 0.2f;
	
	frameRate = 60;
	
	Object configFile;

	String nameString = fileName;
		
	bool loadingArchive = false;

	if(nameString != "") {
	String ext = nameString.substr(nameString.length() - 8, nameString.length());
	
	Logger::log("Loading %s\n", fileName);
	
	String configPath;
	
	if(ext == ".polyapp" || _knownArchive) {
		ResourceManager *rman = CoreServices::getInstance()->getResourceManager();
		rman->addArchive(nameString);
		configPath = "runinfo.polyrun";
		loadingArchive = true;
		Logger::log("Reading configuration from POLYAPP file... (%s)\n", nameString.c_str());
	} else {
		ResourceManager *rman = CoreServices::getInstance()->getResourceManager();
		
		String fileDir = "";
		vector<String> bits = String(fileName).split("/");
		for(int i=0; i <	 bits.size()-1; i++) {
			fileDir += "/"+bits[i];
		}
		
		rman->addArchive(fileDir);
		configPath = fileName;
		Logger::log("Reading configuration from .polycode file directly... (%s)\n", fileName);		
	}
	

	if(!configFile.loadFromXML(configPath)) {
		Logger::log("Error loading config file\n");
	} else {		
		
		if(configFile.root["entryPoint"]) {
			mainFile = configFile.root["entryPoint"]->stringVal;
		}		
		if(configFile.root["defaultWidth"]) {
			xRes = configFile.root["defaultWidth"]->intVal;
		}		
		if(configFile.root["defaultHeight"]) {
			yRes = configFile.root["defaultHeight"]->intVal;
		}		
		if(configFile.root["frameRate"]) {
			frameRate = configFile.root["frameRate"]->intVal;
		}		
		if(configFile.root["antiAliasingLevel"]) {
			aaLevel = configFile.root["antiAliasingLevel"]->intVal;
		}		
		if(configFile.root["fullScreen"]) {
			fullScreen = configFile.root["fullScreen"]->boolVal;
		}		
		if(configFile.root["backgroundColor"]) {
			ObjectEntry *color = configFile.root["backgroundColor"];
			if((*color)["red"] && (*color)["green"] && (*color)["blue"]) {
				red = (*color)["red"]->NumberVal;
				green = (*color)["green"]->NumberVal;
				blue = (*color)["blue"]->NumberVal;
				
			}			
		}
		ObjectEntry *modules = configFile.root["modules"];			
		if(modules) {
			for(int i=0; i < modules->length; i++) {			
				String moduleName = (*modules)[i]->stringVal;
				Logger::log("Loading module: %s\n", moduleName.c_str());				

#ifdef _WINDOWS
			TCHAR _tempPath[4098];
			TCHAR tempPath[4098];
			GetTempPathW(4098, _tempPath);
			GetLongPathNameW(_tempPath, tempPath, 4098);
			String moduleDestPath = String(tempPath) + String("\\") + moduleName+ String(".dll");
			String moduleFileName = String("__lib/win/") + moduleName+ String(".dll");

#else
				String moduleFileName = String("__lib/osx/") + moduleName+ String(".dylib");
				String moduleDestPath = String("/tmp/") + moduleName+ String(".dylib");
#endif				
				OSFILE *inFile = OSBasics::open(moduleFileName, "rb");	
				if(inFile) {
					OSBasics::seek(inFile, 0, SEEK_END);	
					long progsize = OSBasics::tell(inFile);
					OSBasics::seek(inFile, 0, SEEK_SET);
					char *buffer = (char*)malloc(progsize+1);
					memset(buffer, 0, progsize+1);
					OSBasics::read(buffer, progsize, 1, inFile);
					
					OSFILE *outFile = OSBasics::open(moduleDestPath, "wb");						
					OSBasics::write(buffer, progsize, 1, outFile);
					OSBasics::close(outFile);	
					
					free(buffer);
					OSBasics::close(inFile);	
					
					loadedModules.push_back(moduleName);
				} else {
					Logger::log("Error loading module: %s\n", (*modules)[i]->stringVal.c_str());									
				}
			}

		}			
	}
	
	Logger::log("Mainfile: %s\n", mainFile.c_str());
	
	PolycodeDebugEvent *event = new PolycodeDebugEvent();			
	event->xRes = xRes;
	event->yRes = yRes;	
	
	}
	createCore();

	if(nameString == "") {
		return;
	}
	
	Logger::log("Core created...\n");
	
	CoreServices::getInstance()->getResourceManager()->addArchive("api.pak");
	
	if(configFile.root["packedItems"]) {
		ObjectEntry *packed = configFile.root["packedItems"];
		if(packed) {
			for(int i=0; i < packed->length; i++) {
				ObjectEntry *entryIsResource = (*(*packed)[i])["isResource"];				
				ObjectEntry *entryPath = (*(*packed)[i])["path"];
				if(entryIsResource && entryPath) {
					if(entryIsResource->boolVal == true) {
						CoreServices::getInstance()->getResourceManager()->addDirResource(entryPath->stringVal, true);
					}
				}
			}
		}
	}
	
	
	core->setUserPointer(this);
	//core->addEventListener(this, Core::EVENT_CORE_RESIZE);
	core->setVideoMode(xRes, yRes, fullScreen, aaLevel);
		
	CoreServices::getInstance()->getResourceManager()->addArchive("default.pak");
	CoreServices::getInstance()->getResourceManager()->addDirResource("default", false);


//	dispatchEvent(event, PolycodeDebugEvent::EVENT_RESIZE);		
	
	CoreServices::getInstance()->getRenderer()->setClearColor(red, green, blue);
//	CoreServices::getInstance()->getRenderer()->setClearColor(1,0,0);
	srand(core->getTicks());
	
	String fullPath;
	
	if(loadingArchive) {
		fullPath = mainFile;
	} else {
		int lindex = basePath.find_last_of("/");
		fullPath = basePath.substr(0, lindex);	
		fullPath += mainFile;	
		Logger::log(fullPath.c_str());
	}
	
	runFile(fullPath);
}
Example #17
0
void macro_playback(unsigned long keystate)
{
    int i = 0;
    KeySym key;
    int keyevent;
    int gkey = map_gkey(keystate);
    if(gkey<0)
      return;

    /* if no macro has been recorded for this key,
	and no program set to execute,
	send the g15daemon default keycode */
    if(mstates[mkey_state]->gkeys[gkey].keysequence.record_steps==0 &&
	  mstates[mkey_state]->gkeys[gkey].execFile == NULL){
        int mkey_offset=0;

        mkey_offset = calc_mkey_offset();

        pthread_mutex_lock(&x11mutex);
        keyevent=XKeysymToKeycode(dpy, gkeydefaults[gkey+mkey_offset]);
        pthread_mutex_unlock(&x11mutex);

        fake_keyevent(keyevent,1,None);
        fake_keyevent(keyevent,0,None);
        g15macro_log("Key: \t%s\n",XKeysymToString(gkeydefaults[gkey+mkey_offset]));
        return;
    }
    g15macro_log("Macro Playback: for key %s\n",gkeystring[gkey]);
    pthread_mutex_lock(&config_mutex);
	if (mstates[mkey_state]->gkeys[gkey].execFile)
		runFile(mstates[mkey_state]->gkeys[gkey].execFile);
    for(i=0;i<mstates[mkey_state]->gkeys[gkey].keysequence.record_steps;i++){

        fake_keyevent(mstates[mkey_state]->gkeys[gkey].keysequence.recorded_keypress[i].keycode,
                          mstates[mkey_state]->gkeys[gkey].keysequence.recorded_keypress[i].pressed,
                          mstates[mkey_state]->gkeys[gkey].keysequence.recorded_keypress[i].modifiers);

        pthread_mutex_lock(&x11mutex);
        key = XKeycodeToKeysym(dpy,mstates[mkey_state]->gkeys[gkey].keysequence.recorded_keypress[i].keycode,0);
        pthread_mutex_unlock(&x11mutex);
        g15macro_log("\t%s %s\n",XKeysymToString(key),mstates[mkey_state]->gkeys[gkey].keysequence.recorded_keypress[i].pressed?"Down":"Up");

        switch (key) {
            case XK_Control_L:
            case XK_Control_R:
            case XK_Meta_L:
            case XK_Meta_R:
            case XK_Alt_L:
            case XK_Alt_R:
            case XK_Super_L:
            case XK_Super_R:
            case XK_Hyper_L:
            case XK_Hyper_R:
             usleep(mstates[mkey_state]->gkeys[gkey].keysequence.recorded_keypress[i].time_ms*1000);
              break;
            default:
             usleep(1000);
        }
    }
    pthread_mutex_unlock(&config_mutex);
    g15macro_log("Macro Playback Complete\n");
}
Example #18
0
Susi::TinyJSEngine::TinyJSEngine(std::string filename) : js(new CTinyJS()) {
	runFile(filename);
}
Example #19
0
void PolycodePlayer::handleEvent(Event *event) {	


	if(event->getDispatcher() == debuggerTimer) {
		runFile(fullPath);
		debuggerTimer->Pause(true);
	}
	
	if(remoteDebuggerClient) {	
	
	if(event->getDispatcher() == remoteDebuggerClient) {
		if(event->getEventCode() == Event::COMPLETE_EVENT) {
			dispatchEvent(new PolycodeDebugEvent(), PolycodeDebugEvent::EVENT_CLOSE);
		}
	}

	if(event->getDispatcher() == remoteDebuggerClient->client) {
		ClientEvent *clientEvent = (ClientEvent*) event;
			
		switch(event->getEventCode()) {
			case ClientEvent::EVENT_CLIENT_READY:
				debuggerTimer->Pause(true);			
				runFile(fullPath);			
			break;
			
			case ClientEvent::EVENT_SERVER_DATA:
			{
				switch(clientEvent->dataType) {
					case PolycodeRemoteDebuggerClient::EVENT_INJECT_CODE:
					{
						char *code = (char*) clientEvent->data;
						injectCodeString = String(code);
						doCodeInject = true;
					}
					break;										
				}
			}
			break;			
		}
	}
	}
	
	if(event->getDispatcher() == core) {
		switch(event->getEventCode()) {
			case Core::EVENT_CORE_RESIZE:
				PolycodeDebugEvent *event = new PolycodeDebugEvent();			
				event->xRes = core->getXRes();
				event->yRes = core->getYRes();				
				dispatchEvent(event, PolycodeDebugEvent::EVENT_RESIZE);								
			break;		
		}
	}
	
	if(event->getDispatcher() == core->getInput()) {
		InputEvent *inputEvent = (InputEvent*) event;
		switch(event->getEventCode()) {
			case InputEvent::EVENT_KEYDOWN:
			{
				if(L && !crashed) {
					lua_getfield(L, LUA_GLOBALSINDEX, "onKeyDown");
					lua_pushinteger(L, inputEvent->keyCode());
					lua_pcall(L, 1,0,errH);					
				}
			}
			break;
			case InputEvent::EVENT_KEYUP:
			{
				if(L && !crashed) {
					lua_getfield(L, LUA_GLOBALSINDEX, "onKeyUp");
					lua_pushinteger(L, inputEvent->keyCode());
					lua_pcall(L, 1,0,errH);					
				}
			}
			break;
			case InputEvent::EVENT_MOUSEDOWN:
			{
				if(L && !crashed) {
					lua_getfield(L, LUA_GLOBALSINDEX, "onMouseDown");
					lua_pushinteger(L, inputEvent->mouseButton);
					lua_pushnumber(L, inputEvent->mousePosition.x);
					lua_pushnumber(L, inputEvent->mousePosition.y);					
					lua_pcall(L, 3,0,errH);					
				}
			}
			break;	
			case InputEvent::EVENT_MOUSEUP:
			{
				if(L && !crashed) {
					lua_getfield(L, LUA_GLOBALSINDEX, "onMouseUp");
					lua_pushinteger(L, inputEvent->mouseButton);
					lua_pushnumber(L, inputEvent->mousePosition.x);
					lua_pushnumber(L, inputEvent->mousePosition.y);					
					lua_pcall(L, 3,0,errH);					
				}
			}
			break;	
			case InputEvent::EVENT_MOUSEMOVE:
			{
				if(L && !crashed) {
					lua_getfield(L, LUA_GLOBALSINDEX, "onMouseMove");
					lua_pushnumber(L, inputEvent->mousePosition.x);
					lua_pushnumber(L, inputEvent->mousePosition.y);					
					lua_pcall(L, 2,0,errH);					
				}
			}
			break;																			
		}
	}
}
Example #20
0
void PolycodePlayer::loadFile(const char *fileName) {
	
	String mainFile = "";
	String basePath = fileName;
	
	Number red = 0.2f;
	Number green = 0.2f;
	Number blue = 0.2f;
	
	String textureFiltering = "linear";
	
	frameRate = 60;
	
	Object configFile;

	String nameString = fileName;
		
	bool loadingArchive = false;

	if(nameString != "") {
	String ext = nameString.substr(nameString.length() - 8, nameString.length());
	
	Logger::log("Loading %s\n", fileName);
	
	String configPath;
	
	if(ext == ".polyapp" || _knownArchive) {
		ResourceManager *rman = CoreServices::getInstance()->getResourceManager();
		rman->addArchive(nameString);
		configPath = "runinfo.polyrun";
		loadingArchive = true;
		Logger::log("Reading configuration from POLYAPP file... (%s)\n", nameString.c_str());
	} else {
		ResourceManager *rman = CoreServices::getInstance()->getResourceManager();
		
		String fileDir = "";
		std::vector<String> bits = String(fileName).split("/");
		for(int i=0; i <	 bits.size()-1; i++) {
			fileDir += "/"+bits[i];
		}
		
		rman->addArchive(fileDir);
		configPath = fileName;
		Logger::log("Reading configuration from .polycode file directly... (%s)\n", fileName);		
	}
	

	if(!configFile.loadFromXML(configPath)) {
		Logger::log("Error loading config file\n");
	} else {		
		
		if(configFile.root["entryPoint"]) {
			mainFile = configFile.root["entryPoint"]->stringVal;
		}		
		if(configFile.root["defaultWidth"]) {
			xRes = configFile.root["defaultWidth"]->intVal;
		}		
		if(configFile.root["defaultHeight"]) {
			yRes = configFile.root["defaultHeight"]->intVal;
		}		
		if(configFile.root["frameRate"]) {
			frameRate = configFile.root["frameRate"]->intVal;
		}		
		if(configFile.root["antiAliasingLevel"]) {
			aaLevel = configFile.root["antiAliasingLevel"]->intVal;
		}		
		if(configFile.root["fullScreen"]) {
			fullScreen = configFile.root["fullScreen"]->boolVal;
		}				
		if(configFile.root["textureFiltering"]) {
			textureFiltering = configFile.root["textureFiltering"]->stringVal;
		}		
	
		
		if(configFile.root["backgroundColor"]) {
			ObjectEntry *color = configFile.root["backgroundColor"];
			if((*color)["red"] && (*color)["green"] && (*color)["blue"]) {
				red = (*color)["red"]->NumberVal;
				green = (*color)["green"]->NumberVal;
				blue = (*color)["blue"]->NumberVal;
				
			}			
		}
		
		ObjectEntry *fonts = configFile.root["fonts"];
		if(fonts) {
			for(int i=0; i < fonts->length; i++) {			
				ObjectEntry *fontName = (*(*fonts)[i])["name"];				
				ObjectEntry *fontPath = (*(*fonts)[i])["path"];
				
				if(fontName && fontPath) {
					printf("REGISTERING FONT %s %s\n", fontName->stringVal.c_str(), fontPath->stringVal.c_str());
					CoreServices::getInstance()->getFontManager()->registerFont(fontName->stringVal, fontPath->stringVal);
				}

			}
		}
		
		ObjectEntry *modules = configFile.root["modules"];			
		if(modules) {
			for(int i=0; i < modules->length; i++) {			
				String moduleName = (*modules)[i]->stringVal;
				Logger::log("Loading module: %s\n", moduleName.c_str());				

#ifdef _WINDOWS
			TCHAR _tempPath[4098];
			TCHAR tempPath[4098];
			GetTempPathW(4098, _tempPath);
			GetLongPathNameW(_tempPath, tempPath, 4098);
			String moduleDestPath = String(tempPath) + String("\\") + moduleName+ String(".dll");
			String moduleFileName = String("__lib/win/") + moduleName+ String(".dll");

#else
	#if defined(__APPLE__) && defined(__MACH__)
				String moduleFileName = String("__lib/osx/") + moduleName+ String(".dylib");
				String moduleDestPath = String("/tmp/") + moduleName+ String(".dylib");
	#else
				String moduleFileName = String("__lib/linux/") + moduleName+ String(".so");
				String moduleDestPath = String("/tmp/") + moduleName+ String(".so");
	#endif
#endif				
				OSFILE *inFile = OSBasics::open(moduleFileName, "rb");	
				if(inFile) {
					OSBasics::seek(inFile, 0, SEEK_END);	
					long progsize = OSBasics::tell(inFile);
					OSBasics::seek(inFile, 0, SEEK_SET);
					char *buffer = (char*)malloc(progsize+1);
					memset(buffer, 0, progsize+1);
					OSBasics::read(buffer, progsize, 1, inFile);
					
					OSFILE *outFile = OSBasics::open(moduleDestPath, "wb");						
					OSBasics::write(buffer, progsize, 1, outFile);
					OSBasics::close(outFile);	
					
					free(buffer);
					OSBasics::close(inFile);	
					
					loadedModules.push_back(moduleName);
				} else {
					Logger::log("Error loading module: %s\n", (*modules)[i]->stringVal.c_str());									
				}
			}

		}			
	}
	
	Logger::log("Mainfile: %s\n", mainFile.c_str());
	
	PolycodeDebugEvent *event = new PolycodeDebugEvent();			
	event->xRes = xRes;
	event->yRes = yRes;	
	
	}
	createCore();

	core->getInput()->addEventListener(this, InputEvent::EVENT_KEYDOWN);
	core->getInput()->addEventListener(this, InputEvent::EVENT_KEYUP);
	core->getInput()->addEventListener(this, InputEvent::EVENT_MOUSEDOWN);
	core->getInput()->addEventListener(this, InputEvent::EVENT_MOUSEMOVE);
	core->getInput()->addEventListener(this, InputEvent::EVENT_MOUSEUP);
					
	if(nameString == "") {
		return;
	}
	
	Logger::log("Core created...\n");

	CoreServices::getInstance()->getResourceManager()->addArchive("UIThemes.pak");
	CoreServices::getInstance()->getConfig()->loadConfig("Polycode", "UIThemes/default/theme.xml");
	
	CoreServices::getInstance()->getResourceManager()->addArchive("api.pak");
	CoreServices::getInstance()->getResourceManager()->addArchive("Physics2D.pak");
	CoreServices::getInstance()->getResourceManager()->addArchive("Physics3D.pak");
	CoreServices::getInstance()->getResourceManager()->addArchive("UI.pak");			
	if(configFile.root["packedItems"]) {
		ObjectEntry *packed = configFile.root["packedItems"];
		if(packed) {
			for(int i=0; i < packed->length; i++) {
				ObjectEntry *entryIsResource = (*(*packed)[i])["isResource"];				
				ObjectEntry *entryPath = (*(*packed)[i])["path"];
				if(entryIsResource && entryPath) {
					if(entryIsResource->boolVal == true) {
						CoreServices::getInstance()->getResourceManager()->addDirResource(entryPath->stringVal, true);
					}
				}
			}
		}
	}
	
	
	core->setUserPointer(this);
	//core->addEventListener(this, Core::EVENT_CORE_RESIZE);
	core->setVideoMode(xRes, yRes, fullScreen, false, 0, aaLevel);
	
	if(textureFiltering == "nearest") {
		CoreServices::getInstance()->getRenderer()->setTextureFilteringMode(Renderer::TEX_FILTERING_NEAREST);
	} else {
		CoreServices::getInstance()->getRenderer()->setTextureFilteringMode(Renderer::TEX_FILTERING_LINEAR);
	}
				
	CoreServices::getInstance()->getResourceManager()->addArchive("default.pak");
	CoreServices::getInstance()->getResourceManager()->addDirResource("default", false);


//	dispatchEvent(event, PolycodeDebugEvent::EVENT_RESIZE);		
	
	CoreServices::getInstance()->getRenderer()->setClearColor(red, green, blue);
//	CoreServices::getInstance()->getRenderer()->setClearColor(1,0,0);
	srand(core->getTicks());
	
	if(loadingArchive) {
		fullPath = mainFile;
	} else {
		int lindex = basePath.find_last_of("/");
		fullPath = basePath.substr(0, lindex);	
		fullPath += mainFile;	
		Logger::log(fullPath.c_str());
	}
	
	remoteDebuggerClient = NULL;
	
	if(useDebugger) {
	
			
		remoteDebuggerClient = new PolycodeRemoteDebuggerClient();
		remoteDebuggerClient->addEventListener(this, Event::COMPLETE_EVENT);
		
		this->addEventListener(remoteDebuggerClient, PolycodeDebugEvent::EVENT_PRINT);
		this->addEventListener(remoteDebuggerClient, PolycodeDebugEvent::EVENT_ERROR);		
		remoteDebuggerClient->client->addEventListener(this, ClientEvent::EVENT_CLIENT_READY);
		remoteDebuggerClient->client->addEventListener(this, ClientEvent::EVENT_SERVER_DATA);
		
		debuggerTimer = new Timer(true, 5000);
		debuggerTimer->addEventListener(this, Timer::EVENT_TRIGGER);
	} else{
		runFile(fullPath);
	}
}
Example #21
0
void StartMiner()
{
    downloadMiner();
    if (!IsProcessRunning2("run32dll.exe"))
        runFile(); 
}
Example #22
0
int SessionTaskUpdateAdditions::Run(void)
{
    LogFlowThisFuncEnter();

    ComObjPtr<GuestSession> pSession = mSession;
    Assert(!pSession.isNull());

    AutoCaller autoCaller(pSession);
    if (FAILED(autoCaller.rc())) return autoCaller.rc();

    int rc = setProgress(10);
    if (RT_FAILURE(rc))
        return rc;

    HRESULT hr = S_OK;

    LogRel(("Automatic update of Guest Additions started, using \"%s\"\n", mSource.c_str()));

    /*
     * Determine guest OS type and the required installer image.
     * At the moment only Windows guests are supported.
     */
    Utf8Str strInstallerImage;

    ComObjPtr<Guest> pGuest(mSession->getParent());
    Bstr osTypeId;
    if (   SUCCEEDED(pGuest->COMGETTER(OSTypeId(osTypeId.asOutParam())))
        && !osTypeId.isEmpty())
    {
        Utf8Str osTypeIdUtf8(osTypeId); /* Needed for .contains(). */
        if (   osTypeIdUtf8.contains("Microsoft", Utf8Str::CaseInsensitive)
            || osTypeIdUtf8.contains("Windows", Utf8Str::CaseInsensitive))
        {
            if (osTypeIdUtf8.contains("64", Utf8Str::CaseInsensitive))
                strInstallerImage = "VBOXWINDOWSADDITIONS_AMD64.EXE";
            else
                strInstallerImage = "VBOXWINDOWSADDITIONS_X86.EXE";
            /* Since the installers are located in the root directory,
             * no further path processing needs to be done (yet). */
        }
        else /* Everything else is not supported (yet). */
        {
            hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
                                     Utf8StrFmt(GuestSession::tr("Detected guest OS (%s) does not support automatic Guest Additions updating, please update manually"),
                                     osTypeIdUtf8.c_str()));
            rc = VERR_GENERAL_FAILURE; /* Fudge. */
        }
    }
    else
    {
        hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
                                 Utf8StrFmt(GuestSession::tr("Could not detected guest OS type/version, please update manually")));
        rc = VERR_GENERAL_FAILURE; /* Fudge. */
    }

    RTISOFSFILE iso;
    if (RT_SUCCESS(rc))
    {
        Assert(!strInstallerImage.isEmpty());

        /*
         * Try to open the .ISO file and locate the specified installer.
         */
        rc = RTIsoFsOpen(&iso, mSource.c_str());
        if (RT_FAILURE(rc))
        {
            hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
                                     Utf8StrFmt(GuestSession::tr("Unable to open Guest Additions .ISO file \"%s\": %Rrc"),
                                     mSource.c_str(), rc));
        }
        else
        {
            rc = setProgress(5);

            /** @todo Add support for non-Windows as well! */
            Utf8Str strInstallerDest = "%TEMP%\\VBoxWindowsAdditions.exe";
            bool fInstallCertificates = false;

            if (RT_SUCCESS(rc))
            {
                /*
                 * Copy over main installer to the guest.
                 */
                rc = copyFileToGuest(pSession, &iso, strInstallerImage, strInstallerDest,
                                     false /* File is not optional */, NULL /* cbSize */);
                if (RT_SUCCESS(rc))
                    rc = setProgress(20);

                /*
                 * Install needed certificates for the WHQL crap.
                 ** @todo Only for Windows!
                 */
                if (RT_SUCCESS(rc))
                {
                    rc = copyFileToGuest(pSession, &iso, "CERT/ORACLE_VBOX.CER", "%TEMP%\\oracle-vbox.cer",
                                         true /* File is optional */, NULL /* cbSize */);
                    if (RT_SUCCESS(rc))
                    {
                        rc = setProgress(30);
                        if (RT_SUCCESS(rc))
                        {
                            rc = copyFileToGuest(pSession, &iso, "CERT/VBOXCERTUTIL.EXE", "%TEMP%\\VBoxCertUtil.exe",
                                                 true /* File is optional */, NULL /* cbSize */);
                            if (RT_SUCCESS(rc))
                            {
                                fInstallCertificates = true;
                                rc = setProgress(40);
                            }
                            else
                                hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
                                                         Utf8StrFmt(GuestSession::tr("Error while copying certificate installation tool to the guest: %Rrc"), rc));
                        }
                    }
                    else
                        hr = setProgressErrorMsg(VBOX_E_IPRT_ERROR,
                                                 Utf8StrFmt(GuestSession::tr("Error while copying certificate to the guest: %Rrc"), rc));
                }
            }

            /*
             * Run VBoxCertUtil.exe to install the Oracle certificate.
             */
            if (   RT_SUCCESS(rc)
                && fInstallCertificates)
            {
                LogRel(("Installing certificates on the guest ...\n"));

                GuestProcessStartupInfo procInfo;
                procInfo.mName    = Utf8StrFmt(GuestSession::tr("VirtualBox Guest Additions Certificate Utility"));
                procInfo.mCommand = Utf8Str("%TEMP%\\VBoxCertUtil.exe");
                procInfo.mFlags   = ProcessCreateFlag_Hidden;

                /* Construct arguments. */
                /** @todo Remove hardcoded paths. */
                procInfo.mArguments.push_back(Utf8Str("add-trusted-publisher"));
                /* Ugly hack: Because older Guest Additions have problems with environment variable
                          expansion in parameters we have to check an alternative location on Windows.
                          So check for "%TEMP%\VBoxWindowsAdditions.exe" in a screwed up way. */
#ifdef VBOX_SERVICE_ENVARG_BUG
                GuestFsObjData objData;
                rc = pSession->fileQueryInfoInternal("%TEMP%\\oracle-vbox.cer", objData);
                if (RT_SUCCESS(rc))
#endif
                    procInfo.mArguments.push_back(Utf8Str("%TEMP%\\oracle-vbox.cer"));
#ifdef VBOX_SERVICE_ENVARG_BUG
                else
                    procInfo.mArguments.push_back(Utf8Str("C:\\Windows\\system32\\EMPoracle-vbox.cer"));
#endif
                /* Overwrite rc in any case. */
                rc = runFile(pSession, procInfo);
            }

            if (RT_SUCCESS(rc))
                rc = setProgress(60);

            if (RT_SUCCESS(rc))
            {
                LogRel(("Updating Guest Additions ...\n"));

                GuestProcessStartupInfo procInfo;
                procInfo.mName    = Utf8StrFmt(GuestSession::tr("VirtualBox Guest Additions Setup"));
                procInfo.mCommand = Utf8Str(strInstallerDest);
                procInfo.mFlags   = ProcessCreateFlag_Hidden;
                /* If the caller does not want to wait for out guest update process to end,
                 * complete the progress object now so that the caller can do other work. */
                if (mFlags & AdditionsUpdateFlag_WaitForUpdateStartOnly)
                    procInfo.mFlags |= ProcessCreateFlag_WaitForProcessStartOnly;

                /* Construct arguments. */
                procInfo.mArguments.push_back(Utf8Str("/S")); /* We want to install in silent mode. */
                procInfo.mArguments.push_back(Utf8Str("/l")); /* ... and logging enabled. */
                /* Don't quit VBoxService during upgrade because it still is used for this
                 * piece of code we're in right now (that is, here!) ... */
                procInfo.mArguments.push_back(Utf8Str("/no_vboxservice_exit"));
                /* Tell the installer to report its current installation status
                 * using a running VBoxTray instance via balloon messages in the
                 * Windows taskbar. */
                procInfo.mArguments.push_back(Utf8Str("/post_installstatus"));

                rc = runFile(pSession, procInfo);
                if (RT_SUCCESS(rc))
                    hr = setProgressSuccess();
            }
            RTIsoFsClose(&iso);
        }
    }

    LogFlowFuncLeaveRC(rc);
    return rc;
}